User:L293D/common.js

importScript('User:Evad37/rater.js'); // User:Evad37/rater importScript("User:Technical_13/Scripts/OneClickArchiver"); mw.loader.load("//en.wikipedia.org/w/index.php?title=User:L293D/AFCRHS.js\u0026action=raw\u0026ctype=text/javascript");

importScript('User:Shubinator/DYKcheck.js'); //DYKcheck tool //

/** window.hdedit = { onclick: function ($e) { hdedit.anchor = $e.attr('id'); hdedit.pagename = mw.config.get('wgPageName'); hdedit.api = mw.util.wikiScript('api'); $.getJSON(hdedit.api, {               action: 'parse',                page: this.pagename,                prop: 'sections',                format: 'json'        }, function (data) {        	error = false;        	error_msg = '';            $.each(data.parse.sections, function (i, v) { if (v.anchor == hdedit.anchor) { if (v.index !== "") { hdedit.index = v.index; }                   	else { error = true; error_msg = 'This section cannot be edited automatically ' + 'because it uses HTML formatting.'; }                       if (v.fromtitle && (v.fromtitle != hdedit.pagename)) { error = true; error_msg += 'This section cannot be edited automatically ' + 'because it is transcluded from a template.'; }                       return false; }           });            if (error) {            	hdedit.seterror($e, error_msg);            	return;            }            if (hdedit.$e) {            	hdedit.cancel;        	}        	hdedit.$e = $e;            $.getJSON(hdedit.api, { action: 'parse', page: hdedit.pagename, section: hdedit.index, prop: 'wikitext', format: 'json' }, function (obj) { hdedit.wikitext = obj.parse.wikitext['*']; hdedit.section_wikitext = hdedit.wikitext.replace(/^(=+)\s*(.+?)\s*\1[\s\S]*$/, '$2'); hdedit.inputsize = hdedit.section_wikitext.length*1.5; var form = $(' ').css('display', 'inline').submit(hdedit.save); var input = $(' ').attr('id', 'hdedit_input').attr('size', hdedit.inputsize).val(hdedit.section_wikitext); var button1 = $(' ').attr('id', 'hdedit_submit').attr('type', 'submit').text('Save'); var button2 = $(' ').attr('type', 'button').attr('id', 'hdedit_cancel').text('Cancel').click(hdedit.cancel); $(form).append(input).append(button1).append(button2); hdedit.form = form; $e.after(form); $e.hide; }           );        }        );    },    save: function  { hdedit.newheading = $(this).parent.find('input').val; if (hdedit.newheading == hdedit.section_wikitext) { return false; }       $.getJSON(hdedit.api, {                action: 'query',                prop: 'info',                intoken: 'edit',                titles: hdedit.pagename,                format: 'json',                indexpageids: true        }, function (re) {            $('#hdedit_input, #hdedit_submit, #hdedit_cancel').attr('disabled', 'disabled');            $.post(hdedit.api, { action: 'edit', format: 'json', title: hdedit.pagename, section: hdedit.index, minor: true, summary: 'Section heading change: ' + hdedit.section_wikitext + ' → ' + hdedit.newheading + ' using a script', text: hdedit.wikitext.replace(/^(=+)(\s*).+?(\s*)\1(\s*)$/m, '$1$2' + hdedit.newheading                        + '$3$1$4'), token: re.query.pages[re.query.pageids[0]].edittoken }, function (data) { if (data.edit.result == 'Success') { window.location.reload; }               else if (data.error) { alert('API returned error code ' + data.error.code + ': ' + data.error.info                        + '\nPlease edit the section heading manually.'); }               else { alert('Unknown API error. Please edit the section heading manually.'); }           });        });        return false; },   cancel: function  { hdedit.$e.show; hdedit.form.remove; },   seterror: function ($e, msg) { error = $(' '+ msg + ' Please edit manually. ').delay(5000).fadeOut('slow'); $e.parent.after(error); } };
 * Allows for one click modification of section headings when viewing a page
 * add importScript('User:The Evil IP address/hdedit.js'); to your .js file to use it
 * @author Janko Hoener (The Evil IP address)

if (mw.config.get('wgNamespaceNumber') >= 0 && mw.config.get('wgAction') == 'view') { $('h1 span.mw-headline, h2 span.mw-headline, h3 span.mw-headline, h4 span.mw-headline, h5 span.mw-headline, h6 span.mw-headline').click(       function  {            hdedit.onclick($(this));        }    ); }

$.when( mw.loader.using( ['mediawiki.util'] ), $.ready ).done( function { mw.util.addPortletLink( 'p-personal', mw.util.getUrl('Wikipedia:Articles for creation/Redirects'), 'AFCRD', 'pt-specialnew', 'Go to user page', null, '#pt-preferences' ); });

$.when( mw.loader.using( ['mediawiki.util'] ), $.ready ).done( function { mw.util.addPortletLink( 'p-personal', mw.util.getUrl('Special:RecentChanges'), 'Vandalism', 'pt-specialnew', 'Go to user page', null, '#pt-preferences' ); });

importScript( 'User:Enterprisey/delsort.js' ); // Backlink: User:Enterprisey/delsort.js

importScript('User:Ohconfucius/script/formatgeneral.js'); // User:Ohconfucius/script/formatgeneral.js importScript('User:Ohconfucius/script/MOSNUM dates.js'); // User:Ohconfucius/script/MOSNUM dates.js importScript('User:Ohconfucius/script/Common Terms.js'); // User:Ohconfucius/script/Common Terms.js importScript('User:Lourdes/PageCuration.js'); // Linkback: User:Lourdes/PageCuration.js

mw.loader.load('//www.mediawiki.org/w/index.php?title=XTools/ArticleInfo.js&action=raw&ctype=text/javascript');

ephAllowDataCorruptionBug = true;

// var browserHasDataCorruptionBug = $(' ')[0].outerHTML != ' '; if(browserHasDataCorruptionBug && ('undefined' === typeof ephAllowDataCorruptionBug || !ephAllowDataCorruptionBug)) { $(document).ready(function {		$('.editrequest .mbox-text').append(' The editProtectedHelper script is currently disabled because your browser has a bug which will cause corruption of pages that it edits with Parsoid. See here for details. To override this, add "ephAllowDataCorruptionBug = true;" immediately above the line where you load this script. You are responsible for any damage to pages that this causes. ');	}); // only enable this on the latest revision of the page } else if(mw.config.get('wgRevisionId') == mw.config.get('wgCurRevisionId')) { $(document).ready(function {		mw.loader.using( ['mediawiki.api'], function { 'use strict'; var templateResponses = [ [ '', '(No template response)' ], [ 'd', 'Done' ], [ 'pd', 'Partly done:' ], [ 'nd', 'Not done:' ], [ 'nfn', 'Not done for now:' ], [ 'c', 'Not done: please establish a consensus for this alteration before using the template.'], // TODO make dynamic [ 'rs', 'Not done: please provide reliable sources that support the change you want to be made.' ], [ 'xy', 'Not done: it\'s not clear what changes you want made. Please mention the specific changes in a "change X to Y" format.' ], [ 'mis', 'Not done: this is the talk page for discussing improvements to the template. Please make your request at the talk page for the article concerned.'], // TODO make dynamic [ 'sb', 'Not done: please make your requested changes to the template\'s sandbox first; see WP:TESTCASES.' ], [ 'tp', 'Not done: this is the talk page for discussing improvements to the template. If possible, please make your request at the talk page for the article concerned. If you cannot edit the article\'s talk page, you can instead make your request at Wikipedia:Requests for page protection#Current requests for edits to a protected page.' ], [ 'a', 'Already done' ], [ 'hr', 'Not done: According to the page\'s protection level and your user rights, you should be able to edit the page yourself. If you seem to be unable to, please reopen the request with further details.'], [ 'nlp', 'Not done: The page\'s protection level and/or your user rights have changed since this request was placed. You should now be able to edit the page yourself. If you still seem to be unable to, please reopen the request with further details.'], [ 'doc', 'Not done: is usually not required for edits to the documentation, categories, or interlanguage links of templates using a documentation subpage. Use the \'edit\' link at the top of the green "Template documentation" box to edit the documentation subpage.' ], [ 'drv', 'Not done: requests for recreating deleted pages protected against creation should be made at Wikipedia:Deletion review.' ], [ 'r', 'Not done: requests for increases to the page protection level should be made at Wikipedia:Requests for page protection.' ], [ 'ru', 'Not done: requests for decreases to the page protection level should be directed to the protecting admin or to Wikipedia:Requests for page protection if the protecting admin is not active or has declined the request.' ], [ 'p', 'Not done: this is not the right page to request additional user rights. You may reopen this request with the specific changes to be made and someone will add them for you.'], // TODO make dynamic [ 'm', 'Not done: page move requests should be made at Wikipedia:Requested moves.' ], [ 'q', 'Question:' ], [ 'note', 'Note:' ], [ 'udp', 'Undone: This request (or the completed portion of it) has been undone.' ], [ 'ud', 'Undone: This request has been undone.' ] ];			var selector = $('.editrequest .mbox-text'), parsoidDom; var selectedLevel = { semi: [' selected="selected"', , , ], extended: [, ' selected="selected"', , ], template: [, , ' selected="selected"', ], full: [, , , ' selected="selected"'] }; var templateLevel = { semi: 'semi-', extended: 'extended-', template: 'template-', full: 'fully-' }; var responseLevel = { semi: '{' + '{subst:ESp|', extended: '{' + '{subst:EEp|', template: '{' + '{subst:ETp|', full: '{' + '{subst:EP|' }; var warnOnRespond = false, warnOnQuickRespond = true, warnOnRemove = true, autoFixLevel = true; var quickResponses = [ [ 'd', '', 'Done'], [ 'rs', '', 'Needs reliable sources'], [ 'xy', '', 'Unclear/X to Y'], [ 'hr', '', 'Could always edit'], [ 'nlp', '', 'Can edit now'], [ 'mis', '', 'Misplaced'] ];			if('undefined' !== typeof ephWarnOnRespond) { warnOnRespond = ephWarnOnRespond; }			if('undefined' !== typeof ephWarnOnQuickRespond) { warnOnQuickRespond = ephWarnOnQuickRespond; }			if('undefined' !== typeof ephWarnOnRemove) { warnOnRemove = ephWarnOnRemove; }			if('undefined' !== typeof ephAutoFixLevel) { autoFixLevel = ephAutoFixLevel; }			if('undefined' !== typeof ephQuickResponses) { quickResponses = ephQuickResponses; }			function yesno(val, def) { if(typeof val === 'string') { val = val.toLowerCase; }				if(typeof val === 'undefined' || val === '') { return undefined; } else if(val === 'yes' || val === 'y' || val === 'true' || val === 1) { return true; } else if(val === 'no' || val === 'n' || val === 'false' || val === 0) { return false; }				return def; }			function getBanner(level, pagename, answered, force, demo) { return  : '}}');			}			function getResponse(level, template, free) {				return ':' + (template ===  ?  : responseLevel[level] + template + '}} ') + (free ===  ?  : free + ' ') +  + "\n";			}			function makeUniqueString(index) {				// this looks like a strip marker on purpose				return "\x7fUNIQ" + Math.random.toString(16).substr(2) + '-editProtectedHelper-' + index + "-QINU\x7f";			}			function saveWikitextFromParsoid(parsoidObj, data) {				var newWikitext, tmp, removerequest = false;				if(parsoidObj.removerequest) {					tmp = data.split(parsoidObj.templateMarker);					removerequest = true;					newWikitext = tmp[0];					if(parsoidObj.respondedInPage) {						tmp = tmp[1].split(parsoidObj.responseMarker);						newWikitext = newWikitext.replace(/\n+$/, ) + "\n\n" + tmp[1].replace(/^\n+/, );					}				} else {					var response = getResponse(parsoidObj.form.level.value, parsoidObj.form.responsetemplate.value, parsoidObj.form.responsefree.value);					var banner = getBanner(parsoidObj.form.level.value, parsoidObj.form.pagetoedit.value, parsoidObj.form.answered.checked, parsoidObj.form.force.checked, parsoidObj.demo); // prevent empty response if(response == ':' + "\n") { response = ''; }					tmp = data.split(parsoidObj.templateMarker); newWikitext = tmp[0].replace(/\n*$/, tmp[0].trim.length ? "\n\n" : '') + banner + tmp[1].replace(/^\n*/, "\n"); if(parsoidObj.respondedInPage) { tmp = newWikitext.split(parsoidObj.responseMarker); newWikitext = tmp[0].replace(/\n*$/, "\n") + response + tmp[1].replace(/^\n*/, "\n"); } else { newWikitext = newWikitext.replace(/\n*$/, "\n") + response; }				}				var resultObj = parsoidObj.resultObj, sectionName = parsoidObj.section && parsoidObj.section.text.trim; if(sectionName && (sectionName.indexOf(parsoidObj.templateMarker) !== -1 || sectionName.indexOf(parsoidObj.responseMarker) !== -1)) { // someone put an edit request template inside the section header, or something like that. // don't even try to include a working section link in that case sectionName = null; }				console.log(newWikitext); resultObj.text('Saving...'); debugger; // triggers only if debugger is active new mw.Api.get( { action: 'query', prop: 'revisions', rvprop: 'timestamp', revids: mw.config.get('wgRevisionId') }).done(function(data) {					new mw.Api.postWithEditToken( { action: 'edit', pageid: mw.config.get('wgArticleId'), text: newWikitext, summary: (sectionName ? '/' + '* ' + sectionName + ' *' + '/ ' : '') + (removerequest ? 'Removed' : 'replied to') + ' edit request', notminor: true, nocreate: true, basetimestamp: data.query.pages[mw.config.get('wgArticleId')].revisions[0].timestamp } ).done(function(result) { if(typeof(result.edit.newrevid) === 'undefined' || typeof(result.edit.oldrevid) === 'undefined') { resultObj.css('color', 'red').text("Error: The API response omitted required information. Please check the page's history manually to see whether your edit was saved properly. The console may contain details."); } else { resultObj.css('color', 'green').text('Success: Loading diff...'); location.href = mw.config.get('wgScript') + '?diff=' + result.edit.newrevid + '&oldid=' + result.edit.oldrevid; }					}).fail(function(err) { resultObj.css('color', 'red').text('Error: ' + err + '. The console may contain details.'); }).always(console.log);				}); }			function convertModifiedDom(e) { var parsoidObj, nextRequestBeforeHeader = false; if(warnOnRespond && !confirm('Are you sure you want to respond to this edit request?')) { return false; }				$('.editrequest button').prop('disabled', true); parsoidObj = e.data; parsoidObj.resultObj.text('Preparing new wikitext...'); $(parsoidObj).before(parsoidObj.templateMarker); $('h1,h2,h3,h4,h5,h6,.editrequest', parsoidDom).each(function {					var obj = $(this);					if(!obj.hasClass('editrequest')) {						// a heading						if(obj.closest('[typeof="mw:Transclusion"]').length) {							// it's from a template transclusion. ignore							return true;						}						if(obj.add(parsoidObj)[0] === this) {							// before our banner. set as our section header (tentatively) and otherwise ignore							parsoidObj.section = obj;							return true;						}					} else if (obj.add(parsoidObj)[0] === this) {						// not after our banner. ignore						return true;					} else {						nextRequestBeforeHeader = true;					}					obj.before(parsoidObj.responseMarker);					parsoidObj.respondedInPage = true;					return false;				}); if(parsoidObj.removerequest && !nextRequestBeforeHeader && $(parsoidObj).prev.is(parsoidObj.section)) { // if the section header is immediately before a request being removed, remove it too parsoidObj.section.remove; }				$('[about="' + $(parsoidObj).attr('about').replace('\\', '\\\\').replace('"', '\\"') + '"]', parsoidDom).remove; $.ajax({					type: 'POST',					url: '/api/rest_v1/transform/html/to/wikitext/' + encodeURIComponent(mw.config.get('wgPageName')) + '/' + mw.config.get('wgRevisionId'),					headers: {						Accept: 'text/plain; charset=utf-8; profile="mediawiki.org/specs/wikitext/1.0.0"',						'Api-User-Agent': 'editProtectedHelper (https://en.wikipedia.org/wiki/User:Jackmcbarn/editProtectedHelper)'					},					data: { html: parsoidDom.documentElement.outerHTML },					success: function(data) { return saveWikitextFromParsoid(parsoidObj, data); }				}); }			function appendForm(obj, level, pagename, answered, force, parsoidObj) { if(browserHasDataCorruptionBug) { $(obj).append(' WARNING: Your browser has a bug which will cause corruption of pages that it edits with Parsoid. See here for details. You are responsible for any damage to pages that this causes. '); }				var form = $(''); form.append(' .mw-ui-input { background-color: white; } '); form.append(' Level: Semi-protected Extended-confirmed-protected Template-protected Fully protected  '); if(force) { form.append(' Disable protection level autodetection (use only if necessary):  ' ); } else { form.append('' ); // if this is off and you want to turn it on, do it with firebug or something. otherwise people will use this when they shouldn't				} var label = $(' Page to be edited: '); label.append($('').attr('value', pagename !== '' ? pagename : '')); form.append(label); form.append(' Answered:  Response: '); var select = $(''); templateResponses.forEach(function(r) {					select.append($(' ').attr('value', r[0]).text(r[1]));				}); form.append(select); form.append(' ' + ' '); var resultObj = $(' '); var button = $('<button type="button" class="mw-ui-button mw-ui-constructive">Submit ').click(parsoidObj, convertModifiedDom); form.append(button); form.append(' '); $(obj).append(form); var buttons = $(' '); buttons.append($('<button type="button" class="mw-ui-button mw-ui-progressive">Respond ').click(function{ buttons.hide; $(obj).closest('.editrequest').removeClass('mbox-small'); form.show; }))				.append(' ') .append($('<button type="button" class="mw-ui-button mw-ui-destructive">Remove request ').click(function{ if(!warnOnRemove || confirm('Are you sure you want to completely remove this edit request from the page? In general, this should not be done to good-faith requests, even if they are blank, unless they are duplicates of other requests by the same user, etc.')) { warnOnRespond = false; parsoidObj.removerequest = true; button.click; }				}));				if(!answered) { quickResponses.forEach(function(r){						buttons.append(' ').append($('<button type="button" class="mw-ui-button mw-ui-constructive" />').text(r[2]).click(function{							if(!warnOnQuickRespond || confirm('Are you sure you want to respond to this edit request?')) {								warnOnRespond = false;								parsoidObj.form.answered.checked = true;								parsoidObj.form.responsetemplate.value = r[0];								parsoidObj.form.responsefree.value = r[1];								button.click;							}						}));					}); }				$(obj).append(buttons); $(obj).append(resultObj); parsoidObj.form = form[0]; parsoidObj.resultObj = resultObj; }			function parsoidSetupFieldsForTemplate(index) { var obj = $(this); var data_mw = obj.attr('data-mw'); if(data_mw === undefined) { console.log("No data-mw attribute was found on edit request banner " + index + ". This is probably because some template above it on the page opened an HTML tag but didn't close it."); return; }				data_mw = JSON.parse(data_mw); var templateName = data_mw.parts[0].template.target.wt; var level = obj.attr('data-origlevel'); if(autoFixLevel) { switch(this.id) { case 'editsemiprotected': level = 'semi'; break; case 'editextendedprotected': level = 'extended'; break; case 'edittemplateprotected': level = 'template'; break; case 'editprotected': level = 'full'; }				}				var params = []; for(var key in data_mw.parts[0].template.params) { params[key] = data_mw.parts[0].template.params[key].wt; }				// this only runs on numerical parameters params.forEach(function(value, key) {					if(/=/.test(value)) {						params[key] = key + '=' + value;					}				}); var pagename = params.join('|').replace(/^\|+|\|+$/g, '').replace(/\|+/g, '|'); var answered = yesno(params.ans || params.answered, true); this.demo = yesno(params.demo); var force = yesno(params.force); this.params = params; this.templateMarker = makeUniqueString(2 * index); this.responseMarker = makeUniqueString(2 * index + 1); appendForm(selector[index], level, pagename, answered, force, this); }			function onParsoidDomReceived(data) { parsoidDom = new DOMParser.parseFromString(data, 'text/html'); if(!parsoidDom) { // blech. Safari. parsoidDom = document.implementation.createHTMLDocument(''); parsoidDom.documentElement.innerHTML = data; }				var parsoidSelector = $('.editrequest', parsoidDom); if(selector.length != parsoidSelector.length) { console.log('Sanity check failed: ' + selector.length + ' edit requests exist in the page but only ' + parsoidSelector.length + ' were found in Parsoid\'s output.'); return; }				parsoidSelector.each(parsoidSetupFieldsForTemplate); }			if(selector.length) { mw.loader.load('mediawiki.api'); mw.loader.load('mediawiki.ui.button'); mw.loader.load('mediawiki.ui.input'); $.ajax({					url: '/api/rest_v1/page/html/' + encodeURIComponent(mw.config.get('wgPageName')) + '/' + mw.config.get('wgRevisionId'),					headers: {						Accept: 'text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/1.2.1"',						'Api-User-Agent': 'editProtectedHelper (https://en.wikipedia.org/wiki/User:Jackmcbarn/editProtectedHelper)'					},					success: onParsoidDomReceived				}); }		});	}); } //

// (function {   if (mw.config.get('wgPageName').indexOf('Wikipedia:Articles_for_creation/Redirects') === -1) {        return;    }

var afcHelper_RedirectPageName = mw.config.get('wgPageName').replace(/_/g, ' '); var afcHelper_RedirectSubmissions = new Array; var afcHelper_RedirectSections = new Array; var afcHelper_advert = ''; var afcHelper_numTotal = 0; var afcHelper_AJAXnumber = 0; var afcHelper_Submissions = new Array; var needsupdate = new Array; var afcHelper_redirectDecline_reasonhash = { 'exists': 'The title you suggested already exists on Wikipedia', 'blank': 'We cannot accept empty submissions', 'notarget': ' A redirect cannot be created unless the target is an existing article. Either you have not specified the target, or the target does not exist', 'unlikely': 'The title you suggested seems unlikely. Could you provide a source showing that it is a commonly used alternate name?', 'notredirect': 'This request is not a redirect request', 'custom': '' };   var afcHelper_categoryDecline_reasonhash = { 'exists': 'The category you suggested already exists on Wikipedia', 'blank': 'We cannot accept empty submissions', 'unlikely': 'It seems unlikely that there are enough pages to support this category', 'notcategory': 'This request is not a category request', 'custom': '' };

function afcHelper_redirect_init { pagetext = afcHelper_getPageText(afcHelper_RedirectPageName); // cleanup the wikipedia links for preventing stuff like https://en.wikipedia.org/w/index.php?diff=576244067&oldid=576221437 pagetext = afcHelper_cleanuplinks(pagetext);

// first, strip out the parts before the first section. var section_re = /==.*?==/; pagetext = pagetext.substring(pagetext.search(section_re)); // then split it into the rest of the sections afcHelper_RedirectSections = pagetext.match(/^==.*?==$((\r?\n?)(?!==[^=]).*)*/img);

// parse the sections. for (var i = 0; i < afcHelper_RedirectSections.length; i++) { var closed = /(\{\{\s*afc(?!\s+comment)|This is an archived discussion)/i.test(afcHelper_RedirectSections[i]); if (!closed) { // parse. var header = afcHelper_RedirectSections[i].match(section_re)[0]; if (header.search(/Redirect request/i) !== -1) { var wikilink_re = /\[\[(\s*[^=]*?)*?\]\]/g; var links = header.match(wikilink_re); if (!links) continue; for (var l = 0; l < links.length; l++) { links[l] = links[l].replace(/[\[\]]/g, ''); if (links[l].charAt(0) === ':') links[l] = links[l].substring(1); }                   var re = /Target of redirect:\s*\[\[([^\[\]]*)\]\]/i; re.test(afcHelper_RedirectSections[i]); var to = $.trim(RegExp.$1);

var reasonRe = /Reason:[ \t]*?(.+)/i; var reasonMatch = reasonRe.exec(afcHelper_RedirectSections[i]); var reason = reasonMatch && reasonMatch[1].trim ? reasonMatch[1] : null;

var sourceRe = /Source.*?:[ \t]*?(.+)/i; var sourceMatch = sourceRe.exec(afcHelper_RedirectSections[i]); var source = sourceMatch && sourceMatch[1].trim ? sourceMatch[1] : null;

var submission = { type: 'redirect', from: new Array, section: i,                       to: to, title: to, reason: reason, source: source };                   for (var j = 0; j < links.length; j++) { var sub = { type: 'redirect', to: to, id: afcHelper_numTotal, title: links[j], action: '' };                       submission.from.push(sub); afcHelper_Submissions.push(sub); afcHelper_numTotal++; }                   afcHelper_RedirectSubmissions.push(submission); } else if (header.search(/Category request/i) !== -1) {

// Find a wikilink in the header, and assume it's the category to create var category_name = /\[\^\[\+\]\]/.exec(header); if (!category_name) continue; category_name = category_name[0]; category_name = category_name.replace(/[\[\]]/g, ''); category_name = category_name.replace(/Category\s*:\s*/gi, 'Category:'); if (category_name.charAt(0) === ':') category_name = category_name.substring(1);

// Figure out the parent categories var request_text = afcHelper_RedirectSections[i].substring(header.length); var parent_cats = []; var parent_cat_match = null; var parent_cat_regex = /\[\[\s*:\s*(Category:[^\]\[]*)\]\]/ig; do { parent_cat_match = parent_cat_regex.exec(request_text); if (parent_cat_match) { parent_cats.push(parent_cat_match[1]); }                   } while (parent_cat_match);

var submission = { type: 'category', title: category_name, section: i,                       id: afcHelper_numTotal, action: '', parents: parent_cats.join(',') };                   afcHelper_numTotal++; afcHelper_RedirectSubmissions.push(submission); afcHelper_Submissions.push(submission); }           } // end if (!closed) } // end loop over sections

// Build the form var $form = $(' Reviewing AfC redirect requests '); displayMessage($form); var $messageDiv = $form.parent; // now layout the text. var afcHelper_Redirect_empty = 1; var ACTIONS = [ {label: 'Accept', value: 'accept'}, {label: 'Decline', value: 'decline'}, {label: 'Comment',value: 'comment'}, {label: 'None', selected: true, value: 'none'} ];       for (var k = 0; k < afcHelper_RedirectSubmissions.length; k++) { if (afcHelper_RedirectSubmissions[k].to !== undefined) var submissionname = afcHelper_RedirectSubmissions[k].to.replace(/\s/g,''); else var submissionname = ""; var $thisSubList = $('<ul>'); var $thisSubListElement = $('<li>'); if (afcHelper_RedirectSubmissions[k].type === 'redirect') { $thisSubListElement.append('Redirect(s) to '); if (!submissionname) { for (var i = afcHelper_RedirectSubmissions[k].from.length - 1; i >= 0; i--) { needsupdate.push({                           id: afcHelper_RedirectSubmissions[k].from[i].id,                            reason: 'notarget'                        }); }               } else if (!afcHelper_RedirectSubmissions[k].to) { for (var i = afcHelper_RedirectSubmissions[k].from.length - 1; i >= 0; i--) { needsupdate.push({                           id: afcHelper_RedirectSubmissions[k].from[i].id,                            reason: 'notredirect'                        }); }               }                if (afcHelper_RedirectSubmissions[k] === '' || afcHelper_RedirectSubmissions[k] === ' ') { $thisSubListElement.append('Empty submission \#' + afcHelper_Redirect_empty); afcHelper_Redirect_empty++; } else { if (submissionname.length > 0) { $thisSubListElement.append($('<a>')                           .attr('href', mw.config.get('wgArticlePath').replace("$1", encodeURIComponent(afcHelper_RedirectSubmissions[k].to)))                            .attr('target', '_blank')                            .text(afcHelper_RedirectSubmissions[k].to)); } else { $thisSubListElement.append('no target given: '); }               }                var $fromList = $('<ul>').appendTo($thisSubListElement); for (var l = 0; l < afcHelper_RedirectSubmissions[k].from.length; l++) { var from = afcHelper_RedirectSubmissions[k].from[l]; var toarticle = from.title; if (toarticle.replace(/\s*/gi, "").length == 0) toarticle = "no title specified, check the request details"; var reasonAndSource = $('<ul>'); if(afcHelper_RedirectSubmissions[k].reason) reasonAndSource.append('<li>Reason: ' + afcHelper_RedirectSubmissions[k].reason + '</li>'); if(afcHelper_RedirectSubmissions[k].source) reasonAndSource.append('<li>Source: ' + afcHelper_RedirectSubmissions[k].source + '</li>');

var googleSearchUrl = 'http://www.google.com/search?q="' +                           encodeURIComponent(toarticle) + '"+-wikipedia.org'; $fromList.append($('<li>')                       .append('From: ' + toarticle + ' ( <a href=\'' + googleSearchUrl + '\'" target="_blank">' +                            'Google</a> &middot; <a href="https://en.wikipedia.org/wiki/Special:WhatLinksHere/' +                            encodeURIComponent(toarticle) + '" target="_blank">what links here</a>) ')                        .append(reasonAndSource)                        .append($(' ').attr('for', 'afcHelper_redirect_action_' + from.id).text('Action: '))                        .append(afcHelper_generateSelectObject('afcHelper_redirect_action_' + from.id, ACTIONS,                            afcHelper_redirect_makeActionChange(from.id)))                        .append($(' ').attr('id', 'afcHelper_redirect_extra_' + from.id)));                }            } else {                var subId = afcHelper_RedirectSubmissions[k].id; $thisSubListElement.append('Category submission: ') .append($('<a>')                       .attr('href', '/wiki/' + afcHelper_RedirectSubmissions[k].title)                        .attr('title', afcHelper_RedirectSubmissions[k].title)                        .text(afcHelper_RedirectSubmissions[k].title)) .append(' ') .append($(' ').attr('for', 'afcHelper_redirect_action_' + subId).text('Action: ')) .append(afcHelper_generateSelectObject('afcHelper_redirect_action_' + subId, ACTIONS, afcHelper_redirect_makeActionChange(subId))) .append($(' ').attr('id', 'afcHelper_redirect_extra_' + subId)); }           $thisSubList.append($thisSubListElement); $messageDiv.append($thisSubList); } // end loop over sections $messageDiv.append($(' ')           .attr('id', 'afcHelper_redirect_done_button')            .attr('name', 'afcHelper_redirect_done_button')            .text('Done')            .click(afcHelper_redirect_performActions)); for (var y = 0; y < needsupdate.length; y++){ $('#afcHelper_redirect_action_'+needsupdate[y].id).attr('value', 'decline'); afcHelper_redirect_onActionChange(needsupdate[y].id); $('#afcHelper_redirect_decline_'+needsupdate[y].id).attr('value', needsupdate[y].reason); }   }

function afcHelper_redirect_makeActionChange(id) { return function { afcHelper_redirect_onActionChange(id); }; }

function afcHelper_redirect_onActionChange(id) { console.log("Entering afcHelper_redirect_onActionChange, id = " + id); var $extra = $("#afcHelper_redirect_extra_" + id); var selectValue = $("#afcHelper_redirect_action_" + id).val; $extra.html(''); // Blank it first if (selectValue === 'accept') { if (afcHelper_Submissions[id].type === 'redirect') { $extra.append('<label for="afcHelper_redirect_from_' + id + '">From: '); $extra.append($(' ')           		.attr('type', 'text')            		.attr('name', 'afcHelper_redirect_from_' + id)            		.attr('id', 'afcHelper_redirect_from_' + id)            		.attr('value', afcHelper_escapeHtmlChars(afcHelper_Submissions[id].title)));

$extra.html($extra.html + ' <label for="afcHelper_redirect_to_' + id + '">To: <input type="text" ' + 'name="afcHelper_redirect_to_' + id + '" id="afcHelper_redirect_to_' + id + '" value="' + afcHelper_escapeHtmlChars(afcHelper_Submissions[id].to) + '" />'); $extra.html($extra.html + ' <label for="afcHelper_redirect_append_' + id + '">Template to append: (<a href="https://en.wikipedia.org/wiki/Wikipedia:TMR" target="_blank">Help</a>) '); $extra.html($extra.html + afcHelper_generateSelect('afcHelper_redirect_append_' + id, [{ label: 'None', selected: true, value: 'none' }, {                   label: 'Frequently used', value: 'Frequently used', disabled: true }, {                   label: 'R from alternative language', value: 'R from alternative language' }, {                   label: 'R from alternative name', value: 'R from alternative name' }, {                   label: 'R from modification', value: 'R from modification' }, {                   label: 'R to section', value: 'R to section' }, {                   label: 'R from diacritic', value: 'R from diacritic' }, {                   label: 'R to diacritic', value: 'R to diacritic' }, {                   label: 'From – abbreviation, capitalisation, and grammar', value: 'From – abbreviation, capitalisation, and grammar', disabled: true }, {                   label: 'R from acronym', value: 'R from acronym' }, {                   label: 'R from initialism', value: 'R from initialism' }, {                   label: 'R from CamelCase', value: 'R from CamelCase' }, {                   label: 'R from miscapitalisation', value: 'R from miscapitalisation' }, {                   label: 'R from other capitalisation', value: 'R from other capitalisation' }, {                   label: 'R from modification', value: 'R from modification' }, {                   label: 'R from plural', value: 'R from plural' }, {                   label: 'From parts of speach', value: 'From parts of speach', disabled: true }, {                   label: 'R from adjective', value: 'R from adjective' }, {                   label: 'R from adverb', value: 'R from adverb' }, {                   label: 'R from common noun', value: 'R from common noun' }, {                   label: 'R from gerund', value: 'R from gerund' }, {                   label: 'R from proper noun', value: 'R from proper noun' }, {                   label: 'R from verb', value: 'R from verb' }, {                   label: 'From – spelling', value: 'From – spelling', disabled: true }, {                   label: 'R from alternative spelling', value: 'R from alternative spelling' }, {                   label: 'R from misspelling', value: 'R from misspelling' }, {                   label: 'R from American English', value: 'R from American English' }, {                   label: 'R from British English', value: 'R from British English' }, {                   label: 'R from ASCII-only', value: 'R from ASCII-only' }, {                   label: 'R from diacritic', value: 'R from diacritic' }, {                   label: 'R from ligature', value: 'R from ligature' }, {                   label: 'R from stylization', value: 'R from stylization' }, {                   label: 'R from alternative transliteration', value: 'R from alternative transliteration' }, {                   label: 'R from Wade–Giles romanization', value: 'R from Wade–Giles romanization' }, {                   label: 'From alternative names, general', value: 'From alternative names, general', disabled: true }, {                   label: 'R from alternative language', value: 'R from alternative language' }, {                   label: 'R from alternative name', value: 'R from alternative name' }, {                   label: 'R from former name', value: 'R from former name' }, {                   label: 'R from historic name', value: 'R from historic name' }, {                   label: 'R from incomplete name', value: 'R from incomplete name' }, {                   label: 'R from incorrect name', value: 'R from incorrect name' }, {                   label: 'R from letter–word combination', value: 'R from letter–word combination' }, {                   label: 'R from long name', value: 'R from long name' }, {                   label: 'R from portmanteau', value: 'R from portmanteau' }, {                   label: 'R from predecessor company name', value: 'R from predecessor company name' }, {                   label: 'R from short name', value: 'R from short name' }, {                   label: 'R from sort name', value: 'R from sort name' }, {                   label: 'R from less specific name', value: 'R from less specific name' }, {                   label: 'R from more specific name', value: 'R from more specific name' }, {                   label: 'R from antonym', value: 'R from antonym' }, {                   label: 'R from eponym', value: 'R from eponym' }, {                   label: 'R from synonym', value: 'R from synonym' }, {                   label: 'R from Roman numerals', value: 'R from Roman numerals' }, {                   label: 'From alternative names, geography', value: 'From alternative names, geography', disabled: true }, {                   label: 'R from Canadian settlement name', value: 'R from Canadian settlement name' }, {                   label: 'R from name and country', value: 'R from name and country' }, {                   label: 'R from city and state', value: 'R from city and state' }, {                   label: 'R from city and province', value: 'R from city and province' }, {                   label: 'R from more specific geographic name', value: 'R from more specific geographic name' }, {                   label: 'R from postal abbreviation', value: 'R from postal abbreviation' }, {                   label: 'R from postal code', value: 'R from postal code' }, {                   label: 'R from US postal abbreviation', value: 'R from US postal abbreviation' }, {                   label: 'From alternative names, organisms', value: 'From alternative names, organisms', disabled: true }, {                   label: 'R from scientific abbreviation', value: 'R from scientific abbreviation' }, {                   label: 'R from scientific name', value: 'R from scientific name' }, {                   label: 'R from alternative scientific name', value: 'R from alternative scientific name' }, {                   label: 'R from monotypic taxon', value: 'R from monotypic taxon' }, {                   label: 'From alternative names, people', value: 'From alternative names, people', disabled: true }, {                   label: 'R from birth name', value: 'R from birth name' }, {                   label: 'R from given name', value: 'R from given name' }, {                   label: 'R from married name', value: 'R from married name' }, {                   label: 'R from name with title', value: 'R from name with title' }, {                   label: 'R from non-neutral name', value: 'R from non-neutral name' }, {                   label: 'R from personal name', value: 'R from personal name' }, {                   label: 'R from pseudonym', value: 'R from pseudonym' }, {                   label: 'R from relative', value: 'R from relative' }, {                   label: 'R from spouse', value: 'R from spouse' }, {                   label: 'R from surname', value: 'R from surname' }, {                   label: 'From alternative names, technical', value: 'From alternative names, technical', disabled: true }, {                   label: 'R from Bluebook abbreviation', value: 'R from Bluebook abbreviation' }, {                   label: 'R from brand name', value: 'R from brand name' }, {                   label: 'R from drug trade name', value: 'R from drug trade name' }, {                   label: 'R from file name', value: 'R from file name' }, {                   label: 'R from Java package name', value: 'R from Java package name' }, {                   label: 'R from MathSciNet abbreviation', value: 'R from MathSciNet abbreviation' }, {                   label: 'R from molecular formula', value: 'R from molecular formula' }, {                   label: 'R from NLM abbreviation', value: 'R from NLM abbreviation' }, {                   label: 'R from product name', value: 'R from product name' }, {                   label: 'R from slogan', value: 'R from slogan' }, {                   label: 'R from symbol', value: 'R from symbol' }, {                   label: 'R from systematic abbreviations', value: 'R from systematic abbreviations' }, {                   label: 'R from technical name', value: 'R from technical name' }, {                   label: 'R from trademark', value: 'R from trademark' }, {                   label: 'From – navigation', value: 'From – navigation', disabled: true }, {                   label: 'R from file metadata link', value: 'R from file metadata link' }, {                   label: 'R mentioned in hatnote', value: 'R mentioned in hatnote' }, {                   label: 'R from shortcut', value: 'R from shortcut' }, {                   label: 'R from template shortcut', value: 'R from template shortcut' }, {                   label: 'From disambiguations', value: 'From disambiguations', disabled: true }, {                   label: 'R from ambiguous term', value: 'R from ambiguous term' }, {                   label: 'R from incomplete disambiguation', value: 'R from incomplete disambiguation' }, {                   label: 'R from incorrect disambiguation', value: 'R from incorrect disambiguation' }, {                   label: 'R from other disambiguation', value: 'R from other disambiguation' }, {                   label: 'R from predictable disambiguation', value: 'R from predictable disambiguation' }, {                   label: 'R from unnecessary disambiguation', value: 'R from unnecessary disambiguation' }, {                   label: 'From mergers, duplicates, and moves', value: 'From mergers, duplicates, and moves', disabled: true }, {                   label: 'R from duplicated article', value: 'R from duplicated article' }, {                   label: 'R with history', value: 'R with history' }, {                   label: 'R from merge', value: 'R from merge' }, {                   label: 'R from move', value: 'R from move' }, {                   label: 'R with old history', value: 'R with old history' }, {                   label: 'From fiction', value: 'From fiction', disabled: true }, {                   label: 'R from fictional character', value: 'R from fictional character' }, {                   label: 'R from fictional element', value: 'R from fictional element' }, {                   label: 'R from fictional location', value: 'R from fictional location' }, {                   label: 'From related info', value: 'From related info', disabled: true }, {                   label: 'R from album', value: 'R from album' }, {                   label: 'R from animal', value: 'R from animal' }, {                   label: 'R from book', value: 'R from book' }, {                   label: 'R from catchphrase', value: 'R from catchphrase' }, {                   label: 'R from domain name', value: 'R from domain name' }, {                   label: 'R from top-level domain', value: 'R from top-level domain' }, {                   label: 'R from film', value: 'R from film' }, {                   label: 'R from gender', value: 'R from gender' }, {                   label: 'R from legislation', value: 'R from legislation' }, {                   label: 'R from list topic', value: 'R from list topic' }, {                   label: 'R from member', value: 'R from member' }, {                   label: 'R from person', value: 'R from person' }, {                   label: 'R from phrase', value: 'R from phrase' }, {                   label: 'R from quotation', value: 'R from quotation' }, {                   label: 'R from related word', value: 'R from related word' }, {                   label: 'R from school', value: 'R from school' }, {                   label: 'R from song', value: 'R from song' }, {                   label: 'R from subtopic', value: 'R from subtopic' }, {                   label: 'R from team', value: 'R from team' }, {                   label: 'R from work', value: 'R from work' }, {                   label: 'R from writer', value: 'R from writer' }, {                   label: 'R from Unicode', value: 'R from Unicode' }, {                   label: 'To – grammar, punctuation, and spelling', value: 'To – grammar, punctuation, and spelling', disabled: true }, {                   label: 'R to acronym', value: 'R to acronym' }, {                   label: 'R to initialism', value: 'R to initialism' }, {                   label: 'R to ASCII-only title', value: 'R to ASCII-only title' }, {                   label: 'R to diacritic', value: 'R to diacritic' }, {                   label: 'R to ligature', value: 'R to ligature' }, {                   label: 'R to plural', value: 'R to plural' }, {                   label: 'To alternative names', value: 'To alternative names', disabled: true }, {                   label: 'R to former name', value: 'R to former name' }, {                   label: 'R to historic name', value: 'R to historic name' }, {                   label: 'R to joint biography', value: 'R to joint biography' }, {                   label: 'R to name with title', value: 'R to name with title' }, {                   label: 'R to monotypic taxon', value: 'R to scientific name' }, {                   label: 'R to scientific name', value: 'R to scientific name' }, {                   label: 'R to systematic name', value: 'R to systematic name' }, {                   label: 'R to technical name', value: 'R to technical name' }, {                   label: 'To – navigation and disambiguation', value: 'To – navigation and disambiguation', disabled: true }, {                   label: 'R to anchor', value: 'R to anchor' }, {                   label: 'R to anthroponymy page', value: 'R to anthroponymy page' }, {                   label: 'R to disambiguation page', value: 'R to disambiguation page' }, {                   label: 'R to list entry', value: 'R to list entry' }, {                   label: 'R to section', value: 'R to section' }, {                   label: 'To miscellaneous', value: 'To miscellaneous', disabled: true }, {                   label: 'R to decade', value: 'R to decade' }, {                   label: 'R to related topic', value: 'R to related topic' }, {                   label: 'R to subpage', value: 'R to subpage' }, {                   label: 'R to subtopic', value: 'R to subtopic' }, {                   label: 'R to TV episode list entry', value: 'R to TV episode list entry' }, {                   label: 'Custom - prompt me', value: 'custom' }]));           } else { // now Categories $extra.html('<label for="afcHelper_redirect_name_' + id + '">Category name: <input type="text" size="100" ' + 'name="afcHelper_redirect_name_' + id + '" id="afcHelper_redirect_name_' + id + '" value="' + afcHelper_escapeHtmlChars(afcHelper_Submissions[id].title) + '" />'); $extra.html($extra.html + ' <label for="afcHelper_redirect_parents_' + id + '">Parent categories (comma-separated): ' + '<input type="text" size="100" id="afcHelper_redirect_parents_' + id + '" name="afcHelper_redirect_parents_' + id + '" value="' + afcHelper_escapeHtmlChars(afcHelper_Submissions[id].parents) + '" />'); $extra.append(' '); $extra.append($(' ', {type: 'checkbox', name: 'afcHelper_redirect_container_' + id, id: 'afcHelper_redirect_container_' + id})); $extra.append('<label for="afcHelper_redirect_container_' + id + '">This is a <a href="/wiki/Wikipedia:Container_category" title="Wikipedia:Container category">container category</a> '); $extra.html($extra.html + ' <input type="checkbox" name="afcHelper_redirect_container_' + id + '"'); }           $extra.html($extra.html + ' <label for="afcHelper_redirect_comment_' + id + '">Comment: ' + '<input type="text" size="100" id="afcHelper_redirect_comment_' + id + '" name="afcHelper_redirect_comment_' + id + '"/>'); } else if (selectValue === 'decline') { if (afcHelper_Submissions[id].type === 'redirect') { $extra.html('<label for="afcHelper_redirect_decline_' + id + '">Reason for decline: ' + afcHelper_generateSelect('afcHelper_redirect_decline_' + id, [ {                       label: 'Already exists', value: 'exists' }, {                       label: 'Blank request', value: 'blank' }, {                       label: 'No valid target specified', value: 'notarget' }, {                       label: 'Unlikely search term', value: 'unlikely' }, {                       label: 'Not a redirect request', value: 'notredirect' }, {                       label: 'Custom - reason below', selected: true, value: 'custom' }]));           } else { // now Categories $extra.html('<label for="afcHelper_redirect_decline_' + id + '">Reason for decline: ' + afcHelper_generateSelect('afcHelper_redirect_decline_' + id, [{ label: 'Already exists', value: 'exists' }, {                   label: 'Blank request', value: 'blank' }, {                   label: 'Unlikely category', value: 'unlikely' }, {                   label: 'Not a category request', value: 'notcategory' }, {                   label: 'Custom - reason below', selected: true, value: 'custom' }]));           }            $extra.html($extra.html + ' <label for="afcHelper_redirect_comment_' + id + '">Comment: ' + '<input type="text" size="100" id="afcHelper_redirect_comment_' + id + '" name="afcHelper_redirect_comment_' + id + '"/>'); } else if (selectValue === 'none'){ // for categories and redirects! $extra.html(''); } else { $extra.html($extra.html + '<label for="afcHelper_redirect_comment_' + id + '">Comment: ' + '<input type="text" size="100" id="afcHelper_redirect_comment_' + id + '" name="afcHelper_redirect_comment_' + id + '"/>'); }   }

function afcHelper_redirect_performActions { // Load all of the data. for (var i = 0; i < afcHelper_Submissions.length; i++) { var action = $("#afcHelper_redirect_action_" + i).val; afcHelper_Submissions[i].action = action; if (action === 'none') continue; if (action === 'accept') { if (afcHelper_Submissions[i].type === 'redirect') { afcHelper_Submissions[i].title = $("#afcHelper_redirect_from_" + i).val; afcHelper_Submissions[i].to = $("#afcHelper_redirect_to_" + i).val; afcHelper_Submissions[i].append = $("#afcHelper_redirect_append_" + i).val; if (afcHelper_Submissions[i].append === 'custom') { afcHelper_Submissions[i].append = prompt("Please enter the template to append to " + afcHelper_Submissions[i].title + ". Do not include the curly brackets."); }                   if (afcHelper_Submissions[i].append === 'none' || afcHelper_Submissions[i].append === null) afcHelper_Submissions[i].append = ''; else afcHelper_Submissions[i].append = '\{\{' + afcHelper_Submissions[i].append + '\}\}'; } else { afcHelper_Submissions[i].title = $("#afcHelper_redirect_name_" + i).val; afcHelper_Submissions[i].parents = $("#afcHelper_redirect_parents_" + i).val; afcHelper_Submissions[i].container = $("#afcHelper_redirect_container_" + i).is(':checked'); }           } else if (action === 'decline') { afcHelper_Submissions[i].reason = $('#afcHelper_redirect_decline_' + i).val; }           afcHelper_Submissions[i].comment = $("#afcHelper_redirect_comment_" + i).val; }       // Data loaded. Show progress screen and get WP:AFC/R page text. displayMessage('<ul id="afcHelper_status"></ul><ul id="afcHelper_finish"></ul>'); var addStatus = function ( status ) { $('#afcHelper_status').append( status ); }; $('#afcHelper_finish').html($('#afcHelper_finish').html + '<span id="afcHelper_finished_wrapper"><span id="afcHelper_finished_main" style="display:none"><li id="afcHelper_done">Done (<a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(afcHelper_RedirectPageName)) + '?action=purge" title="' + afcHelper_RedirectPageName + '">Reload page</a>)</li> '); pagetext = afcHelper_getPageText(afcHelper_RedirectPageName, addStatus); var totalaccept = 0; var totaldecline = 0; var totalcomment = 0; // traverse the submissions and locate the relevant sections. addStatus('<li>Processing ' + afcHelper_RedirectSubmissions.length + ' submission' +           (afcHelper_RedirectSubmissions.length === 1 ? '' : 's') + '...</li>'); for (var i = 0; i < afcHelper_RedirectSubmissions.length; i++) { var sub = afcHelper_RedirectSubmissions[i]; if (pagetext.indexOf(afcHelper_RedirectSections[sub.section]) === -1) { // Someone has modified the section in the mean time. Skip. addStatus('<li>Skipping ' + sub.title + ': Cannot find section. Perhaps it was modified in the mean time?</li>'); continue; }           var text = afcHelper_RedirectSections[sub.section]; var startindex = pagetext.indexOf(afcHelper_RedirectSections[sub.section]); var endindex = startindex + text.length;

// First deal with cats. These are easy. if (sub.type === 'category') { if (sub.action === 'accept') { var cattext = ''; if (sub.container) { cattext += '\n'; }                   if (sub.parents !== '') { cattext = sub.parents .split(',') .map(function(cat){ return '\[\[' + cat + '\]\]'; }) .join('\n'); }                   afcHelper_editPage(sub.title, cattext, 'Created via \[\[WP:AFC|Articles for Creation\]\] (\[\[WP:WPAFC|you can help!\]\])', true); var talktext = '\{\{subst:WPAFC/article|class=Cat\}\}'; var talktitle = sub.title.replace(/Category:/gi, 'Category talk:'); afcHelper_editPage(talktitle, talktext, 'Placing WPAFC project banner', true); var header = text.match(/==[^=]*==/)[0]; text = header + "\n\{\{AfC-c|a\}\}\n" + text.substring(header.length); if (sub.comment !== '') text += '\n*\{\{subst:afc category|accept|2=' + sub.comment + '\}\} \~\~\~\~\n'; else text += '\n*\{\{subst:afc category\}\} \~\~\~\~\n'; text += '\{\{AfC-c|b\}\}\n'; totalaccept++; } else if (sub.action === 'decline') { var header = text.match(/==[^=]*==/)[0]; var reason = afcHelper_categoryDecline_reasonhash[sub.reason]; if (reason === '') reason = sub.comment; else if (sub.comment !== '') reason = reason + ': ' + sub.comment; if (reason === '') { $('afcHelper_status').html($('#afcHelper_status').html + '<li>Skipping ' + sub.title + ': No decline reason specified.</li>'); continue; }                   text = header + "\n\{\{AfC-c|d\}\}\n" + text.substring(header.length); if (sub.comment === '') text += '\n*\{\{subst:afc category|' + sub.reason + '\}\} \~\~\~\~\n'; else text += '\n*\{\{subst:afc category|decline|2=' + reason + '\}\} \~\~\~\~\n'; text += '\{\{AfC-c|b\}\}\n'; totaldecline++; } else if (sub.action === 'comment') { if (sub.comment !== '') text += '\n\n\{\{afc comment|1=' + sub.comment + ' \~\~\~\~\}\}\n'; totalcomment++; }           } else { // redirects...... var acceptcomment = ''; var declinecomment = ''; var othercomment = ''; var acceptcount = 0, declinecount = 0, commentcount = 0, hascomment = false; for (var j = 0; j < sub.from.length; j++) { var redirect = sub.from[j]; if (redirect.action === 'accept') { var redirecttext = '#REDIRECT \[\[' + redirect.to + '\]\]\n' + redirect.append; afcHelper_editPage(redirect.title, redirecttext, 'Redirected page to \[\[' + redirect.to + '\]\] via \[\[WP:AFC|Articles for Creation\]\] (\[\[WP:WPAFC|you can help!\]\])', true); var talktext = '\{\{subst:WPAFC/redirect\}\}'; var talktitle = 'Talk:' + redirect.title; afcHelper_editPage(talktitle, talktext, 'Placing WPAFC project banner', true); acceptcomment += redirect.title + " &rarr; " + redirect.to; if (redirect.comment !== '') { acceptcomment += ': ' + redirect.comment; hascomment = true; } else { acceptcomment += '. ';                       }                        acceptcount++; } else if (redirect.action === 'decline') { var reason = afcHelper_redirectDecline_reasonhash[redirect.reason]; if (reason === '') reason = redirect.comment; else if (redirect.comment !== '') reason = reason + ': ' + redirect.comment; if (reason === '') { $('#afcHelper_status').html($('#afcHelper_status').html + '<li>Skipping ' + redirect.title + ': No decline reason specified.</li>'); continue; }                       declinecomment += ((redirect.reason === 'blank' || redirect.reason === 'notredirect') ? reason + ". " : redirect.title + " &rarr; " + redirect.to + ": " + reason + ". "); declinecount++; } else if (redirect.action === 'comment') { othercomment += redirect.title + ": " + redirect.comment + ". "; commentcount++; }               }                var reason = '';

if (acceptcount > 0) reason += '\n*\{\{subst:afc redirect|accept|2=' + acceptcomment + ' Thank you for your contributions to Wikipedia!\}\} \~\~\~\~'; if (declinecount > 0) reason += '\n*\{\{subst:afc redirect|decline|2=' + declinecomment + '\}\} \~\~\~\~'; if (commentcount > 0) reason += '\n*\{\{afc comment|1=' + othercomment + '\~\~\~\~\}\}'; reason += '\n'; if (!hascomment && acceptcount === sub.from.length) { if (acceptcount > 1) reason = '\n*\{\{subst:afc redirect|all\}\} \~\~\~\~\n'; else reason = '\n*\{\{subst:afc redirect\}\} \~\~\~\~\n'; }               if (acceptcount + declinecount + commentcount > 0) { if (acceptcount + declinecount === sub.from.length) { // Every request disposed of. Close. var header = text.match(/==[^=]*==/)[0]; if (acceptcount > declinecount) text = header + "\n\{\{AfC-c|a\}\}\n" + text.substring(header.length); else text = header + "\n\{\{AfC-c|d\}\}\n" + text.substring(header.length); text += reason; text += '\{\{AfC-c|b\}\}\n'; } else text += reason + '\n'; }               totalaccept += acceptcount; totaldecline += declinecount; totalcomment += commentcount; }           pagetext = pagetext.substring(0, startindex) + text + pagetext.substring(endindex); }

var summary = "Updating submission status:"; if (totalaccept > 0) summary += " accepting " + totalaccept + " request" + (totalaccept > 1 ? 's' : ''); if (totaldecline > 0) { if (totalaccept > 0) summary += ','; summary += " declining " + totaldecline + " request" + (totaldecline > 1 ? 's' : ''); }       if (totalcomment > 0) { if (totalaccept > 0 || totaldecline > 0) summary += ','; summary += " commenting on " + totalcomment + " request" + (totalcomment > 1 ? 's' : ''); }

afcHelper_editPage(afcHelper_RedirectPageName, pagetext, summary, false);

// Display the "Done" text only after all ajax requests are completed $(document).ajaxStop(function {            $("#afcHelper_finished_main").css("display", "");        }); }

/**    * Gets the text of a page. * @param {string} The title of the page to get. * @param {function} A function that takes a HTML string to report status. */   function afcHelper_getPageText(title, addStatus) { var addStatus = typeof addStatus !== 'undefined' ? addStatus : function ( status ) {}; addStatus('<li id="afcHelper_get' + jqEsc(title) + '">Getting <a href="' +               mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' +                title + '</a></li>');

var request = { 'action': 'query', 'prop': 'revisions', 'rvprop': 'content', 'format': 'json', 'indexpageids': true, 'titles' : title };

var response = JSON.parse(           $.ajax({ url: mw.util.wikiScript('api'), data: request, async: false })           .responseText        );

pageid = response['query']['pageids'][0]; if (pageid === "-1") { addStatus('The page <a class="new" href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) +               '" title="' + title + '">' + title + '</a> does not exist'); return ''; }       var newtext = response['query']['pages'][pageid]['revisions'][0]['*']; addStatus('<li id="afcHelper_get' + jqEsc(title) + '">Got <a href="' +               mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></li>'); return newtext; }

function afcHelper_cleanuplinks(text) { // Convert external links to Wikipedia articles to proper wikilinks var wikilink_re = /(\[){1,2}(?:https?:)?\/\/(en.wikipedia.org\/wiki|enwp.org)\/([^\s\|\]\[]+)(\s|\|)?((?:\[\^\[\*\]\]|[^\]\[])*)(\]){1,2}/gi; var temptext = text; var match; while (match = wikilink_re.exec(temptext)) { var pagename = decodeURI(match[3].replace(/_/g,' ')); var displayname = decodeURI(match[5].replace(/_/g,' ')); if (pagename === displayname) displayname = ''; var replacetext =  + displayname : ) + ''; pagetext = pagetext.replace(match[0],replacetext); }       return text; }

function afcHelper_generateSelect(title, options, onchange) { var text = '<select name="' + title + '" id="' + title + '" '; if (onchange !== null) text += 'onchange = "' + onchange + '" '; text += '>'; for (var i = 0; i < options.length; i++) { var o = options[i]; text += '<option value="' + afcHelper_escapeHtmlChars(o.value) + '" '; if (o.selected) text += 'selected="selected" '; if (o.disabled) text += 'disabled '; text += '>' + o.label + ' '; }       text += " "; return text; }

/**    * Like the other function, except this one returns a jQuery object. * This time, however, onchange should be an actual function object. */   function afcHelper_generateSelectObject(title, options, onchange) { var $select = $(' ') .attr('name', title) .attr('id', title); if ( onchange !== null ) { $select.change(function{console.log("IN CHANGE HANDLER");}); $select.change(onchange); }       options.forEach( function ( option ) {            var $option = $( ' ' )                .appendTo( $select )                .val( afcHelper_escapeHtmlChars( option.value) )                .text( option.label );            if ( option.selected ) $option.attr( 'selected', 'selected' );            if ( option.disabled ) $option.attr( 'disabled', 'disabled' );        } ); return $select; }

function afcHelper_escapeHtmlChars(original) { return original.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");   }

/**    * The old mw.util.jsMessage function before https://gerrit.wikimedia.org/r/#/c/17605/, which * introduced the silly auto-hide function. Also with the original styles. * Add a little box at the top of the screen to inform the user of    * something, replacing any previous message. * Calling with no arguments, with an empty string or null will hide the message * Taken from User:Timotheus Canens/displaymessage.js *    * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box. * @param className {String} Used in adding a class; should be different for each call * to allow CSS/JS to hide different boxes. null = no class used. * @return {Boolean} True on success, false on failure. */   function displayMessage( message, className ){ if ( !arguments.length || message === '' || message === null ) { $( '#display-message' ).empty.hide; return true; // Emptying and hiding message is intended behaviour, return true } else { // We special-case skin structures provided by the software. Skins that // choose to abandon or significantly modify our formatting can just define // an mw-js-message div to start with. var $messageDiv = $( '#display-message' ); if ( !$messageDiv.length ) { $messageDiv = $( '<div id="display-message" style="margin:1em;padding:0.5em 2.5%;border:solid 1px #ddd;background-color:#fcfcfc;font-size: 0.8em"> ' ); if ( mw.util.$content.length ) { mw.util.$content.prepend( $messageDiv ); } else { return false; }           }            if ( className ) { $messageDiv.prop( 'class', 'display-message-' + className ); }           if ( typeof message === 'object' ) { $messageDiv.empty; $messageDiv.append( message ); } else { $messageDiv.html( message ); }           $messageDiv.slideDown; return true; }   }

function jqEsc(expression) { return expression.replace(/[!"#$%&'*+,.\/:;<=>?@\[\\\]^`{|}~ ]/g, '');    }

function afcHelper_editPage(title, newtext, summary, createonly, nopatrol) { var edittoken = mw.user.tokens.get('csrfToken'); summary += afcHelper_advert; $("#afcHelper_finished_wrapper").html('<span id="afcHelper_AJAX_finished_' + afcHelper_AJAXnumber + '" style="display:none">' + $("#afcHelper_finished_wrapper").html + ' '); var func_id = afcHelper_AJAXnumber; afcHelper_AJAXnumber++; $('#afcHelper_status').html($('#afcHelper_status').html + '<li id="afcHelper_edit' + jqEsc(title) + '">Editing <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></li>'); var request = { 'action': 'edit', 'title': title, 'text': newtext, 'summary': summary, 'token': edittoken };       if (createonly) request.createonly = true;

var api = new mw.Api; api.post(request) .done(function ( data ) {                   if ( data && data.edit && data.edit.result && data.edit.result == 'Success' ) {                        $('#afcHelper_edit' + jqEsc(title)).html('Saved <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a>');                    } else {                        $('#afcHelper_edit' + jqEsc(title)).html('<span class="afcHelper_notice">Edit failed on <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a>. Error info: ' + JSON.stringify(data));                       window.console && console.error('Edit failed on %s (%s). Error info: %s', mw.config.get('wgArticlePath').replace("$1", encodeURI(title)), title, JSON.stringify(data));                   }                } ) .fail( function ( error ) {                   if (createonly && error == "articleexists")                        $('#afcHelper_edit' + jqEsc(title)).html('<span class="afcHelper_notice">Edit failed on <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a>. Error info: The article already exists!');                   else                        $('#afcHelper_edit' + jqEsc(title)).html('<span class="afcHelper_notice">Edit failed on <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a>. Error info: ' + error);                }) .always( function {                    $("#afcHelper_AJAX_finished_" + func_id).css("display", '');                });

if (!nopatrol) { /* We patrol by default */ if ($('.patrollink').length) { // Extract the rcid token from the "Mark page as patrolled" link on page var patrolhref = $('.patrollink a').attr('href'); var rcid = mw.util.getParamValue('rcid', patrolhref);

if (rcid) { $('#afcHelper_status').html($('#afcHelper_status').html + '<li id="afcHelper_patrol' + jqEsc(title) + '">Marking <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + ' as patrolled</a></li>'); var patrolrequest = { 'action': 'patrol', 'format': 'json', 'token': mw.user.tokens.get('patrolToken'), 'rcid': rcid };                   api.post(patrolrequest) .done(function ( data ) {                               if ( data ) {                                    $('#afcHelper_patrol' + jqEsc(title)).html('Marked <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a> as patrolled');                                } else {                                    $('#afcHelper_patrol' + jqEsc(title)).html('<span class="afcHelper_notice">Patrolling failed on <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a> with an unknown error');                                    window.console && console.error('Patrolling failed on %s (%s) with an unknown error.', mw.config.get('wgArticlePath').replace("$1", encodeURI(title)), title);                                }                            } ) .fail( function ( error ) {                               $('#afcHelper_patrol' + jqEsc(title)).html('<span class="afcHelper_notice">Patrolling failed on <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a>. Error info: ' + error);                            }); }                          }        }    }

// From http://stackoverflow.com/a/6323598/1757964 function allMatches ( regex, string ) { var matches = [], match; do { match = regex.exec( string ); if ( match ) { matches.push( match ); }       } while ( match ); return matches; }

// Create portlet link var redirectportletLink = mw.util.addPortletLink('p-cactions', '#', 'Review AFC/R', 'ca-afcrhs', 'Review', 'a'); // Bind click handler $(redirectportletLink).click(function(e) {       e.preventDefault;        // clear variables for the case somebody is clicking multiple times on "review"        afcHelper_RedirectSubmissions.length = 0;        afcHelper_RedirectSections.length = 0;        afcHelper_numTotal = 0;        afcHelper_Submissions.length = 0;        needsupdate.length = 0;        afcHelper_redirect_init;    }); }); //

//

//Mass rollback function //Written by John254 //Adapted from User:Mr.Z-man/rollbackSummary.js //Instructions: Selecting the "rollback all" tab when viewing a user's contributions history //will open all rollback links displayed there. (Use with caution)

jQuery(document).ready(function ($) {

function rollbackEverything { for (var i in document.links) { if (document.links[i].href.indexOf('action=rollback') != -1) { window.open(document.links[i].href); }		}	}

function rollbackEverythingButton { var hasRollback = $("span.mw-rollback-link"); if (hasRollback[0] && (document.title.indexOf("User contributions") !== -1) ) { var link = mw.util.addPortletLink(				'p-cactions',				'#',				'rollback all',				'ca-rollbackeverything',				'rollback all edits displayed here'			); $(link).click(function (e) {				e.preventDefault;				rollbackEverything;			}); }	}

mw.loader.using(['mediawiki.util'], function {		rollbackEverythingButton;	});

});

importScript( 'User:Andy M. Wang/pageswap.js' ); // Backlink: User:Andy M. Wang/pageswap

importScript( 'User:Evad37/MoveToDraft.js' ); // Backlink: User:Evad37/MoveToDraft importScript( 'User:Technical 13/Scripts/OrphanStatus.js' );// User:Technical 13/Scripts/OrphanStatus importScript( 'User:Qwertyytrewqqwerty/DisamAssist.js'); importScript("User:Writ Keeper/Scripts/teahouseUtility.js"); // Gives one-click option to add Teahouse invitation or talkback to a user

importScript("User:Writ Keeper/Scripts/teahouseTalkback.js"); // Adds Talkback reminder when you save an edit at the Teahouse

importScript("User:Writ Keeper/Scripts/teahouseTalkbackLink.js"); // Adds a talkback link to signatures on the Teahouse

importScript("User:Ocaasi/WikiLoveinstallscript.js");// Adds Teahouse Badges to WikiLove importscritp("User:Timotheus Canens/spihelper.js");