User:RillkeBot/AjaxSoftRedirects.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
if ('BrokenRedirects' === mw.config.get('wgCanonicalSpecialPageName') || 'Commons:Database reports/Broken redirects' === mw.config.get('wgPageName').replace(/_/g, ' ') ) {

// Load this script in special-namespace, too.
if (!window.AjaxDeleteOptOut  && -1 == mw.config.get('wgNamespaceNumber')) {
	importScript('MediaWiki:AjaxQuickDelete.js');
}
mediaWiki.loader.using('jquery.ui', function () {
	$(document).ready(function () {

	AjaxQuickDelete.umObtainEditToken = function () {
		this.edittoken = (this.edittoken || window['wikilove-edittoken'] || mw.user.tokens.get('csrfToken'));
		if (this.edittoken) {
			return;
		}
		var query = {
			action: 'query',
			prop: 'info',
			intoken: 'edit',
			titles: 'FAQ'  // Random title
		};
		this.doAPICall(query, 'umObtainEditTokenCB');
	}

	AjaxQuickDelete.umObtainEditTokenCB = function (result) {
		var pages = result.query.pages;
		for (var id in pages) { // there should be only one, but we don't know its ID
			this.edittoken = pages[id].edittoken;
		}
	}
	AjaxQuickDelete.savePage = function (page, summary, callback) {
		var edit = {
			action: 'edit',
			summary: summary,
			watchlist: (page.watchlist || 'preferences'),
			nocreate: '', // Do not create non-existing userpages
			title: page.title
		};
		if (page.redirect) edit.redirect = '';
		edit[page.editType] = page.text;
		edit.token = this.edittoken;
		this.doAPICall(edit, callback);
	}

	AjaxQuickDelete.doHTTPRequest = function (params, callback, requestType, requestURL) {
		var o = this;
		$.ajax({
			url: (requestURL || (mw.config.get('wgServer') + mw.config.get('wgScript'))),
			cache: false,
			dataType: 'html',
			data: params,
			type: requestType,
			success: function (result, status, x) {
				if (!result) return o.fail("Received empty response:\n" + x.responseText);
				if (x.status > 299) return o.fail("Status over 299 - fail\n" + x.responseText);
				if (x.status < 200) return this.showProgress(status);

				try {
					o[callback](result, params);
				} catch (e) {
					return o.fail(e);
				}
			},
			error: function (x, status, error) {
				return o.fail("API request returned code " + x.status + " " + status + "Error code is " + error);
			}
		});
	}

	AjaxQuickDelete.replaceWithSoftRedir = function () {
		var _this = this;
		var userRegEx = new RegExp('(' + mw.config.get('wgFormattedNamespaces')[2] + '.*:.+)');
		
		if ('Special:BrokenRedirects' == mw.config.get('wgPageName')) {
			$('.mw-spcontent > ol > li').each(function(x, v) {
			try {
				page= decodeURI($(v).children('del').children('a').eq(0).attr('href')).match(userRegEx)[1].replace(/_/g, " ");
				_this.log('Doing: '+page+'\n');
				_this.doHTTPRequest({ action: 'raw', title: page }, 'replaceWithSoftRedirCB', 'GET');
			} catch (ex) { _this.log('Error ' + ex + ' at ' + x) }
			});
		} else {
			$('table.sortable > tbody > tr > td > a').each(function(x, v) {
			try {
				page= decodeURI($(v).eq(0).attr('href')).match(userRegEx)[1].replace(/_/g, " ");
				_this.log('Doing: '+page+'\n');
				_this.doHTTPRequest({ action: 'raw', title: page }, 'replaceWithSoftRedirCB', 'GET');
			} catch (ex) { _this.log('Error ' + ex + ' at ' + x) }
			});
		}
	}

	AjaxQuickDelete.replaceWithSoftRedirCB = function (result, ref) {
		var talkRegEx = new RegExp(mw.config.get('wgFormattedNamespaces')[3]);
		if ('string' == typeof result) {
			if ("" != $.trim(result)) {
				resultO = result;
				result = result.replace(/^\s*\#\s*REDIRECT\s*\[\[:?((?:w:)?(?:\D{2,12}:)?[^:\]]+:[^:\]]+)\]\]/i, '{{Softredirect|:$1}}');
				var page = [];
				page.title = ref.title;
				page.text = result;
				page.watchlist = 'nochange';
				page.editType = 'text';
				if (resultO != result) { 
					this.showProgress('Saving ' + ref.title); 
					this.savePage(page, this.rrSummary + (talkRegEx.test(page.title) ? this.rrSummaryTalkAddition : ""), 'replaceWithSoftRedirCBCB'); 
				}
			}
		}
	}
	
	AjaxQuickDelete.log = function (t) {
		if (console && console.log) console.log(t);
	}

	AjaxQuickDelete.replaceWithSoftRedirCBCB = function (result) {
		this.log('success for ');
	}
	
	AjaxQuickDelete.rrSummary = "Script: Replacing broken redirect by Softredirect.";
	AjaxQuickDelete.rrSummaryTalkAddition = " [[Commons:Talk page guidelines#Can I do whatever I want to my own user talk page?|Do not attempt to redirect your user talk page to a talk page on another Wikimedia project.]]";

		mw.util.addPortletLink('p-tb', 'javascript:AjaxQuickDelete.replaceWithSoftRedir();', "Replace Redirs", 't-AjaxQuickDeletx3', null);

		AjaxQuickDelete.umObtainEditToken();
	});
});

} // Pages guard