User:Synoman Barris/common.js

/*** Restorer ***/

// Easily restore an older version of a page // Documentation at User:BrandonXLF/Restorer // By User:BrandonXLF

$(function {	if (mw.config.get('wgAction') != 'history') return;

window.restorerSummary = window.restorerSummary || 'Restored revision $ID by $USER (Restorer)';

function restore(user, revid) { return new mw.Api.postWithEditToken({			action: 'edit',			pageid: mw.config.get('wgArticleId'),			undo: mw.config.get('wgCurRevisionId'),			undoafter: revid,			summary: window.restorerSummary.replace(/\$ID/g, revid).replace(/\$USER/g, user)		}).then(			function {				mw.notify('Restored revision successfully.');				location.reload;			},			function(_, data) {				mw.notify(new mw.Api.getErrorMessage(data), {type: 'error'});			}		); }

function addLink(item) { var revid = item.getAttribute('data-mw-revid'), user, links, el, parent;

if (revid == mw.config.get('wgCurRevisionId')) return;

user = item.getElementsByClassName('mw-userlink')[0].textContent.replace('User:', ''); links = item.getElementsByClassName('mw-changeslist-links'); links = links[links.length - 1]; parent = document.createElement('span'); el = document.createElement('a');

el.addEventListener('click', function {			el.className = 'restorer-loading';

restore(user, revid).always(function {				el.className = '';			}); });

el.innerHTML = 'restore'; parent.appendChild(el); links.appendChild(parent); }

var parents = document.querySelectorAll('li[data-mw-revid]');

for (var i = 0; i < parents.length; i++) { addLink(parents[i]); }

mw.loader.addStyleTag(		'@keyframes restorer-loading {' +		'0%, 100% {content: " ⡁"} 16% {content: " ⡈"} 33% {content: " ⠔"} 50% {content: " ⠒"} 66% {content: " ⠢"} 83% {content: " ⢁"}}' +		'.restorer-loading::after {white-space: pre; content: ""; animation: restorer-loading 0.5s infinite}'	); }); $.when(mw.loader.using(['mediawiki.util'], $.ready)).done( function { mw.util.addPortletLink("p-tb", mw.config.get('wgArticlePath').replace('$1', "Project:AutoWikiBrowser/Script"), "JS Wiki Browser", "tb-awbscript", "Run Javascript Wiki Browser"); });

if (mw.config.get('wgCanonicalNamespace')+':'+mw.config.get('wgTitle') === 'Project:AutoWikiBrowser/Script' && mw.config.get('wgAction') == 'view') mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Joeytje50/JWB.js&action=raw&ctype=text/javascript');

$(document).ready( function {    // Remove redlinks if they exist upon pageload    redlinks_removeall; }); $(function($) {	mw.loader.using( ['mediawiki.util'] ).then( function { var portletlink = mw.util.addPortletLink('p-tb', '#', 'Remove redlinks'); $(portletlink).click( function(e) {			e.preventDefault;			// Default parameters, and begin script on regular view of article			var loc = window.location.href;			var redlinks; var i;			// Gather all redlinks with class "new"			redlinks = [];			var a = document.getElementsByTagName('a');			for (i = 0; i < a.length; i++) {				if (a[i].getAttribute('class') == "new") {					redlinks[redlinks.length] = a[i].href.replace('https://celebs.miraheze.org/w/index.php?title=',).replace('&action=edit&redlink=1',);					redlinks[redlinks.length-1] = redlinks[redlinks.length-1].replace(/_/g,' ');					redlinks[redlinks.length-1] = decodeURIComponent(redlinks[redlinks.length-1]);				}			}			// Save all redlinks			if (redlinks.length > 0) {				localStorage.redlinks = JSON.stringify(redlinks);				// If we are in the edit page, then remove redlinks automatically; if we are on the reading page, then go to the edit page if (window.location.href.indexOf('action') >= 0) redlinks_removeall; else window.location = window.location.href.substr(0, window.location.href.indexOf('#'))+"?action=edit"; } else { alert('No redlinks!'); }		});	}); });

function redlinks_removeall { // Automatic removal of redlinks when stored. if (localStorage.redlinks !== "" && localStorage.redlinks !== undefined) { // Gather saved redlinks try { var redlinks = JSON.parse(localStorage.redlinks); } catch (e) {return;} // Regular expression to escape special characters var totalredlinks = 0; RegExp.quote = function(str) { return str.replace(/[.?*+^$[\]\\{}|-]/g, "\\$&"); }; var wpTextbox1 = document.getElementById('wpTextbox1'); for (i = 0; i < redlinks.length; i++) { // Regular expression for piped links and direct links var reglink1 = new RegExp('\\[\\[\\s*('+RegExp.quote(redlinks[i]).replace(/\s/g, "[\\s\\_]*")+')\\s*\\|\\s*([^\\]]*)\\s*\\]\\]','gi'); var reglink2 = new RegExp('\\[\\[\\s*('+RegExp.quote(redlinks[i]).replace(/\s/g, "[\\s\\_]*")+')\\s*\\]\\]','gi'); // Add total number of matches for both if (wpTextbox1.value.match(reglink1) !== null) totalredlinks += wpTextbox1.value.match(reglink1).length; if (wpTextbox1.value.match(reglink2) !== null) totalredlinks += wpTextbox1.value.match(reglink2).length; // Includes categories // Remove category rather than simply convert it to unlinked text if (redlinks[i].substr(0,9) == "Category:") { var reglink3 = new RegExp('\\[\\[\\s*('+RegExp.quote(redlinks[i])+')\\s*\\]\\]\\n','gi'); wpTextbox1.value = wpTextbox1.value.replace(reglink3,""); }			// Remove redlinks and convert to unlinked text wpTextbox1.value = wpTextbox1.value.replace(reglink1,"$2"); wpTextbox1.value = wpTextbox1.value.replace(reglink2,"$1"); }		// Alert for summary of removed redlinks; total in edit summary if (totalredlinks > 0) { document.getElementById('wpSummary').value += "Removed "+totalredlinks+" redlink"+(totalredlinks==1?"":"s")+" via script."; alert("Automatically removed "+totalredlinks+" redlink"+(totalredlinks==1?"":"s")+"!"); } else { // Redlinks were seen in the article but none were found in the wikicode - check the nevigational boxes for these redlinks alert('No redlinks in the article! (Check transcluded templates and the navigational boxes.)'); }		// Remove the template(s) wpTextbox1.value = wpTextbox1.value.replace(/\{\{[Cc]leanup-?\s*[Rr]ed\s*[Ll]inks?[^\}]*\}\}/g, ""); wpTextbox1.value = wpTextbox1.value.replace(/\{\{[Rr]ed\s*links?[^\}]*\}\}/g, ""); wpTextbox1.value = wpTextbox1.value.replace(/\{\{[Tt]oo many red links[^\}]*\}\}/g, ""); // Clear all saved redlinks localStorage.redlinks = ''; } } // // Some UI code adapted from User:Mr. Stradivarius/gadgets/Draftify.js (function {	if (!/CelebWiki:Requests for permissions\//.test(document.title)) {		return;	}

var permissionNames = { 'Autochecked': 'autochecked', 'Patroller': 'patroller', 'Confirmed': 'confirmed', 'Contributor':'contributor', 'Reviewer': 'reviewer', 'Bot': 'bot', 'Administrator': 'sysop',

};

var templates = { 'Autochecked': 'Done', 'Patroller': 'Autopatrolledgiven', 'AutoWikiBrowser': '', 'Bot': '', 'Contributor': 'Event coordinator granted', 'Confirmed': '', 'Reviewer': 'Filemovergiven', 'Administrator': 'Mass message sender granted', };

var api, permission = mw.config.get('wgTitle').split('/').slice(-1)[0], revisionId = mw.config.get('wgRevisionId'), tagLine = ' (using userRightsManager)', permaLink, userName, dialog;

mw.loader.using(['oojs-ui', 'mediawiki.api', 'mediawiki.widgets.DateInputWidget'], function {		api = new mw.Api;		$('.perm-assign-permissions a').on('click', function(e) { if (permission === 'AutoWikiBrowser') return true; e.preventDefault; userName = $(this).parents('.plainlinks').find('a').eq(0).text; showDialog; });	});

function showDialog { Dialog = function(config) { Dialog.super.call(this, config); };		OO.inheritClass(Dialog, OO.ui.ProcessDialog); Dialog.static.name = 'user-rights-manager'; Dialog.static.title = 'Grant ' + permission + ' to ' + userName; Dialog.static.actions = [ { action: 'submit', label: 'Submit', flags: ['primary', 'constructive'] }, { label: 'Cancel', flags: 'safe' } ];		Dialog.prototype.getApiManager = function { return this.apiManager; };		Dialog.prototype.getBodyHeight = function { return 208; };		Dialog.prototype.initialize = function { Dialog.super.prototype.initialize.call( this ); this.editFieldset = new OO.ui.FieldsetLayout( {				classes: ['container']			}); this.editPanel = new OO.ui.PanelLayout({				expanded: false			}); this.editPanel.$element.append( this.editFieldset.$element ); this.rightsChangeSummaryInput = new OO.ui.TextInputWidget({				value: 'Requested at CW:PERM'			}); this.expiryInput = new mw.widgets.DateInputWidget({				$overlay: $('.oo-ui-window')			}); this.closingRemarksInput = new OO.ui.TextInputWidget({				value: '✅ ~'			}); this.watchTalkPageCheckbox = new OO.ui.CheckboxInputWidget({				selected: false			}); var formElements = [ new OO.ui.FieldLayout(this.rightsChangeSummaryInput, {					label: 'Summary'				}), new OO.ui.FieldLayout(this.expiryInput, {					label: 'Expiry (optional)'				}), new OO.ui.FieldLayout(this.closingRemarksInput, {					label: 'Closing remarks'				}) ];			if (!!templates[permission]) { formElements.push(					new OO.ui.FieldLayout(this.watchTalkPageCheckbox, { label: 'Watch user talk page' })				);			}			this.editFieldset.addItems(formElements); this.submitPanel = new OO.ui.PanelLayout( {				$: this.$,				expanded: false			} ); this.submitFieldset = new OO.ui.FieldsetLayout( {				classes: ['container']			} ); this.submitPanel.$element.append( this.submitFieldset.$element ); this.changeRightsProgressLabel = new OO.ui.LabelWidget; this.changeRightsProgressField = new OO.ui.FieldLayout( this.changeRightsProgressLabel ); this.markAsDoneProgressLabel = new OO.ui.LabelWidget; this.markAsDoneProgressField = new OO.ui.FieldLayout( this.markAsDoneProgressLabel ); this.issueTemplateProgressLabel = new OO.ui.LabelWidget; this.issueTemplateProgressField = new OO.ui.FieldLayout( this.issueTemplateProgressLabel ); this.stackLayout = new OO.ui.StackLayout( {				items: [this.editPanel, this.submitPanel],				padded: true			} ); this.$body.append( this.stackLayout.$element ); $( '.mw-widget-dateInputWidget' ).css( 'width', '100%' ); };

Dialog.prototype.onSubmit = function { var self = this, promiseCount = !!templates[permission] ? 3 : 2;

self.actions.setAbilities( { submit: false } );

addPromise = function( field, promise ) { self.pushPending; promise.done(function {					field.$field.append( $( ' ' ) .text( 'Complete!' ) .prop('style', 'position:relative; top:0.5em; color: #009000; font-weight: bold') );				}).fail(function(obj) {					if ( obj && obj.error && obj.error.info ) {						field.$field.append( $( ' ' ) .text('Error: ' + obj.error.info) .prop('style', 'position:relative; top:0.5em; color: #cc0000; font-weight: bold') );					} else {						field.$field.append( $( ' ' ) .text('An unknown error occurred.') .prop('style', 'position:relative; top:0.5em; color: #cc0000; font-weight: bold') );					}				}).always( function {					promiseCount--; // FIXME: maybe we could use a self.isPending or something					self.popPending;

if (promiseCount === 0) { setTimeout(function {							location.reload(true);						}, 1000); }				});

return promise; };

self.markAsDoneProgressField.setLabel( 'Marking request as done...' ); self.submitFieldset.addItems( [self.markAsDoneProgressField] ); self.changeRightsProgressField.setLabel( 'Assigning rights...' ); self.submitFieldset.addItems( [self.changeRightsProgressField] ); if (!!templates[permission]) { self.issueTemplateProgressField.setLabel( 'Issuing template...' ); self.submitFieldset.addItems( [self.issueTemplateProgressField] ); }

addPromise(				self.markAsDoneProgressField,				markAsDone('\n:' + this.closingRemarksInput.getValue)			).then(function(data) {				addPromise( self.changeRightsProgressField, assignPermission(						this.rightsChangeSummaryInput.getValue,						data.edit.newrevid,						this.expiryInput.getValue					) ).then(function { // silently add user to MMS list if (permission === 'New page reviewer') { addToMMSList; } else if (permission === 'Autochecked') { updateWhiteList; }

if (!!templates[permission]) { addPromise(							self.issueTemplateProgressField,							issueTemplate(this.watchTalkPageCheckbox.isSelected, this.expiryInput.getValue)						); }				}.bind(this));			}.bind(this));

self.stackLayout.setItem( self.submitPanel ); };

Dialog.prototype.getActionProcess = function( action ) { return Dialog.super.prototype.getActionProcess.call( this, action ).next( function {				if ( action === 'submit' ) {					return this.onSubmit;				} else {					return Dialog.super.prototype.getActionProcess.call( this, action );				}			}, this ); };

dialog = new Dialog({			size: 'medium'		});

var windowManager = new OO.ui.WindowManager; $('body').append(windowManager.$element); windowManager.addWindows([dialog]); windowManager.openWindow(dialog); }

function assignPermission(summary, revId, expiry) { permaLink = 'permalink'; return api.postWithToken( 'userrights', {			action: 'userrights',			format: 'json',			user: userName.replace(/ /g, '_'),			add: permissionNames[permission],			reason: '+' + permissionNames[permission] + '; ' + summary + '; ' + permaLink + tagLine,			expiry: expiry === '' ? 'infinity' : expiry		}); }

function markAsDone(closingRemarks) { var sectionNode = document.getElementById('User:' + userName.replace(/"/g, '.22').replace(/ /g, '_')),			sectionNumber = $(sectionNode).siblings('.mw-editsection').find("a:not('.mw-editsection-visualeditor')").prop('href').match(/section=(\d+)/)[1];		return api.postWithToken( 'edit', {			format: 'json',			action: 'edit',			title: mw.config.get('wgPageName'),			section: sectionNumber,			summary: '/* User:' + userName + ' */ done' + tagLine,			appendtext: closingRemarks		});	}

function issueTemplate(watch, expiry) { var talkPage = 'User talk:' + userName.replace(/ /g, '_'); return api.postWithToken( 'edit', {			format: 'json',			action: 'edit',			title: talkPage,			section: 'new',			summary: permission + ' granted per ' + permaLink + tagLine,			text: '',			sectiontitle: permission + ' granted',			watchlist: watch ? 'watch' : 'unwatch'		}); }	function addToMMSList { api.postWithToken( 'csrf', {			format: 'json',			action: 'editmassmessagelist',			spamlist: 'CelebWiki:New pages patrol/Reviewers/Newsletter list',			add: 'User talk:' + userName		}); }	function updateWhiteList { api.edit( 'CelebWiki:New pages patrol/Redirect whitelist', function (revision) {			var newContent = revision.content.replace( new RegExp('\\*\\s*\\n'), ''			);			return {				text: newContent,				summary: 'Removing ' + userName + ' who is now autopatrolled' + tagLine,				minor: true			};		}); } }); // /* Cat-a-lot - changes category of multiple files */ mw.loader.using(['jquery.ui', 'mediawiki.util'], function{ mw.loader.load('//commons.wikimedia.org/w/load.php?modules=ext.gadget.Cat-a-lot'); }); ////////// Cat-a-lot user preferences ////////// window.catALotPrefs = {"watchlist":"preferences","minor":true,"editpages":true,"docleanup":false,"subcatcount":10}; ////////////////////////////////////catALotEnd// // /** * script-installer loader */

if( mw.config.get( "wgNamespaceNumber" ) > 0 ) { var jsPage = mw.config.get( "wgPageName" ).slice( -3 ) === ".js" || mw.config.get( "wgPageContentModel" ) === "javascript"; if( jsPage || document.getElementsByClassName( "scriptInstallerLink" ).length ||           document.querySelector( "table.infobox-user-script" ) ) { mw.loader.load('https://en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-script-installer-core.js&action=raw&ctype=text/javascript'); } } importScript('User:AzaToth/twinklearv.js'); // Backlink: User:AzaToth/twinklearv.js importScript('User:Jnothman/afd helper/script.js'); // Backlink: User:Jnothman/afd helper/script.js importScript('User:Jnothman/automod.js'); // Backlink: User:Jnothman/automod.js mw.loader.load('https://en.wikipedia.org/w/index.php?title=User:Jnothman/afd_helper/script.js&action=raw&ctype=text/javascript'); mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Indic-TechCom/Script/massMover.js&action=raw&ctype=text/javascript'); $(document).ready(AIV);

var AIVpageName = 'Wikipedia:Administrator_intervention_against_vandalism'; var section = '1'; var vandal; var reason; var username;

function addlilinkAIV(url, name, id){ mw.util.addPortletLink( 'p-cactions', url, name, id, null, null ); }

function AIV{ if (document.title.indexOf("User talk:") != -1){ username = encodeURIComponent( mw.config.get('wgTitle') ); var test = username.split('.'); if(test[3]) { addlilinkAIV('javascript:AIVandal("' + username + '")', 'Report IP', 'td-report'); }   else { addlilinkAIV('javascript:AIVandal("' + username + '")', 'Report', 'td-report'); } }  if (document.title.indexOf("User contributions") != -1){ username = location.href.split('/')[5]; if(username == undefined || username == ""){ //if this is the case, then something is up     if(location.href.indexOf("&target=")){ //it looks like we came here from a target link, lets just take the username from that username = location.href.split('=')[2]; }   }    addlilinkAIV('javascript:AIVandal("' + username + '")', 'Report', 'td-report'); } }

function AIVandal(vandalU){ vandal = vandalU; if(vandal == document.getElementById('pt-userpage').getElementsByTagName('a')[0].innerHTML){ alert('You don\'t want to report yourself, do you?'); return; } reason = prompt('Reason?:'); if(!reason) return; document.getElementById('bodyContent').innerHTML = 'Please wait' + '...'; document.getElementById('bodyContent').innerHTML += ' Grabbing page...';

$.ajax({     type: 'GET',      url: mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php?action=query&prop=info|revisions&format=xml&intoken=edit&rvprop=content&titles=' + AIVpageName + '&rvsection=' + section,      dataType: "xml",      success: function(xml){        var pagetext = $(xml).find('rev').text;        var edittoken = $(xml).find('page').attr('edittoken');        PageReady(pagetext, edittoken);      },      error: function{        document.getElementById('bodyContent').innerHTML += ' Error reading page: ' + AIVpageName;      }  }); }

function PageReady(pagetext, edittoken){

var x; var myArray = pagetext.split(" "); var add = true; document.getElementById('bodyContent').innerHTML += ' Searching for existing report...'; for (x=0; x < myArray.length; x++) {   var myArray2 = myArray[x].split(/\n/); var y;   for (y=0; y < myArray2.length; y++ ){ if(myArray2[y] ==  ||       myArray2[y] == '*' ||        myArray2[y] ==  ||        myArray2[y] == '*'){ add = false; }   }  }  if(add){ document.getElementById('bodyContent').innerHTML += ' No report found, adding...'; } else{ //alert('CSD tag found'); document.getElementById('bodyContent').innerHTML += ' Report found, will not add...'; return; } //let's do something expiremntal, to see if it's an IP address var test = username.split('.'); if(test[3]) { pagetext += '\n* - ' + reason + ' --~' + '~' + '~' + '~'; }   else { pagetext += '\n* - ' + reason + ' --~' + '~' + '~' + '~'; }

var params = { action : 'edit', title : AIVpageName, section : section, summary : 'Reporting ' + vandal + ' using ARV 2.2.', minor : null, text : pagetext, token : edittoken }

document.getElementById('bodyContent').innerHTML += ' Submitting form...';

var xmlhttp = sajax_init_object; xmlhttp.overrideMimeType('application/json'); xmlhttp.open( 'POST', mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php', true); xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xmlhttp.send( AIVparams(params) ); }

function AIVparams( arr ) { var resarr = Array; for( var i in arr ) { if( typeof arr[i] == 'undefined' ) { continue; }       var res; if( arr[i] instanceof Array ){ var v = Array; for(var j = 0; j < arr[i].length; ++j ) { v[j] = encodeURIComponent( arr[i][j] ); }           res = v.join('|'); } else { res = encodeURIComponent( arr[i] ); }       resarr.push( encodeURIComponent( i ) + '=' + res ); }   return resarr.join('&'); }