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: deletion discussion module (nominate, vote, close, relist) */
( function () {
	'use strict';
	var BM = window.BharatMitra;
	var AFD = 'Bharatpedia:Articles for deletion';
	var MFD = 'Bharatpedia:Miscellany for deletion';
	var MONTHS = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
	function ordinal( n ) {
		var s = [ 'th', 'st', 'nd', 'rd' ], v = n % 100;
		return n + ( s[ ( v - 20 ) % 10 ] || s[ v ] || s[ 0 ] );
	}
	function discussionName( title, n ) {
		return title + ( n && n > 1 ? ' (' + ordinal( n ) + ' nomination)' : '' );
	}
	function discussionTitle( title, n ) {
		return AFD + '/' + discussionName( title, n );
	}
	function buildBanner( name ) {
		/* For a renomination, the discussion page name (numbered suffix
		   included) goes into the banner, as the afd template itself directs. */
		return name ? '{{subst:afd|' + name + '}}' : '{{subst:afd}}';
	}
	function findDiscussion( title ) {
		/* First free discussion page name: the plain name, then
		   (2nd nomination), (3rd nomination), and so on. This is what lets
		   an article be nominated again after an earlier discussion closed. */
		var n = 1;
		function step() {
			var disc = discussionTitle( title, n );
			return BM.core.getPage( disc ).then( function ( p ) {
				if ( !p.exists ) {
					return { n: n, disc: disc, prev: n > 1 ? discussionTitle( title, n - 1 ) : null };
				}
				n++;
				if ( n > 20 ) { throw new Error( 'Too many previous deletion discussions for this page.' ); }
				return step();
			} );
		}
		return step();
	}
	function logTitle() {
		var d = new Date();
		return AFD + '/Log/' + d.getFullYear() + ' ' + MONTHS[ d.getMonth() ] + ' ' + d.getDate();
	}
	function createDiscussion( disc, title, reason, prev ) {
		var statement = reason;
		if ( prev ) {
			statement = 'This is a renomination. The previous discussion is at [[' + prev + ']]. ' + statement;
		}
		var text = '{{subst:afd2|pg=' + BM.core.cleanParam( title ) +
			'|text=' + statement + ' ' + BM.SIG + '}}';
		return BM.core.savePage( disc, text,
			'Deletion discussion nomination (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])' );
	}
	function addToLog( name ) {
		/* appendToPage creates the log page holding just this entry if it is missing.
		   afd3 needs the discussion page name, numbered suffix included. */
		return BM.core.appendToPage( logTitle(), '{{subst:afd3|pg=' + BM.core.cleanParam( name ) + '}}',
			'Added a deletion nomination to the log (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])' );
	}
	function notifyBlock( title, disc ) {
		return '== Nomination of [[:' + title + ']] for deletion ==\n' +
			'Hello. The page [[:' + title + ']] has been nominated for deletion. ' +
			'You are welcome to take part in the discussion at [[' + disc + ']] ' +
			'and to improve the page in the meantime. Please do not remove the deletion notice ' +
			'from the page while the discussion is in progress.\n' + BM.SIG;
	}
	function nominationDialog() {
		var title = mw.config.get( 'wgPageName' ).replace( /_/g, ' ' );
		BM.core.getConfig().then( function ( cfg ) {
			BM.core.dialog( {
				title: 'Put in deletion discussion',
				help: 'Page: ' + title + '. A deletion notice will be placed on the page, a discussion page will be created under Bharatpedia:Articles for deletion, the nomination will be added to today\'s log, and the creator will be notified.',
				fields: [
					{ name: 'reason', label: 'Reason for the discussion', type: 'textarea', rows: 3, required: true },
					{ name: 'notify', label: 'Notify the creator', type: 'checkbox', value: cfg.speedyNotify !== false }
				],
				preview: function () {
					return '\'\'A deletion discussion banner will be placed at the top of this page. ' +
						'A discussion page will be created under [[Bharatpedia:Articles for deletion]] ' +
						'(with a numbered name such as "(2nd nomination)" if the page has been nominated before) ' +
						'and the nomination will be added to today\'s log.\'\'';
				},
				previewTitle: function () { return title; },
				submitLabel: 'Start the discussion',
				success: 'The page has been nominated for deletion.',
				onSubmit: function ( v ) {
					var reason = BM.core.cleanParam( v.reason );
					return BM.core.getPage( title ).then( function ( p ) {
						if ( !p.exists ) { throw new Error( 'This page does not exist.' ); }
						if ( /\{\{\s*(subst:)?(afd|Article for deletion)/i.test( p.content ) ) {
							throw new Error( 'This page already has a deletion discussion notice.' );
						}
						return findDiscussion( title ).then( function ( found ) {
							var name = discussionName( title, found.n );
							var banner = buildBanner( found.n > 1 ? name : null );
							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' + banner + p.content.slice( nl );
							} else {
								newContent = banner + '\n' + p.content;
							}
							return BM.core.savePage( title, newContent,
								'Nominated for deletion discussion (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', p.revid ).then( function () {
								return createDiscussion( found.disc, title, reason, found.prev ).then( function () {
									return addToLog( name ).then( function () {
										if ( !v.notify ) { return null; }
										return BM.core.notifyCreator( title, notifyBlock( title, found.disc ),
											'Deletion discussion notice (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])' ).then( function ( status ) {
											if ( status === 'skipped' || status === 'failed' ) {
												mw.notify( 'The page has been nominated, but the creator could not be notified (no local account for the creator).', { type: 'warn' } );
											}
											return null;
										} );
									} );
								} );
							} );
						} );
					} );
				}
			} );
		} );
	}

	/* ---------- tools for a discussion page itself: vote, close, relist ---------- */
	function isSysop() {
		return ( mw.config.get( 'wgUserGroups' ) || [] ).indexOf( 'sysop' ) !== -1;
	}
	function venueInfo() {
		var pn = mw.config.get( 'wgPageName' ).replace( /_/g, ' ' );
		if ( pn.indexOf( AFD + '/' ) === 0 ) {
			return { key: 'afd', venue: AFD, top: 'Afd top', bottom: 'Afd bottom', disc: pn };
		}
		if ( pn.indexOf( MFD + '/' ) === 0 ) {
			return { key: 'mfd', venue: MFD, top: 'Mfd top', bottom: 'Mfd bottom', disc: pn };
		}
		return null;
	}
	function subjectOf( v, content ) {
		var m = content.match( /^===\s*\[\[:?([^\]|]+)(?:\|[^\]]*)?\]\]\s*===/m );
		if ( m ) { return m[ 1 ].trim(); }
		var s = v.disc.slice( v.venue.length + 1 );
		return s.replace( /\s*\(\d+(?:st|nd|rd|th) nomination\)\s*$/, '' );
	}
	function talkTitle( title ) {
		var i = title.indexOf( ':' );
		if ( i === -1 ) { return 'Talk:' + title; }
		var ns = title.slice( 0, i ), rest = title.slice( i + 1 );
		if ( ns === 'Talk' ) { return title; }
		return ns + ' talk:' + rest;
	}
	function deletePage( title, reason ) {
		return BM.core.api().postWithToken( 'delete', {
			action: 'delete', title: title, reason: reason, format: 'json'
		} ).then( function ( r ) {
			if ( r && r.delete ) { return r; }
			throw new Error( 'Could not delete ' + title + '.' );
		} );
	}
	function removeAfdBanner( subject ) {
		/* Removes the deletion notice block from the article and reports the
		   dated-template values, which the talk page record needs. */
		return BM.core.getPage( subject ).then( function ( p ) {
			if ( !p.exists ) { return null; }
			var info = null;
			var dm = p.content.match( /\{\{Article for deletion\/dated\|([^}]*)\}\}/ );
			if ( dm ) {
				info = {};
				dm[ 1 ].split( '|' ).forEach( function ( kv ) {
					var e = kv.indexOf( '=' );
					if ( e > 0 ) { info[ kv.slice( 0, e ).trim() ] = kv.slice( e + 1 ).trim(); }
				} );
			}
			var out = p.content.replace( /<!-- Please do not remove or change this AfD message[\s\S]*?<!-- End of AfD message, feel free to edit beyond this point -->\s*\n?/, '' );
			if ( out === p.content ) { return info; }
			return BM.core.savePage( subject, out,
				'Removed the deletion notice, the discussion has closed (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', p.revid )
				.then( function () { return info; } );
		} );
	}
	function addOldAfdNotice( subject, info, resultLabel ) {
		if ( !info || !info.day || !info.month || !info.year ) { return null; }
		var line = '{{Old AfD multi|page=' + subject + '|date=' + info.day + ' ' + info.month + ' ' + info.year +
			'|result=\'\'\'' + resultLabel.toLowerCase() + '\'\'\'}}';
		return BM.core.appendToPage( talkTitle( subject ), line,
			'Added the closed deletion discussion record (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])' );
	}
	function cleanDelsort( content, disc ) {
		/* A closed discussion leaves the deletion sorting lists it was on. */
		var seen = {}, names = [];
		var re = /\[\[Bharatpedia:WikiProject Deletion sorting\/([^\]|]+)/g, m;
		while ( ( m = re.exec( content ) ) !== null ) {
			if ( !seen[ m[ 1 ] ] ) { seen[ m[ 1 ] ] = 1; names.push( m[ 1 ] ); }
		}
		var chain = Promise.resolve();
		names.forEach( function ( n ) {
			var listTitle = 'Bharatpedia:WikiProject Deletion sorting/' + n;
			chain = chain.then( function () {
				return BM.core.getPage( listTitle ).then( function ( p ) {
					if ( !p.exists ) { return null; }
					var lines = p.content.split( '\n' );
					var kept = lines.filter( function ( l ) { return l.indexOf( '{{' + disc + '}}' ) === -1; } );
					if ( kept.length === lines.length ) { return null; }
					return BM.core.savePage( listTitle, kept.join( '\n' ),
						'Removed a closed deletion discussion (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', p.revid );
				} );
			} );
		} );
		return chain;
	}
	function voteLine( vals ) {
		var reason = BM.core.cleanParam( vals.reason );
		if ( vals.vote === 'Comment' ) {
			return '* ' + reason + ' ' + BM.SIG;
		}
		var line = '*\'\'\'' + vals.vote + '\'\'\'';
		var t = BM.core.cleanParam( vals.target );
		if ( ( vals.vote === 'Redirect' || vals.vote === 'Merge' ) && t ) {
			line += ( vals.vote === 'Redirect' ? ' to ' : ' into ' ) + '[[' + t + ']]';
		}
		line += ': ' + ( reason ? reason + ' ' : '' ) + BM.SIG;
		return line;
	}
	function resultText( vals ) {
		var r = vals.result;
		var t = BM.core.cleanParam( vals.target );
		if ( ( r === 'Redirect' || r === 'Merge' ) && t ) {
			r = ( r === 'Redirect' ? 'Redirect to' : 'Merge into' ) + ' [[' + t + ']]';
		}
		var reason = BM.core.cleanParam( vals.reason );
		if ( reason ) { r += '. ' + reason; }
		return r;
	}
	function isClosedText( content ) {
		return /xfd-closed|archived debate/.test( content );
	}

	function doVote( v, vals ) {
		return BM.core.getPage( v.disc ).then( function ( p ) {
			if ( !p.exists ) { throw new Error( 'This discussion page does not exist.' ); }
			if ( isClosedText( p.content ) ) { throw new Error( 'This discussion is already closed.' ); }
			if ( vals.vote === 'Comment' && !BM.core.cleanParam( vals.reason ) ) {
				throw new Error( 'Please write the comment.' );
			}
			var out = p.content.replace( /\s+$/, '' ) + '\n' + voteLine( vals ) + '\n';
			return BM.core.savePage( v.disc, out,
				'Vote: ' + vals.vote + ' (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', p.revid );
		} );
	}
	function doRelist( v ) {
		return BM.core.getPage( v.disc ).then( function ( p ) {
			if ( !p.exists ) { throw new Error( 'This discussion page does not exist.' ); }
			if ( isClosedText( p.content ) ) { throw new Error( 'This discussion is already closed.' ); }
			var lm = p.content.match( /\[\[(Bharatpedia:Articles for deletion\/Log\/[^\]#|]+)/ );
			var oldLog = lm ? lm[ 1 ] : null;
			var note = '\n----\n\'\'\'Relisted to generate a more thorough discussion and clearer consensus.\'\'\'<br>\n' +
				'<small>Please add new comments below this notice. Thanks, ' + BM.SIG + '</small>\n';
			var out = p.content.replace( /\s+$/, '' ) + note;
			return BM.core.savePage( v.disc, out,
				'Relisted the discussion (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', p.revid ).then( function () {
				var entry = '{{' + v.disc + '}}<!--Relisted-->';
				var today = logTitle();
				function addEntry() {
					return BM.core.getPage( today ).then( function ( lp ) {
						if ( !lp.exists ) {
							return BM.core.savePage( today, entry + '\n',
								'Relisted a discussion (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])' );
						}
						var marker = '<!-- Add new entries to the TOP of the following list -->';
						var idx = lp.content.indexOf( marker );
						var newText;
						if ( idx !== -1 ) {
							var eol = lp.content.indexOf( '\n', idx );
							newText = lp.content.slice( 0, eol + 1 ) + entry + '\n' + lp.content.slice( eol + 1 );
						} else {
							newText = entry + '\n' + lp.content;
						}
						return BM.core.savePage( today, newText,
							'Relisted a discussion (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', lp.revid );
					} );
				}
				if ( !oldLog ) { return addEntry(); }
				return BM.core.getPage( oldLog ).then( function ( op ) {
					if ( !op.exists ) { return addEntry(); }
					var lines = op.content.split( '\n' );
					var kept = lines.filter( function ( l ) { return l.indexOf( '{{' + v.disc + '}}' ) === -1; } );
					var rm = kept.length === lines.length ? Promise.resolve() :
						BM.core.savePage( oldLog, kept.join( '\n' ),
							'Moved a relisted discussion to today\'s log (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', op.revid );
					return rm.then( addEntry );
				} );
			} );
		} );
	}
	function doClose( v, vals ) {
		return BM.core.getPage( v.disc ).then( function ( p ) {
			if ( !p.exists ) { throw new Error( 'This discussion page does not exist.' ); }
			if ( isClosedText( p.content ) ) { throw new Error( 'This discussion is already closed.' ); }
			var subject = subjectOf( v, p.content );
			var rt = resultText( vals );
			var out = '{{subst:' + v.top + '|' + rt + '}}\n' +
				p.content.replace( /\s+$/, '' ) + '\n{{subst:' + v.bottom + '}}\n';
			return BM.core.savePage( v.disc, out,
				'Closed as ' + vals.result + ' (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])', p.revid ).then( function () {
				var chain = Promise.resolve();
				var delReason = 'Deleted as a result of the deletion discussion at [[' + v.disc + ']]';
				if ( vals.result === 'Delete' || vals.result === 'Speedy delete' || vals.result === 'Soft delete' ) {
					chain = chain.then( function () {
						return deletePage( subject, delReason ).then( function () {
							var tt = talkTitle( subject );
							return BM.core.getPage( tt ).then( function ( tp ) {
								if ( tp.exists ) { return deletePage( tt, delReason ); }
								return null;
							} );
						} );
					} );
				} else if ( vals.result === 'Redirect' ) {
					var t = BM.core.cleanParam( vals.target );
					if ( t ) {
						chain = chain.then( function () {
							return BM.core.savePage( subject, '#REDIRECT [[' + t + ']]\n',
								'Redirected as a result of the deletion discussion at [[' + v.disc + ']] (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])' );
						} );
					}
				} else if ( v.key === 'afd' ) {
					chain = chain.then( function () {
						return removeAfdBanner( subject ).then( function ( info ) {
							return addOldAfdNotice( subject, info, vals.result );
						} );
					} );
				}
				if ( v.key === 'afd' ) {
					chain = chain.then( function () { return cleanDelsort( p.content, v.disc ); } );
				}
				if ( vals.notify ) {
					chain = chain.then( function () {
						return BM.core.firstEditor( v.disc ).then( function ( nom ) {
							if ( !nom || /^(imported>|->)/.test( nom ) || /[<>[\]{}|#]/.test( nom ) ) { return null; }
							var block = '== Deletion discussion closed: [[:' + subject + ']] ==\n' +
								'The discussion at [[' + v.disc + ']] has been closed. The result was \'\'\'' +
								vals.result + '\'\'\'. ' + BM.SIG;
							return BM.core.appendUnderMonth( 'User talk:' + nom, block,
								'Deletion discussion result (using [[Bharatpedia:Bharat Mitra|Bharat Mitra]])' );
						} );
					} );
				}
				return chain;
			} );
		} );
	}
	function discussionDialog() {
		var v = venueInfo();
		var sysop = isSysop();
		var actionOptions = [ [ 'vote', 'Vote in this discussion' ] ];
		if ( sysop ) {
			actionOptions.push( [ 'close', 'Close this discussion' ] );
			if ( v.key === 'afd' ) { actionOptions.push( [ 'relist', 'Relist this discussion' ] ); }
		}
		BM.core.dialog( {
			title: 'Deletion discussion tools',
			help: 'Discussion: ' + v.disc + '. Pick the action, then fill only the fields that action needs.' +
				( sysop ? '' : ' Closing and relisting are administrator actions.' ),
			fields: [
				{ name: 'action', label: 'Action', type: 'select', required: true, options: actionOptions },
				{ name: 'vote', label: 'Your vote (Vote action)', type: 'select', options: [
					[ 'Delete', 'Delete' ], [ 'Keep', 'Keep' ], [ 'Redirect', 'Redirect' ],
					[ 'Merge', 'Merge' ], [ 'Comment', 'Just a comment' ]
				] },
				{ name: 'result', label: 'Result (Close action)', type: 'select', options: [
					[ 'Delete', 'Delete' ], [ 'Keep', 'Keep' ], [ 'Redirect', 'Redirect' ], [ 'Merge', 'Merge' ],
					[ 'No consensus', 'No consensus' ], [ 'Soft delete', 'Soft delete' ],
					[ 'Speedy delete', 'Speedy delete' ], [ 'Withdrawn', 'Withdrawn' ]
				] },
				{ name: 'target', label: 'Target page (Redirect or Merge)', type: 'text' },
				{ name: 'reason', label: 'Reason, or closing statement for Close', type: 'textarea', rows: 3 },
				{ name: 'notify', label: 'Notify the nominator of the result (Close action)', type: 'checkbox', value: true }
			],
			preview: function ( vals ) {
				if ( vals.action === 'close' ) {
					return '{{subst:' + v.top + '|' + resultText( vals ) + '}}\n\n(the discussion text)\n\n{{subst:' + v.bottom + '}}';
				}
				if ( vals.action === 'relist' ) {
					return '----\n\'\'\'Relisted to generate a more thorough discussion and clearer consensus.\'\'\'<br>\n' +
						'<small>Please add new comments below this notice. Thanks, ' + BM.SIG + '</small>';
				}
				return voteLine( vals );
			},
			previewTitle: function () { return v.disc; },
			submitLabel: 'Do it',
			success: 'Done.',
			onSubmit: function ( vals ) {
				if ( vals.action === 'close' ) {
					if ( !sysop ) { throw new Error( 'Only administrators can close a discussion.' ); }
					return doClose( v, vals );
				}
				if ( vals.action === 'relist' ) {
					if ( !sysop ) { throw new Error( 'Only administrators can relist a discussion.' ); }
					return doRelist( v );
				}
				return doVote( v, vals );
			}
		} );
	}
	BM.register( 'xfd', {
		open: function () {
			if ( venueInfo() ) { discussionDialog(); } else { nominationDialog(); }
		}
	} );
}() );
/* </nowiki> */