User:TheNozomi/global.js

require(['jquery', 'mw', 'wikia.ui.factory', 'wikia.window'], function ($, mw, uiFactory, context) {   'use strict';    if (context.DiffModalLoaded) {        return;    }    context.DiffModalLoaded = true;    var lang = mw.config.get('wgUserLanguage');    var msg = {        en: {            error: 'Something went wrong while getting the page at “%url”.',            loading: 'Loading…',            title: 'Changes: %pagename'        },        be: {            error: 'Што-то пайшло не так падчас загрузкі старонкі «%url».',            loading: 'Загрузка…',            title: 'Змены: %pagename'        },        es: {            error: 'Un error ha occurido mientras se extraia la página en “%url”.',            loading: 'Cargando…',            title: 'Diferencia entre revisiones: %pagename'        },        it: {            error: 'Qualcosa è andato storto mentre si caricava la pagina da “%url”.', loading: 'Caricamento…', title: 'Modifiche: %pagename' },       nl: { error: 'Er ging iets verkeerd bij het ophalen van de pagina op “%url”.', loading: 'Laden…', title: 'Wijzigingen: %pagename' },       pl: { error: 'Coś się zepsuło podczas ładowania strony „%url”.', loading: 'Ładowanie…', title: 'Zmiany: %pagename' },       ru: { error: 'Что-то пошло не так во время загрузки страницы «%url».', loading: 'Загрузка…', title: 'Изменения: %pagename' },       uk: { error: 'Щось пішло не так під час завантаження сторінки «%url».', loading: 'Завантаження…', title: 'Зміни: %pagename' },       vi: { error: 'Đã có sự cố xảy ra khi tải trang tại đường dẫn “%url”.', loading: 'Đang tải…', title: 'Thay đổi: %pagename' }   };    msg = msg[lang] || msg[lang.split('-')['0']] || msg.en; var specialDiff = { en: 'Diff' };   specialDiff = mw.config.get('wgFormattedNamespaces')['-1'] + ':' + (specialDiff[mw.config.get('wgContentLanguage')] || specialDiff.en); var currentModal = null; var pendingModal = null; var uiModalFactory = null; function updateModal(modal) { if (!currentModal) { currentModal = modal; modal.$buttons = modal.$element.find('> footer > .buttons'); modal.$content.addClass('WikiaArticle'); pendingModal['1'] = pendingModal['1'] || msg.loading; }       var shouldFire = pendingModal['2']; if (pendingModal['1']) { modal.setTitle(msg.title.replace('%pagename', pendingModal['1'])); }       modal.setContent(pendingModal['0']); pendingModal = null; modal.$buttons.empty; if (shouldFire) { mw.hook('DiffModal.ready').fire(modal); }       modal.show; }   function loadModal { if (uiModalFactory) { uiModalFactory.createComponent({               vars: {                    content: '',                    id: 'diff-modal',                    size: 'large'                },                confirmCloseModal: function  {                    currentModal = null;                    return true;                }            }, updateModal); } else { uiFactory.init(['modal']).then(function (uiModal) {               uiModalFactory = uiModal;                loadModal;            }); }   }    function showModal(content, title, shouldFire) { if (pendingModal) { pendingModal = [content, title, shouldFire]; return; }       pendingModal = [content, title, shouldFire]; if (currentModal) { updateModal(currentModal); } else { loadModal; }   }    function loadDiff(url) { showModal(''); url.extend({           action: 'render',            diffonly: '1'        }); var urlString = url.toString; $.get(urlString).always(function (content) {           var $content = null;            var valid = false;            if (typeof content === 'string') {                $content = $(content);            }            if ($content && $content.hasClass('diff')) {                valid = true;            }            if (!valid && $content) {                var $contentDiff = $content.find('table.diff');                if ($contentDiff.length) {                    $content = $contentDiff;                    content = $contentDiff.prop('outerHTML');                    valid = true;                }            }            if (valid) {                var title = $content.find('#mw-diff-ntitle1 > strong > a').attr('title');                mw.loader.using('mediawiki.action.history.diff', function  { showModal(content, title, true); });           } else {                showModal(msg.error.replace('%url', urlString));            }        }); }   function init { mw.util.addCSS(           '#diff-modal > section {' +                'box-sizing: border-box;' +                'font-size: 13px;' +                'line-height: 21px;' +                'overflow: auto;' +                'position: relative;' +            '}' +            '#blackout_diff-modal ~ .modalWrapper {' +                'position: fixed;' +            '}'        ); $(document.body).on('click.DiffModal', 'a', function (event) {           var url = new mw.Uri(event.currentTarget.href);            if (url.host !== location.hostname) {                return;            }            var hasDiffParam = url.query.diff && !url.fragment;            var isSpecialDiffLink = event.currentTarget.title.indexOf(specialDiff + '/') === 0;            if (hasDiffParam || isSpecialDiffLink) {                event.preventDefault;                loadDiff(url);            }        }); }   $(init); mw.hook('DiffModal.ready').add(function (modal) {       var $buttons = modal.$content.find('.diff-ntitle')            .find('.mw-rev-head-action, .mw-rollback-link, .patrollink').clone;        $buttons.contents.filter(function (ignore, element) { return element.nodeType === 3; }).remove;       $buttons.find('a').addClass('button');        modal.$buttons.append($buttons);    }); }); window.UseCSS = {	skin: ,	init: function {		if (window.location.href.indexOf('usesitecss=') == -1) return;		var url = UseCSS.parseURL(window.location.href);		if (url.query.usesitecss) {			UseCSS.skin = (url.query.usewikicss || url.query.usesitecss);		}		if (UseCSS.skin != ) {			$(document.body).bind('click.usecss', UseCSS.clicEvent);			$('form').bind('submit.usecss', UseCSS.submitEvent);		}	},	parseURL: function(url) {		var ret = {base:,qs:,query:{},hash:''};		var loc = url.indexOf('#');		if (loc != -1) {			ret.hash = url.substr(loc+1);			url = url.substr(0,loc);		}		loc = url.indexOf('?');		if (loc != -1) {			ret.qs = url.substr(loc+1);			url = url.substr(0,loc);			var paras = ret.qs.split('&');			for (var i = 0; i < paras.length; i++) {				var p = paras[i].split('=');				if (p.length == 2) {					ret.query[p[0]] = p[1];				}			}		}		ret.base = url;		return ret;	},	getURL: function(url) { var nurl = url.base + '?'; for (var p in url.query) { nurl += p + '=' + url.query[p] + '&'; }		nurl = nurl.substr(0,nurl.length-1); if (url.hash != '') { nurl += '#'+ url.hash; }		return nurl; },	clicEvent: function(e) { if (e.target.tagName.toLowerCase != 'a') return; if (e.target.href.indexOf(window.wgServer) != 0) return; var url = UseCSS.parseURL(e.target.href); var thisloc = UseCSS.parseURL(window.location.href); if (url.base == thisloc.base && url.qs == thisloc.qs && url.hash != '') { return; }		if (url.query.usesitecss && url.query.usesitecss != UseCSS.skin) { url.query.usewikicss = UseCSS.skin; } else { url.query.usesitecss = UseCSS.skin; }		e.target.href = UseCSS.getURL(url); },	submitEvent: function(e) { if (this.action.indexOf(window.wgServer) != 0) return; if (this.method == 'post') { var url = UseCSS.parseURL(this.action); url.query.usesitecss = UseCSS.skin; this.action = UseCSS.getURL(url); } else { $(this).append(''); }	},	stop: function { $(document.body).unbind('click.usecss'); $('form').unbind('submit.usecss'); } }; $(UseCSS.init);

mw.loader.using('mediawiki.api', function {	if ($('.mw-rollback-link').length) return;	var conf = mw.config.get([ 'wgAction', 'wgCanonicalSpecialPageName', 'wgContentLanguage', 'wgPageName', 'wgUserLanguage', 'skin' ]),	i18n = {		en: {			rollback: "rollback",			description: "&quot;Rollback&quot; reverts edit(s) to this page of the last contributor in one click",			summary: "Reverted edits by $1 (talk | block) to last version by $2",			summaryShort: "Reverted edits by $1 (talk | block)",			editConflict: "Unable to rollback (edit conflict)",			contentFail: "Unable to rollback (failed to get page content)",			singleEditor: "Unable to rollback (no different editor found)",			revisionFail: "Unable to rollback (failed to get revisions)",			editFail: "Unable to rollback (failed to publish edit)",			success: "Rollback successful"		},		es: {			rollback: "rollback",			description: "&quot;Rollback&quot; reverts edit(s) to this page of the last contributor in one click",			summary: "Revertidos las ediciones de $1 (disc | bloquear) a la última edición de $2", summaryShort: "Revertidos las ediciones de $1 (disc | bloquear)", editConflict: "Unable to rollback (edit conflict)", contentFail: "Unable to rollback (failed to get page content)", singleEditor: "Unable to rollback (no different editor found)", revisionFail: "Unable to rollback (failed to get revisions)", editFail: "Unable to rollback (failed to publish edit)", success: "Rollback successful" }	};	i18n = i18n[conf.wgContentLanguage] || i18n[conf.wgContentLanguage.split('-')[0]] || i18n[conf.wgUserLanguage] || i18n[conf.wgUserLanguage.split('-')[0]] || i18n.en; if (conf.wgAction == "history" && $('#pagehistory li').length > 1) $('#pagehistory li:first .mw-history-undo a').before(' ' + i18n.rollback + ' | '); else if (conf.wgCanonicalSpecialPageName == "Contributions") { $('#mw-content-text ul').find('li').each(function {			if ($(this).find('.mw-uctop').length)				$(this).append(' [' + i18n.rollback + '] ');		}); }	else if (($.getUrlVar('diff') || $.getUrlVar('oldid')) && $('#differences-nextlink').length === 0) $('.mw-usertoollinks:last').after('   [' + i18n.rollback + '] '); else return; conf.API = new mw.Api; conf.token = mw.user.tokens.values.editToken; mw.util.addCSS('.mw-custom-rollback-link a { cursor: pointer; }'); $('.mw-custom-rollback-link a').click(function {		getRevisionIdAndContent($(this).data('id'),$(this).data('user').replace(/_/g, " "));		$(this).parent.remove;	}); function getRevisionIdAndContent(title,target) { conf.API.get({		action: 'query',		prop: 'revisions',		titles: title,		rvprop: 'user|ids',		rvlimit: 500,		cb: new Date.getTime		}) .done(function(d) {			if (!d.error) {				var revisions;				for (var i in d.query.pages) {					revisions = d.query.pages[i].revisions;				}				if (target != revisions[0].user) {					outputError(i18n.editConflict);					return;				}				var lastUser,				revId;				for (var i in revisions) {					if (revisions[i].user != target) {						lastUser = revisions[i].user;						revId = revisions[i].revid;						break;					}				}				if (lastUser) {					conf.API.get({ action: 'query', prop: 'revisions', rvprop: 'content', revids: revId, cb: new Date.getTime })					.done(function(d) { if (!d.error) { var content = ""; //can be no content on page for (var i in d.query.pages) { if (d.query.pages[i].revisions) content = d.query.pages[i].revisions[0]["*"]; }							performRollback(title,content,target,lastUser); }						else outputError(i18n.contentFail + ': ' + d.error.code); })					.fail(function { outputError(i18n.contentFail); });				}				else					outputError(i18n.singleEditor);			}			else				outputError(i18n.revisionFail + ': ' + d.error.code);		}) .fail(function {			outputError(i18n.revisionFail);		}); }	function performRollback(page,text,user,user2) { var summary = i18n.summary.replace(/\$1/g,user).replace(/\$2/g,user2); if (summary.length > 150) summary = i18n.summaryShort.replace('$1',user); conf.API.post({		action: 'edit',		title: page,		text: text,		summary: summary,		minor: true,		token: conf.token		}) .done(function(d) {			if (!d.error) {				new BannerNotification(i18n.success,'confirm').show;							}			else				outputError(i18n.editFail + ': ' + d.error.code);		}) .fail(function {			outputError(i18n.editFail);		}); }

function outputError(text) { switch (conf.skin) { case 'oasis': case 'wikia': new BannerNotification(text,'error').show; break; default: alert(text); break; }		} });

/* * Ajax batch delete thingy, version [0.0.3] by Grunny * Based on: http://en.wikipedia.org/wiki/User:Splarka/ajaxbatchdelete.js * Converted to use jQuery */ ( function ( mw, $, window, document ) {	"use strict";	// Prevent double runs	if ($('#t-ajaxbd').length)		return;	var skin = mw.config.get( 'skin' ),		wgServer = mw.config.get( 'wgServer' ),		wgScriptPath = mw.config.get( 'wgScriptPath' );	function createAjaxDeleteForm {		var	pageHeading = ( skin === 'oasis' ) ? ( $( '.AdminDashboardArticleHeader' ).length ? '.AdminDashboardArticleHeader > h1' : '.WikiaPageHeader > h1' ) : 'h1.firstHeading',			$bodyId = $( '#mw-content-text > p' ),			bdelFormHtml = ''				+ ' Delete reason: '				+ '   ';		$( pageHeading ).text( 'Ajax Batch Delete' );		$bodyId.text( 'List of pages to delete:' );		$bodyId.after( bdelFormHtml );		$( '#abd-startbutton' ).click( ajaxDeleteStart );	}	function ajaxDeleteStart {		document.getElementById( 'abd-startbutton' ).setAttribute( 'disabled', 'disabled' );		var	txt = document.getElementById( 'abd-textarea' ),			deletes = txt.value.split( '\n' ),			page = deletes[0],			reason = document.getElementById( 'abd-reason' ).value, badchars = /(\#|<|>|\[|\]|\{|\}|\|)/; if( page === '' ) { $( '#abd-output' ).append( '* Done! Nothing left to do, or next line is blank.\n' ); document.getElementById( 'abd-startbutton' ).removeAttribute( 'disabled' ); } else { if( badchars.test( page ) ) { $( '#abd-output' ).append( '! Illegal characters detected, skipping:' + page + '\n' ); setTimeout( ajaxDeleteStart, 1000 ); } else { $( '#abd-output' ).append( '> Attempting to delete ' + page + '\n' ); ajaxBatchDeleteAPage( page, reason ); }		}		deletes = deletes.slice( 1, deletes.length ); txt.value = deletes.join( '\n' ); }	function ajaxBatchDeleteAPage( title, deleteReason ) { var token = mw.user.tokens.get( 'editToken' ), url = wgServer + wgScriptPath + '/api.php?action=delete&title=' + window.encodeURIComponent( title ) + '&reason=' + window.encodeURIComponent( deleteReason ) + '&format=json&token=' + window.encodeURIComponent( token ); $.post( url, function( data ) {			if( data.error ) {				$( '#abd-output' ).append( '  > Error: ' + data.error.info + '\n' );			} else {				$( '#abd-output' ).append( '  > Deleted\n' );			}			setTimeout( ajaxDeleteStart, 1000 );		} ); }	$( function {		if( skin === 'monobook' ) {			mw.util.addPortletLink( 'p-tb', wgServer + wgScriptPath + '/index.php?title=Special:BlankPage&blankspecial=ajaxjqbd', 'Batch Delete', 't-ajaxbd' );		} else {			$( '#my-tools-menu' ).prepend( 'Batch Delete</a></li>' );		}		if( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Blankpage' || ('wgCanonicalSpecialPageName' ) === 'BlanquearPágina' && $.getUrlVar( 'blankspecial' ) === 'ajaxjqbd' ) {			document.title = 'Ajax Batch Delete';			createAjaxDeleteForm;		}	} ); } ( mediaWiki, jQuery, window, document ) );

// Script imports WHAMDelay = 100; importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:PortableCSSPad/code.js',        'u:dev:MediaWiki:WHAM/code.2.js',        'u:dev:MediaWiki:AjaxRedirect/code.js',        'u:dev:MediaWiki:FindAndReplace/code.js',        'u:dev:ListFiles/code.js',        'u:dev:Thread Inspection/code.js',        'u:dev:Nuke/code.js'    ] });