The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* <nowiki> */
/* Bharat Mitra: redirect special pages. On Special:DoubleRedirects it adds a
   one click fix for every double redirect. On Special:BrokenRedirects it adds
   batch selection with speedy deletion nomination for all users and batch
   deletion for administrators. Shown only when Bharat Mitra is enabled.
   All panel updates go through fresh document lookups by id, and all clicks
   are handled by delegation from the document: the visible panel can be a
   re-serialised copy of the inserted one, so element references captured at
   build time may point at detached nodes that are no longer on the page. */
( function () {
	'use strict';
	var BM = window.BharatMitra;
	var started = false;
	var doubleCtx = null;
	var brokenCtx = null;
	var delegationBound = false;

	function bindDelegation() {
		if ( delegationBound ) { return; }
		delegationBound = true;
		$( document ).on( 'click', '#bm-fixall-btn', function () { if ( doubleCtx ) { doubleCtx.onFix(); } } );
		$( document ).on( 'click', '#bm-selall-btn', function () { if ( brokenCtx ) { brokenCtx.onSelAll(); } } );
		$( document ).on( 'click', '#bm-selnone-btn', function () { if ( brokenCtx ) { brokenCtx.onSelNone(); } } );
		$( document ).on( 'click', '#bm-nominate-btn', function () { if ( brokenCtx ) { brokenCtx.onNominate(); } } );
		$( document ).on( 'click', '#bm-delete-btn', function () { if ( brokenCtx ) { brokenCtx.onDelete(); } } );
		$( document ).on( 'change', '#bm-specialredirects .bm-broken-check', function () { if ( brokenCtx ) { brokenCtx.onDisarm(); } } );
	}
	function byId( id ) {
		var n = document.getElementById( id );
		return n ? $( n ) : $();
	}
	function setText( id, text ) { byId( id ).text( text ); }
	function isSysop() {
		return ( mw.config.get( 'wgUserGroups' ) || [] ).indexOf( 'sysop' ) !== -1;
	}
	function specialName() {
		return mw.config.get( 'wgCanonicalSpecialPageName' ) || '';
	}
	function queryPageAll( name ) {
		var out = [];
		function step( cont ) {
			var params = {
				action: 'query', list: 'querypage', qppage: name,
				qplimit: 500, formatversion: 2
			};
			if ( cont ) { params.qpcontinue = cont; }
			return BM.core.api().get( params ).then( function ( r ) {
				var qp = ( r.query && r.query.querypage ) || {};
				( qp.results || [] ).forEach( function ( x ) { out.push( x ); } );
				if ( r.continue && r.continue.qpcontinue ) {
					return step( r.continue.qpcontinue );
				}
				return out;
			} );
		}
		return step( null );
	}
	function finalTarget( title ) {
		return BM.core.api().get( {
			action: 'query', titles: title, redirects: 1, formatversion: 2
		} ).then( function ( r ) {
			var pages = ( r.query && r.query.pages ) || [];
			return pages.length ? pages[ 0 ].title : title;
		} );
	}
	function wait( ms ) {
		return new $.Deferred( function ( d ) { setTimeout( d.resolve, ms ); } ).promise();
	}
	function pageLink( title ) {
		return $( '<a>' ).attr( 'href', mw.util.getUrl( title ) ).text( title );
	}
	function makePanel( heading ) {
		var host = document.querySelector( '#mw-content-text' );
		if ( !host || document.getElementById( 'bm-specialredirects' ) ) { return false; }
		var box = $( '<div>' ).attr( 'id', 'bm-specialredirects' )
			.attr( 'style', 'border:1px solid #a2a9b1;background:#f8f9fa;padding:10px 14px;margin:0 0 14px 0;font-size:95%;' );
		box.append( $( '<div>' ).append( $( '<strong>' ).text( heading ) ) );
		box.append( $( '<div>' ).attr( 'id', 'bm-sr-status' ).attr( 'style', 'margin:6px 0;' ).text( 'Loading…' ) );
		host.insertBefore( box[ 0 ], host.firstChild );
		return true;
	}
	function panelBox() { return byId( 'bm-specialredirects' ); }
	function setStatus( text ) { setText( 'bm-sr-status', text ); }
	function makeTable( headers ) {
		var table = $( '<table>' ).addClass( 'wikitable' ).attr( 'style', 'width:100%;background:#fff;' );
		var tr = $( '<tr>' );
		headers.forEach( function ( h ) { tr.append( $( '<th>' ).text( h ) ); } );
		table.append( tr );
		return table;
	}

	/* ---------------- Double redirects ---------------- */
	function runDouble() {
		queryPageAll( 'DoubleRedirects' ).then( function ( rows ) {
			if ( !rows.length ) {
				setStatus( 'Double redirects: 0. There is nothing to fix.' );
				return;
			}
			setStatus( 'Double redirects: ' + rows.length + '. The final target of each page is found live when the table loads.' );
			var table = makeTable( [ 'Page', 'Final target', 'Status' ] );
			panelBox().append( table );
			var rowInfo = [];
			var pending = rows.length;
			rows.forEach( function ( r, idx ) {
				var tr = $( '<tr>' );
				tr.append( $( '<td>' ).append( pageLink( r.title ) ) );
				tr.append( $( '<td>' ).attr( 'id', 'bm-double-target-' + idx ).text( '…' ) );
				tr.append( $( '<td>' ).attr( 'id', 'bm-double-status-' + idx ).text( '' ) );
				table.append( tr );
				rowInfo[ idx ] = { title: r.title, target: null };
				finalTarget( r.title ).then( function ( fin ) {
					rowInfo[ idx ].target = fin;
					setText( 'bm-double-target-' + idx, fin );
				} ).catch( function () {
					setText( 'bm-double-target-' + idx, 'Could not be found' );
				} ).then( function () {
					pending--;
					if ( !pending ) { addFixButton( rowInfo ); }
				} );
			} );
		} ).catch( function () {
			setStatus( 'The double redirect list could not be loaded.' );
		} );
	}
	function addFixButton( rowInfo ) {
		var btn = $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'bm-fixall-btn' ).addClass( 'bm-btn bm-primary' )
			.attr( 'style', 'margin-top:10px;' ).text( 'Fix all double redirects (' + rowInfo.length + ')' );
		panelBox().append( btn );
		var armed = false;
		doubleCtx = { onFix: function () {
			var liveBtn = byId( 'bm-fixall-btn' );
			if ( !armed ) {
				armed = true;
				liveBtn.text( 'Confirm: fix all ' + rowInfo.length + ' double redirects' );
				setStatus( 'Each page will be changed to point directly to its final target. Click the button again to confirm.' );
				return;
			}
			liveBtn.prop( 'disabled', true );
			var fixed = 0, failed = 0, skipped = 0;
			var chain = $.Deferred().resolve().promise();
			rowInfo.forEach( function ( info, idx ) {
				chain = chain.then( function () {
					var sc = 'bm-double-status-' + idx;
					if ( !info.target || info.target === info.title ) {
						skipped++; setText( sc, 'Skipped' ); return null;
					}
					setText( sc, 'Working…' );
					return BM.core.getPage( info.title ).then( function ( p ) {
						if ( !p.exists ) { skipped++; setText( sc, 'Skipped: page missing' ); return null; }
						var lines = p.content.split( '\n' );
						if ( !/^\s*#\s*REDIRECT/i.test( lines[ 0 ] ) ) {
							skipped++; setText( sc, 'Skipped: not a redirect' ); return null;
						}
						lines[ 0 ] = '#REDIRECT [[' + info.target + ']]';
						return BM.core.savePage( info.title, lines.join( '\n' ),
							'Fixed a double redirect (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', p.revid )
							.then( function () { fixed++; setText( sc, 'Fixed' ); } );
					} ).catch( function () {
						failed++; setText( sc, 'Failed' );
					} ).then( function () { return wait( 300 ); } );
				} );
			} );
			chain.then( function () {
				var msg = 'Done. Fixed: ' + fixed + ', skipped: ' + skipped + ', failed: ' + failed +
					'. This special page list is cached by the wiki, so fixed pages can stay listed here for some time.';
				setStatus( msg );
				mw.notify( msg, { type: failed ? 'warn' : 'success' } );
			} );
		} };
	}

	/* ---------------- Broken redirects ---------------- */
	function targetText( r ) {
		var d = r.databaseResult || {};
		var t = String( d.rd_title || '' ).replace( /_/g, ' ' );
		if ( !t ) { return ''; }
		if ( d.rd_fragment ) { t += '#' + String( d.rd_fragment ).replace( /_/g, ' ' ); }
		return t;
	}
	function runBroken() {
		queryPageAll( 'BrokenRedirects' ).then( function ( rows ) {
			if ( !rows.length ) {
				setStatus( 'Broken redirects: 0. There is nothing to do.' );
				return;
			}
			setStatus( 'Broken redirects: ' + rows.length + '. Select the pages, then nominate them for speedy deletion' +
				( isSysop() ? ' or, as an administrator, delete them directly.' : '.' ) );
			var table = makeTable( [ '', 'Page', 'Target (does not exist)', 'Status' ] );
			panelBox().append( table );
			var items = [];
			rows.forEach( function ( r, idx ) {
				var cb = $( '<input>' ).attr( 'type', 'checkbox' ).attr( 'id', 'bm-broken-cb-' + idx ).addClass( 'bm-broken-check' );
				var tr = $( '<tr>' );
				tr.append( $( '<td>' ).append( cb ) );
				tr.append( $( '<td>' ).append( pageLink( r.title ) ) );
				tr.append( $( '<td>' ).text( targetText( r ) ) );
				tr.append( $( '<td>' ).attr( 'id', 'bm-broken-status-' + idx ).text( '' ) );
				table.append( tr );
				items.push( { title: r.title, idx: idx } );
			} );
			var controls = $( '<div>' ).attr( 'style', 'margin-top:10px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;' );
			controls.append( $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'bm-selall-btn' ).addClass( 'bm-btn' ).text( 'Select all' ) );
			controls.append( $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'bm-selnone-btn' ).addClass( 'bm-btn' ).text( 'Select none' ) );
			var notifyLabel = $( '<label>' ).attr( 'style', 'font-size:13px;' );
			notifyLabel.append( $( '<input>' ).attr( 'type', 'checkbox' ).attr( 'id', 'bm-notify-cb' ),
				document.createTextNode( ' Notify creators (nomination only)' ) );
			controls.append( notifyLabel );
			controls.append( $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'bm-nominate-btn' ).addClass( 'bm-btn bm-primary' )
				.text( 'Nominate selected for speedy deletion' ) );
			if ( isSysop() ) {
				controls.append( $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'bm-delete-btn' ).addClass( 'bm-btn' )
					.attr( 'style', 'background:#b03a2e;border-color:#b03a2e;color:#fff;font-weight:bold;' )
					.text( 'Delete selected (admin)' ) );
			}
			panelBox().append( controls );
			function selected() {
				return items.filter( function ( i ) {
					var n = document.getElementById( 'bm-broken-cb-' + i.idx );
					return n && n.checked;
				} );
			}
			function setBusy( b ) {
				byId( 'bm-nominate-btn' ).prop( 'disabled', b );
				byId( 'bm-delete-btn' ).prop( 'disabled', b );
				byId( 'bm-selall-btn' ).prop( 'disabled', b );
				byId( 'bm-selnone-btn' ).prop( 'disabled', b );
			}
			var armedNom = false, armedDel = false;
			function disarm() {
				armedNom = false; armedDel = false;
				byId( 'bm-nominate-btn' ).text( 'Nominate selected for speedy deletion' );
				byId( 'bm-delete-btn' ).text( 'Delete selected (admin)' );
			}
			function onNominate() {
				var sel = selected();
				if ( !sel.length ) { mw.notify( 'Select at least one page first.', { type: 'warn' } ); return; }
				if ( !armedNom ) {
					armedNom = true;
					byId( 'bm-nominate-btn' ).text( 'Confirm: nominate ' + sel.length + ' selected' );
					setStatus( 'These pages will be nominated for speedy deletion (criterion G8). Click the button again to confirm.' );
					return;
				}
				disarm();
				setBusy( true );
				var notifyNode = document.getElementById( 'bm-notify-cb' );
				var doNotify = !!( notifyNode && notifyNode.checked );
				var done = 0, skipped = 0, failed = 0;
				var chain = $.Deferred().resolve().promise();
				sel.forEach( function ( item ) {
					chain = chain.then( function () {
						var sc = 'bm-broken-status-' + item.idx;
						setText( sc, 'Working…' );
						return BM.core.getPage( item.title ).then( function ( p ) {
							if ( !p.exists ) { skipped++; setText( sc, 'Skipped: page missing' ); return null; }
							if ( /\{\{\s*(?:subst:)?db/i.test( p.content ) ) {
								skipped++; setText( sc, 'Skipped: already nominated' ); return null;
							}
							var tag = '{{subst:db-g8}}';
							var nl = p.content.indexOf( '\n' );
							var firstLine = nl === -1 ? p.content : p.content.slice( 0, nl );
							var newContent;
							if ( /^\s*#\s*REDIRECT/i.test( firstLine ) && nl !== -1 ) {
								newContent = firstLine + '\n' + tag + p.content.slice( nl );
							} else {
								newContent = tag + '\n' + p.content;
							}
							return BM.core.savePage( item.title, newContent,
								'Nominated for speedy deletion (G8) (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', p.revid )
								.then( function () {
									done++; setText( sc, 'Nominated' );
									if ( !doNotify ) { return null; }
									var block = '{{subst:Db-notice|' + BM.core.cleanParam( item.title ) + '}}\n' + BM.SIG;
									return BM.core.notifyCreator( item.title, block,
										'Speedy deletion notice (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])' );
								} );
						} ).catch( function () {
							failed++; setText( sc, 'Failed' );
						} ).then( function () { return wait( 300 ); } );
					} );
				} );
				chain.then( function () {
					setBusy( false );
					var msg = 'Done. Nominated: ' + done + ', skipped: ' + skipped + ', failed: ' + failed + '.';
					setStatus( msg );
					mw.notify( msg, { type: failed ? 'warn' : 'success' } );
				} );
			}
			function onDelete() {
				var sel = selected();
				if ( !sel.length ) { mw.notify( 'Select at least one page first.', { type: 'warn' } ); return; }
				if ( !armedDel ) {
					armedDel = true;
					byId( 'bm-delete-btn' ).text( 'Confirm: delete ' + sel.length + ' selected' );
					setStatus( 'These pages will be deleted. This cannot be undone from this page. Click the button again to confirm.' );
					return;
				}
				disarm();
				setBusy( true );
				var done = 0, failed = 0;
				var chain = $.Deferred().resolve().promise();
				sel.forEach( function ( item ) {
					chain = chain.then( function () {
						var sc = 'bm-broken-status-' + item.idx;
						setText( sc, 'Working…' );
						return BM.core.api().postWithToken( 'delete', {
							action: 'delete', title: item.title,
							reason: 'Broken redirect to a page that does not exist (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])',
							format: 'json'
						} ).then( function () {
							done++; setText( sc, 'Deleted' );
							var n = document.getElementById( 'bm-broken-cb-' + item.idx );
							if ( n ) { n.checked = false; }
						} ).catch( function () {
							failed++; setText( sc, 'Failed' );
						} ).then( function () { return wait( 700 ); } );
					} );
				} );
				chain.then( function () {
					setBusy( false );
					var msg = 'Done. Deleted: ' + done + ', failed: ' + failed +
						'. This special page list is cached by the wiki, so deleted pages can stay listed here for some time.';
					setStatus( msg );
					mw.notify( msg, { type: failed ? 'warn' : 'success' } );
				} );
			}
			brokenCtx = {
				onSelAll: function () {
					items.forEach( function ( i ) {
						var n = document.getElementById( 'bm-broken-cb-' + i.idx );
						if ( n ) { n.checked = true; }
					} );
				},
				onSelNone: function () {
					items.forEach( function ( i ) {
						var n = document.getElementById( 'bm-broken-cb-' + i.idx );
						if ( n ) { n.checked = false; }
					} );
				},
				onNominate: onNominate,
				onDelete: onDelete,
				onDisarm: disarm
			};
		} ).catch( function () {
			setStatus( 'The broken redirect list could not be loaded.' );
		} );
	}

	function check() {
		if ( started ) { return; }
		if ( mw.config.get( 'wgNamespaceNumber' ) !== -1 ) { return; }
		var name = specialName();
		if ( name !== 'BrokenRedirects' && name !== 'DoubleRedirects' ) { return; }
		started = true;
		bindDelegation();
		$( function () {
			if ( name === 'DoubleRedirects' ) {
				if ( makePanel( 'Bharat Mitra: double redirect fixer' ) ) { runDouble(); }
			} else {
				if ( makePanel( 'Bharat Mitra: broken redirect tools' ) ) { runBroken(); }
			}
		} );
	}

	BM.register( 'specialredirects', {
		open: check,
		check: check
	} );
}() );
/* </nowiki> */