User:Writ Keeper/Scripts/deorphanizer.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.
function deorphanArticle()
{
	var api = new mw.Api();
	api.get({
		"action":"query", 
		"prop":"revisions",
		"pageids":mw.config.get("wgArticleId"),
		"rvlimit":1,
		"rvprop":"content"
	}).done(function(data) 
	{
		var articleText = data.query.pages[mw.config.get("wgArticleId")].revisions[0]["*"];
		var orphanRegex = /\s*\{\{[oO]rphan[^\}]*\}\}\s*/;
		if(orphanRegex.test(articleText))
		{
			var revisedText = articleText.replace(orphanRegex,"");
			api.postWithToken("edit", {
				"action":"edit",
				"pageid":mw.config.get("wgArticleId"), 
				"summary":"No longer an orphan. You can help: [[WP:ORPHANAGE|WikiProject Orphanage]].", 
				"text":revisedText
			}).done(function (result)
			{
				mw.log("saving edit; reloading page");
				location.reload();
			}).fail(function (result)
			{
				mw.log("page edit failed; page not modified");
				$("#ca-deorphan").text("De-orphan failed");
				$("#ca-deorphan").off("click");
			});
		}
	}).fail(function (data)
	{
		mw.log("Wikitext retrieval failed; page not modified");
		$("#ca-deorphan").text("De-orphan failed");
		$("#ca-deorphan").off("click");
	});
}

mw.loader.using( ['mediawiki.util', 'mediawiki.api'], function() 
{
	if($.inArray("All orphaned articles",mw.config.get("wgCategories")) > -1)
	{
		mw.util.addPortletLink( 'p-cactions', '#',
			'De-orphan', 'ca-deorphan', 'De-orphan the current article');
		$("#ca-deorphan").click( deorphanArticle );
	}
});