Jump to content

User:Frietjes/masspurge.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.
/// Mass Purge Tool
/// Adapted from [[User:Timotheus_Canens/massedit.js]]
/// Once installed, go to Special:MassPurge and provide a list of pages

var edited = 0, failed = [], error = []; 
function doMassPurge() {
	document.getElementById("wpMassPurgeSubmit1").disabled = true;
	document.getElementById("wpMassPurgeSubmit2").disabled = true;
	var templates = document.getElementById("wpMassPurgeTransclusions").value.split("\n");
	var articlelimit = Number(document.getElementById("wpMassPurgeTransclusionsLimit").value);
	if(templates.length > 0) {
		if(templates[0].search(/[^\s]/g) < 0) {
			templates.shift();
		}
	}
	if(templates.length > 0) {
		var articlelist = [];
		for(var j=0;j<templates.length;j++) {
			var k = 0;
			var loopflag = true;
			var ckey;
			while(loopflag) {
				k = k + 1;
				var req = new XMLHttpRequest();
				var cstr = "";
				if(k > 1) {
					cstr = "&eicontinue=" + ckey; 
				}
				req.open("GET", mw.config.get('wgScriptPath') + "/api.php?format=json" +
					"&action=query&continue=" + cstr + 
					"&list=embeddedin&eilimit=500&eititle=" + 
					encodeURIComponent(templates[j]), false);
				req.send();
				var response = JSON.parse(req.responseText).query.embeddedin;
				for(var index in response) {
					var info = response[index];
					articlelist.push(info.title);
				}
				if(JSON.parse(req.responseText).continue) {
					loopflag = true;
					ckey = JSON.parse(req.responseText).continue.eicontinue;
				} else {
					loopflag = false;
				}
				if(articlelist.length >= articlelimit) {
					loopflag = false;
				}
			}
		}
		articlelist.sort();
		articlelist = articlelist.filter( function( item, index, inputArray ) {
			return inputArray.indexOf(item) == index;
		});
		document.getElementById("wpMassPurgePages").value = 
			document.getElementById("wpMassPurgePages").value + '\n' + articlelist.join('\n');
	}
	document.getElementById("wpMassPurgePages").value = document.getElementById("wpMassPurgePages").value.replace(/[\r\n][\t ]*[\r\n]/, '\n');
	document.getElementById("wpMassPurgePages").value = document.getElementById("wpMassPurgePages").value.replace(/^[\t ]*[\r\n]/, '');
	var articles = document.getElementById("wpMassPurgePages").value.split("\n");
	articles.sort();
	var articlecount = articles.length;
	if(articles.length < 1) return;
	// The following is a convoluted method for a for loop with a 3 second per iteration delay
	var i=0;
	function myLoop () {
		setTimeout(function () {
			doPurge(articles[i], !articles[i+1],articlecount);
			i++;
			if(i<articles.length){
				myLoop();
			}
			}, 3000);
	}
	myLoop();
	// End loop code
}
function doPurge(article, lastflag, tcount){
	if(article.length > 0) {
		article = article.replace(/[\u200e\s]*\((?:redirect|transclusion)\)[\u200e\s]*$/, '');
		article = article.replace(/[\u200e\s]*\([\s]*links[\s]*\|[\s]*edit[\s]*\)[\u200e\s]*$/, '');
		var req = new XMLHttpRequest();
		req.open("GET", mw.config.get('wgScriptPath') + "/api.php?format=json&action=query&prop=info&meta=tokens&titles=" + encodeURIComponent(article), false);
		req.send();
		var edittoken = JSON.parse(req.responseText).query.tokens.csrftoken;
		var postdata = "format=json"
			+ "&action=edit&watchlist=nochange"
			+ "&title=" + encodeURIComponent(article)
			+ "&summary=" + "Null"
			+ "&token=" + encodeURIComponent(edittoken)
			+ "&nocreate=1"
			+ "&minor=1"
			+ "&prependtext=";
		req = new XMLHttpRequest();
		req.open("POST", mw.config.get('wgScriptPath') + "/api.php", false);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", postdata.length);
		req.send(postdata);
		if(JSON.parse(req.responseText).edit ) { //If edited, update the count and the button.
			edited++;
			document.getElementById("wpMassPurgeSubmit2").value = "(" + edited + " / " + tcount + ")";
		} else { //If not edited, add the title to the "failed" array and a description of the error to the "error" array.
			failed.push(article);
			error.push(JSON.parse(req.responseText).error.info);
		}
	}
	if(lastflag) {
		document.getElementById("wpMassPurgeSubmit2").value = "Done (" + edited + ")";
		if(failed.length > 0) {
			var linkedList = "";
			for(x=0; x<failed.length; x++) {
				linkedList += "<li><a href=\"" + mw.config.get('wgScript') + "?title=" + encodeURIComponent(failed[x]) + "\">" + failed[x] + "</a>: " + error[x] + "</li>"; //Links the titles in the "failed" array
			}
			document.getElementById("wpMassPurgeFailedContainer").innerHTML += '<br /><b>Failed edits:</b><ul>' + linkedList + '</ul>';
		}
	}
}

function masspurgeform() {
	var bodyContent = 'bodyContent';
	switch (mw.config.get('skin')) {
		case 'modern':
			bodyContent = 'mw_contentholder';
			break;
		case 'cologneblue':
			bodyContent = 'article';
			break;
		case 'vector':
		case 'monobook':
		case 'vector':
		default:
			bodyContent = 'bodyContent';
			break;
	}
	document.getElementsByTagName("h1")[0].textContent = "Mass purge tool";
	document.title = "Mass purge tool - Wikipedia, the free encyclopedia";
	document.getElementById(bodyContent).innerHTML = '<h3 id="siteSub">From Wikipedia, the free encyclopedia</h3><br /><br />'
		+ '<form id="wpMassPurge1" name="wpMassPurge1">'
		+ '<b>If you abuse this tool, it\'s <i>your</i> fault, not mine.</b>'
		+ '<div id="wpMassPurgeFailedContainer"></div>'
		+ '<p></p>'
			+ 'Limit (rounded up to nearest 500):'
			+ '<br /><input type="text" tabindex="1" name="wpMassPurgeTransclusionsLimit" id="wpMassPurgeTransclusionsLimit" value="5000" maxlength="6" />'
			+ '<br /><br />'
			+ 'Pages with transclusions to purge (one on each line, with namespace prefix):<br />'
			+ '<textarea tabindex="2" name="wpMassPurgeTransclusions" id="wpMassPurgeTransclusions" rows="5" cols="80"></textarea>'
			+ '<input type="button" id="wpMassPurgeSubmit1" name="wpMassPurgeSubmit1" value="Purge" onclick="doMassPurge()" />'
		+ '</form><form id="wpMassPurge2" name="wpMassPurge2">'
			+ 'Pages to purge (one on each line, please):<br />'
			+ '<textarea tabindex="3" name="wpMassPurgePages" id="wpMassPurgePages" rows="10" cols="80"></textarea>'
			+ '<input type="button" id="wpMassPurgeSubmit2" name="wpMassPurgeSubmit2" value="Purge" onclick="doMassPurge()" />'
		+ '</form>';
}
if(mw.config.get('wgNamespaceNumber') === -1 && (mw.config.get('wgTitle') === "Masspurge" || mw.config.get('wgTitle') === "MassPurge")
) {
	$.when( $.ready, mw.loader.using(['mediawiki.util'])).done( masspurgeform );
}