Jump to content

User:DatGuyTesting/RfXtesting.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// <nowiki>
/*
The MIT License (MIT)

Copyright (c) 2013 Mr.Z-man

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

mw.loader.using( ['mediawiki.util', 'mediawiki.api', 'jquery.ui'], function () {
	if (mw.config.get('wgNamespaceNumber') == 4 ){ //&& 
	//mw.config.get('wgTitle').indexOf('Requests for adminship/') === 0 | mw.config.get('wgTitle').indexOf('Requests for bureaucratship') ) {
		$(document).ready( function () {
			mw.util.addPortletLink( 'p-cactions', '#', 'Close', 'ca-closeRFX', 'Close RfX' );
		} );	
		
		CloseRFX = {
			remove: true,
			recent: true,
			api: false,
			actionmap: {
				'succesful':'succesful',
				'unsuccesful':'unsuccesful',
				'nocon':'no consensus',
				'snow':'snow close',
				'notnow':'notnow',
				'withdrawn':'withdrawn'
			},
			token: false,
			titles: [],
			wikitext: false,
			actionsStarted: {
				'notdoneyet':0,
				'rfxpage':0,
				'edit':0,
				'addrecent':0,
				'rmcurrent':0
			},
			actionsFinished: {
				'notdoneyet':0,
				'rfxpage':0,
				'edit':0,
				'addrecent':0,
				'rmcurrent':0
			},
			debate: mw.config.get('wgTitle').substr(mw.config.get('wgTitle').indexOf('/')+1),
			logs: {}
		};
		
		// Handler for the close link in the top bar
		CloseRFX.close = function() {
			$( "#closeRFX-dialog" ).show().dialog( { title: "Closing "+mw.config.get('wgTitle'),
				width:400,
				buttons: [ { text: "Close RFX", click: CloseRFX.startCloseAction }, 
				{ text: "Cancel", click: function() {
					$( this ).dialog( "close" )
				} }]
			} );
			// We get the token now just to make the code less convoluted later
			CloseRFX.api = new mw.Api();
			params = {
				'action':'query',
				'meta':'tokens',
				'type': 'csrf'
			}
			CloseRFX.api.get(params)
			.done ( function (data) {
				CloseRFX.token = data['query']['tokens']['csrftoken'];
			})
			return false;
		}

		// Check if we're completely done
		CloseRFX.checkDone = function() {
			if (CloseRFX.actionsStarted['notdoneyet'] == CloseRFX.actionsFinished['notdoneyet'] &&
			CloseRFX.actionsStarted['rfxpage'] == CloseRFX.actionsFinished['rfxpage'] &&
			CloseRFX.actionsStarted['edit'] == CloseRFX.actionsFinished['edit'] &&
			CloseRFX.actionsStarted['addrecent'] == CloseRFX.actionsFinished['addrecent'] &&
			CloseRFX.actionsStarted['rmcurrent'] == CloseRFX.actionsFinished['rmcurrent']) {
				elem = $('#closeRFX-action5');
				$(elem).css('color', 'darkgreen').css('font-weight', 'bold').text("Done – ");
				link = $("<a></a>").attr('href', "//en.wikipedia.org/wiki/"+mw.config.get('wgPageName')+"?action=purge")
				.text("Reload page").css('color', '#0645AD');
				$(elem).append(link);
			}

		}
		
		// Edit a page
		// pageid/title - page to edit
		// newxtext - new text for page
		// summary - edit summary
		// callback - function to call on success
		// errorElem - element to put an error message in
		// incr - Variable to increment
		CloseRFX.edit = function(pageid, title, newtext, summary, callback, incr) {
			if (/^\s*$/.test(newtext)) { // making sure we don't accidentally blank the page
				$('#CloseRFX-error').css('color', 'red').text('Error when trying to edit "'+title+'"')
				}
				CloseRFX.actionsFinished[incr]++;
				CloseRFX.checkDone();
				return false;
			}
			CloseRFX.actionsStarted[incr]++;
			editparams = {'action':'edit',
				'watchlist':'nochange'
			};
			if (pageid) {
				editparams['pageid'] = pageid;
			} else if (title) {
				editparams['title'] = title;
			}
			editparams['text'] = newtext;
			editparams['summary'] = summary;
			editparams['token'] = CloseRFX.token;			
			CloseRFX.api.post(editparams)
			.fail( function (error) {
				{
					$('#CloseRFX-error').css('color', 'red').text("Error: "+error);
				}
				CloseRFX.actionsFinished[incr]++;
				CloseRFX.checkDone();
			})
			.done(function() {
				CloseRFX.actionsFinished[incr]++;
				callback()
				CloseRFX.checkDone();
			})			
		}
		
		// This gets called when you click the Close button
		CloseRFX.startCloseAction = function() {
			$( this ).dialog( "close" );
			$( "#CloseRFX-closestatus-dialog" ).show().dialog( { title: "Closing "+mw.config.get('wgTitle'),
				width:400,
				close: function( event, ui ) { CloseRFX.reset(); }
			} );
			var selected = $('input[name="CloseRFX-action"]:checked');
			if (typeof $(selected).val() == "undefined") {
				$( "#CloseRFX-closestatus-dialog" ).dialog( "close" );
				return false;
			}
			var patt = /CloseRFX-([a-z]+)/;
			CloseRFX.action = patt.exec($(selected).attr('id'))[1];
			// Get wikitext of AFD page
			$('#CloseRFX-rfxpage').text("Fetching AFD page...");
			var params = {
				'action':'query',
				'prop':'revisions',
				'titles':mw.config.get('wgPageName'),
				'rvprop':'timestamp|content'
			}
			CloseRFX.api.get(params)
			.fail( function (error) {
				$('#CloseRFX-error').text("Error: "+error);
			})
			.done( function (data) {
				var pageid = mw.config.get('wgArticleId').toString();
				CloseRFX.wikitext = data['query']['pages'][pageid]['revisions'][0]['*']
				// Check to make sure it's not already closed
				if (CloseRFX.wikitext.indexOf('boilerplate rfa') != -1) {
					$('#CloseRFX-rfxpage').css('color', 'red').text("RFX is already closed!");
					return false;
				}
				{
					CloseRFX.finishCloseAction();
				}
			})
		}
		
		// Now that we know what we want to do and where, actually do it
		CloseRFX.finishCloseAction = function() {
			// Assemble the closing statement
			var resultstr = "'''";
			var summary = '';
			var editsum = "Closing nomination, result was "+summary
			resultstr += CloseAFD.actionmap[CloseAFD.action];
			summary += CloseAFD.actionmap[CloseAFD.action];
			if (CloseAFD.action == 'merge' || CloseAFD.action == 'redir' || CloseAFD.action == 'delandred') {
			resultstr += "'''. ";
			resultstr += $('#CloseRFX-rationale').val();
			resultstr += ' ~~'+'~~\n';
			// Remove the template and add the closing templates
			var newtext = CloseRFX.wikitext.replace(/\{\{'''{{RfA tally\|[^}]*}}<!-- WHEN CLOSING THIS RFA, REPLACE THIS PART WITH.*$/m, '');
			if (CloseAFD.action == 'succesful') {
				newtext = '{'+'{subst:Rfap}}'+resultstr+newtext+'\n{{subst:Rfab}'+'}'
			} else {
				newtext = '{'+'{subst:Rfaf}}'+resultstr+newtext+'\n{{subst:Rfab}'+'}'
			}
			$('#CloseRFX-rfxpage').text("Saving "+wgTitle+'...');
			CloseRFX.actionsStarted['notdoneyet'] = 1;
			CloseRFX.edit(mw.config.get('wgArticleId').toString(), '', newtext, editsum, function (data) {
				$('#CloseRFX-rfxpage').css('color', 'darkgreen').text(wgTitle+" closed.");
			}, 'rfxpage');
			.fail( function (error) {
				$('#CloseRFX-error').text("Error: "+error);
			})
			.done( function (result) {
				timestamp = result['query']['pages'][mw.config.get('wgArticleId').toString()]['revisions'][0]['timestamp'];
				var d2 = new Date();
				var curdate = d2.getUTCDate().toString()+' '+CloseRFX.months[d2.getUTCMonth()]+' '+d2.getUTCFullYear().toString();
				// Set edit summary
				var editsum =  '[['+wgPageName.replace(/_/g, ' ')+']] closed as '+summary
				params = {
					'action':'query',
					'titles':'Wikipedia:Requests for adminship|Wikipedia:Requests for adminship/Recent',
					'indexpageids': '1',
					'prop':'revisions',
					'rvprop':'content',
					'redirects':'1'
				}
				CloseRFX.api.get(params)
				.fail( function (error) {
					$('#CloseRFX-error').text("Error: "+error);
				})
				.done( function (data) {
						$('#CloseRFX-action1').text('Editing page(s)...');
					}
				//CloseRFX.actionsFinished['notdoneyet'] = 1;
				//CloseRFX.checkDone();
			});	
		}

		// Add the Afd-merge-from template to the talk page of the target article
		CloseRFX.mergefrom = function(fromtitles, summary, date) {
			var target = $('#CloseRFX-target').val()
			t = 'Talk:'+target;
			var prepend = '';
			for (var i=0; i<fromtitles.length; i++) {
				prepend+= '{'+'{Afd-merge from|'+fromtitles[i]+'|'+CloseRFX.debate+'|'+date+'}}\n'
			}
			CloseRFX.actionsStarted['edittalk']++;
			editparams = {'action':'edit',
				'title': t,
				'summary': summary,
				'prependtext': prepend,
				'token': CloseRFX.token
			};		
			CloseRFX.api.post(editparams)
			.fail( function (error) {
				$('#CloseRFX-error').css('color', 'red').text("Error: "+error);
				CloseRFX.actionsFinished['edittalk']++;
				CloseRFX.checkDone();
			})
			.done(function() {
				CloseRFX.actionsFinished['edittalk']++;
				if (CloseRFX.actionsStarted['edittalk'] == CloseRFX.actionsFinished['edittalk']) {
					$('#CloseRFX-action1').css('color', 'darkgreen').text("Merge tags added");
				}
				CloseRFX.checkDone();
			})
		}
		
		$(document).on('click', '#ca-CloseRFX', CloseRFX.close);
	
		CloseRFX.reset = function() {		
			$('#CloseRFX-AFDpage').empty();
			$('#CloseRFX-multititles').empty();	
			$('#CloseRFX-action1').empty();
			$('#CloseRFX-action2').empty();
			$('#CloseRFX-action3').empty();
			$('#CloseRFX-action4').empty();
			$('#CloseRFX-action5').empty();
			$('#CloseRFX-error').empty();
			CloseRFX.titles = [];
		}
		// HTML for closing dialog
		$('#bodyContent').before('<div id="CloseRFX-dialog" style="width:400px;display:none;">'+
			'<div style="padding-bottom:2%;"><input type="checkbox" name="CloseRFX-speedy" id="CloseRFX-speedy" /><label for="CloseRFX-speedy">Speedy:</label></div>'+
			'<div style="float:left; width:150px; padding-bottom:1%;">'+
			'<span class="CloseRFX-nbc"><input type="radio" name="CloseRFX-action" id="CloseRFX-delete" /><label for="CloseRFX-delete">Delete</label><br /></span>'+
			'<input type="radio" name="CloseRFX-action" id="CloseRFX-keep" /><label for="CloseRFX-keep">Keep</label><br />'+
			'<input type="radio" name="CloseRFX-action" id="CloseRFX-nocon" /><label for="CloseRFX-nocon">No consensus</label><br />'+
			'<input type="radio" name="CloseRFX-action" id="CloseRFX-merge" /><label for="CloseRFX-merge">Merge</label><br />'+
			'</div><div style="float:left; width:210px; padding-bottom:1%;">'+
			'<input type="radio" name="CloseRFX-action" id="CloseRFX-redir" /><label for="CloseRFX-redir">Redirect</label><br />'+
			'<span class="CloseRFX-nbc"><input type="radio" name="CloseRFX-action" id="CloseRFX-delandred" /><label for="CloseRFX-delandred">Delete & redirect</label><br /></span>'+
			'<input type="radio" name="CloseRFX-action" id="CloseRFX-other" /><label for="CloseRFX-other">Other:</label>'+
			'<input type="text" size=15 disabled=disabled id="CloseRFX-other-action" /><br />'+
			'</div><div style="clear:both;padding-bottom:1%" id="CloseRFX-delrediropt">'+
			'<input type="checkbox" name="CloseRFX-delredir" id="CloseRFX-delredir" /><label for="CloseRFX-delredir">Delete redirects</label></div>'+
			'<div style="clear:both;padding-bottom:1%" id="CloseRFX-targetopt">'+
			'<label for="CloseRFX-delredir">Target page:</label><input type="text" name="CloseRFX-target" id="CloseRFX-target" /></div>'+
			'<div style="clear:both;">Additional closing rationale (optional):</div>'+
			'<textarea id="CloseRFX-rationale" rows=4 cols=100></textarea>'+
		'</div>');
		$('#CloseRFX-delrediropt').hide();
		$('#CloseRFX-targetopt').hide();
		
		// HTML for closing status dialog
		$('#bodyContent').before('<div id="CloseRFX-closestatus-dialog" style="width:400px;display:none;">'+
		'<div id="CloseRFX-RFXpage" style="width:380px;"></div>'+
		'<div id="CloseRFX-multititles" style="width:380px;display:none;"></div>'+
		'<div id="CloseRFX-action2" style="width:380px;"></div>'+
		'<div id="CloseRFX-action1" style="width:380px;"></div>'+
		'<div id="CloseRFX-action3" style="width:380px;"></div>'+
		'<div id="CloseRFX-action4" style="width:380px;"></div>'+
		'<div id="CloseRFX-action5" style="width:380px;"></div>'+
		'<div id="CloseRFX-error" style="width:380px;color:red;"></div>'+
		'</div>');
		
		// Hide succesful option from non-bureaucrat
		if (jquery.inArray("bureaucrat", mw.config.get('wgUserGroups')) == -1) {
			$(".CloseRFX-nbc").hide();
		}
	}
	
	RegExp.quote = function(str) {
		return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
	};
})
// </nowiki>