User:Psycwave/global.js

importArticles({   type: 'script',    articles: [    	'u:dev:MediaWiki:AllPagesHideRedirect/code.js',    	'u:dev:MediaWiki:BulkVideoUpload.js',    	'u:dev:MediaWiki:UsefulDropdown/code.js',        'u:dev:MediaWiki:AddArticleToCategory/code.js',        'u:dev:MediaWiki:AjaxRedirect/code.js',        'u:dev:MediaWiki:AjaxUndo/code.js',        'u:dev:MediaWiki:AnchoredRollback/code.js',        'u:dev:MediaWiki:EditConflictAlert/code.js',        'u:dev:MediaWiki:EditIntroButton/code.js',        'u:dev:MediaWiki:JWB/load.js',        'u:dev:MediaWiki:MassCategorization/code.js',        'u:dev:MediaWiki:MassNullEdit/code.js',        'u:dev:MediaWiki:MassRollback.js',        'u:dev:MediaWiki:MassSetTemplateType.js',        'u:dev:MediaWiki:NoImageLightbox/code.js',        'u:dev:MediaWiki:Nuke/code.js',        'u:dev:MediaWiki:NullEditButton/code.js',        'u:dev:MediaWiki:QuickTemplate/code.js', 'u:dev:MediaWiki:QuickTitle/code.js', 'u:dev:MediaWiki:Reconstitution.js', 'u:dev:MediaWiki:Rollback/code.js', 'u:dev:MediaWiki:UndeleteBacklink.js', 'u:dev:MediaWiki:UploadMultipleFiles.js', 'u:dev:MediaWiki:WantedPagesFilter/code.js' ] }); "use strict";  if (!window || !$ || !mw || module.isLoaded || window.isMassEditLoaded) {    return;  }  module.isLoaded = true;  var main, init;  main = {};  init = {};  Object.defineProperties(main, { Selectors: { enumerable: true, writable: false, configurable: false, value: Object.freeze({       ID_PLACEMENT_LIST: "massedit-placement-list",        ID_PLACEMENT_LINK: "massedit-placement-link",        ID_MODAL_CONTAINER: "massedit-modal-container",        ID_MODAL_SUBMIT: "massedit-modal-submit",        ID_MODAL_TOGGLE: "massedit-modal-toggle",        ID_MODAL_CANCEL: "massedit-modal-cancel",        ID_MODAL_PREVIEW: "massedit-modal-preview",        ID_MODAL_CLEAR: "massedit-modal-clear",        ID_MODAL_CLOSE: "massedit-modal-close",        ID_CONTENT_REPLACE: "massedit-content-replace",        ID_CONTENT_ADD: "massedit-content-add",        ID_CONTENT_MESSAGE: "massedit-content-message",        ID_CONTENT_LIST: "massedit-content-list",        ID_CONTENT_PREVIEW: "massedit-content-preview",        ID_CONTENT_FORM: "massedit-content-form",        ID_CONTENT_FIELDSET: "massedit-content-fieldset",        ID_CONTENT_CONTENT: "massedit-content-content", ID_CONTENT_TARGET: "massedit-content-target", ID_CONTENT_INDICES: "massedit-content-indices", ID_CONTENT_PAGES: "massedit-content-pages", ID_CONTENT_SUMMARY: "massedit-content-summary", ID_CONTENT_SCENE: "massedit-content-scene", ID_CONTENT_ACTION: "massedit-content-action", ID_CONTENT_TYPE: "massedit-content-type", ID_CONTENT_CASE: "massedit-content-case", ID_CONTENT_MATCH: "massedit-content-match", ID_CONTENT_LOG: "massedit-content-log", ID_CONTENT_BYLINE: "massedit-content-byline", ID_CONTENT_BODY: "massedit-content-body", ID_CONTENT_MEMBERS: "massedit-content-members", ID_PREVIEW_CONTAINER: "massedit-preview-container", ID_PREVIEW_TITLE: "massedit-preview-title", ID_PREVIEW_BODY: "massedit-preview-body", ID_PREVIEW_CLOSE: "massedit-preview-close", ID_PREVIEW_BUTTON: "massedit-preview-button", CLASS_PLACEMENT_OVERFLOW: "overflow", CLASS_PREVIEW_BUTTON: "massedit-preview-button", CLASS_OOUI_FRAME: "oo-ui-window-frame", CLASS_OOUI_HEAD: "oo-ui-window-head", CLASS_OOUI_BODY: "oo-ui-window-body", CLASS_OOUI_FOOT: "oo-ui-window-foot", CLASS_OOUI_LABEL: "oo-ui-labelElement-label", CLASS_MODAL_CONTAINER: "massedit-modal-container", CLASS_MODAL_BUTTON: "massedit-modal-button", CLASS_MODAL_LEFT: "massedit-modal-left", CLASS_MODAL_OPTION: "massedit-modal-option", CLASS_MODAL_TIMER: "massedit-modal-timer", CLASS_CONTENT_CONTAINER: "massedit-content-container", CLASS_CONTENT_FORM: "massedit-content-form", CLASS_CONTENT_FIELDSET: "massedit-content-fieldset", CLASS_CONTENT_TEXTAREA: "massedit-content-textarea", CLASS_CONTENT_INPUT: "massedit-content-input", CLASS_CONTENT_DIV: "massedit-content-div", CLASS_CONTENT_SPAN: "massedit-content-span", CLASS_CONTENT_SELECT: "massedit-content-select", }),   },    UserGroups: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze({ CAN_EDIT: Object.freeze([         "autoconfirmed",          "emailconfirmed",          "sysop",          "content-moderator",          "bot",          "bot-global",          "content-volunteer",        ]), CAN_MESSAGE: Object.freeze([         "global-discussions-moderator",          "threadmoderator",        ]), }),   },    Scenes: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze({ REPLACE: Object.freeze({         NAME: "replace",          POSITION: 0,          SCHEMA: Object.freeze([ Object.freeze({             HANDLER: "assembleDropdown",              PARAMETER_ARRAYS: Object.freeze([ Object.freeze(["type",                 Object.freeze(["pages", "categories", "namespaces"])                ]), Object.freeze(["case",                 Object.freeze(["sensitive", "insensitive"])                ]), Object.freeze(["match",                 Object.freeze(["plain", "regex"])                ]), ])           }),            Object.freeze({              HANDLER: "assembleTextfield",              PARAMETER_ARRAYS: Object.freeze([ Object.freeze(["target", "textarea"]), Object.freeze(["indices", "input"]), Object.freeze(["content", "textarea"]), Object.freeze(["pages", "textarea"]), Object.freeze(["summary", "input"]), ])           })          ]),        }),        ADD: Object.freeze({          NAME: "add",          POSITION: 1,          SCHEMA: Object.freeze([ Object.freeze({             HANDLER: "assembleDropdown",              PARAMETER_ARRAYS: Object.freeze([ Object.freeze(["action",                 Object.freeze(["prepend", "append"])                ]), Object.freeze(["type",                 Object.freeze(["pages", "categories", "namespaces"])                ]) ])           }),            Object.freeze({              HANDLER: "assembleTextfield",              PARAMETER_ARRAYS: Object.freeze([ Object.freeze(["content", "textarea"]), Object.freeze(["pages", "textarea"]), Object.freeze(["summary", "input"]), ])           })          ]),        }),        MESSAGE: Object.freeze({          NAME: "message",          POSITION: 2,          SCHEMA: Object.freeze([ Object.freeze({             HANDLER: "assembleTextfield",              PARAMETER_ARRAYS: Object.freeze([ Object.freeze(["pages", "textarea"]), Object.freeze(["byline", "input"]), Object.freeze(["body", "textarea"]), ])           })          ]),        }),        LIST: Object.freeze({          NAME: "list",          POSITION: 3,          SCHEMA: Object.freeze([ Object.freeze({             HANDLER: "assembleDropdown",              PARAMETER_ARRAYS: Object.freeze([ Object.freeze(["type",                 Object.freeze(["categories", "namespaces", "templates"])                ]) ])           }),            Object.freeze({              HANDLER: "assembleTextfield",              PARAMETER_ARRAYS: Object.freeze([ Object.freeze(["pages", "textarea"]), Object.freeze(["members", "textarea"]), ])           })          ]),        }),      }),    },    Buttons: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze({ SUBMIT: Object.freeze({         HANDLER: "handleSubmit",          TEXT: "buttonSubmit",          EVENT: "submit",          PRIMARY: true,          DISABLED: false,          ID: "ID_MODAL_SUBMIT",          CLASSES: Object.freeze([ "CLASS_MODAL_BUTTON", "CLASS_MODAL_OPTION", ])       }),        TOGGLE: Object.freeze({          HANDLER: "handleToggle",          TEXT: "buttonPause",          EVENT: "toggle",          PRIMARY: true,          DISABLED: true,          ID: "ID_MODAL_TOGGLE",          CLASSES: Object.freeze([ "CLASS_MODAL_BUTTON", "CLASS_MODAL_TIMER", ])       }),        CANCEL: Object.freeze({          HANDLER: "handleCancel",          TEXT: "buttonCancel",          EVENT: "cancel",          PRIMARY: true,          DISABLED: true,          ID: "ID_MODAL_CANCEL",          CLASSES: Object.freeze([ "CLASS_MODAL_BUTTON", "CLASS_MODAL_TIMER", ])       }),        PREVIEW: Object.freeze({          HANDLER: "handlePreviewing",          TEXT: "buttonPreview",          EVENT: "preview",          PRIMARY: true,          DISABLED: true,          ID: "ID_MODAL_PREVIEW",          CLASSES: Object.freeze([ "CLASS_MODAL_BUTTON", ])       }),        CLOSE: Object.freeze({          TEXT: "buttonClose",          EVENT: "close",          PRIMARY: false,          DISABLED: false,          ID: "ID_MODAL_CLOSE",          CLASSES: Object.freeze([ "CLASS_MODAL_BUTTON", "CLASS_MODAL_LEFT", "CLASS_MODAL_OPTION" ])       }),        CLEAR: Object.freeze({          HANDLER: "handleClear",          TEXT: "buttonClear",          EVENT: "clear",          PRIMARY: false,          DISABLED: false,          ID: "ID_MODAL_CLEAR",          CLASSES: Object.freeze([ "CLASS_MODAL_BUTTON", "CLASS_MODAL_LEFT", "CLASS_MODAL_OPTION" ])       }),      }),    },    Flags: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze({ DEBUG: false, TESTING: false, }),   },    Utility: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze({ LS_KEY: "MassEdit-cache-scenes", LS_PREFIX: "MassEdit-cache-scenes-", FIRST_SCENE: "REPLACE", DAYS_ACTIVE: 90, MAX_SUMMARY_CHARS: 800, FADE_INTERVAL: 1000, DELAY: 35000, BOTTOM_PADDING: 15, }),   },  });  Object.defineProperties(init, {    Dependencies: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze({ ARTICLES: Object.freeze([         Object.freeze({ DEV: "colors", HOOK: "dev.colors", ARTICLE: "u:dev:MediaWiki:Colors/code.js", TYPE: "script", }),         Object.freeze({ DEV: "i18n", HOOK: "dev.i18n", ARTICLE: "u:dev:MediaWiki:I18n-js/code.js", TYPE: "script", }),         Object.freeze({ DEV: "modal", HOOK: "dev.modal", ARTICLE: "u:dev:MediaWiki:Modal.js", TYPE: "script", }),         Object.freeze({ DEV: "placement", HOOK: "dev.placement", ARTICLE: "u:dev:MediaWiki:Placement.js", TYPE: "script", }),         Object.freeze({ WINDOW: "wgMessageWallsExist", HOOK: "dev.enablewallext", ARTICLE: "u:dev:MediaWiki:WgMessageWallsExist.js", TYPE: "script", }),       ]),        MODULES: Object.freeze([          "mediawiki.user",          "mediawiki.util",        ]), }),   },    Placement: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze({ DEFAULTS: Object.freeze({         ELEMENT: "tools",          TYPE: "prepend",        }), VALID_TYPES: Object.freeze([         "append",          "prepend",        ]), }),   },    Globals: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze([ "wgFormattedNamespaces", "wgLegalTitleChars", "wgScriptPath", "wgServer", "wgUserGroups", "wgUserLanguage", "wgVersion", ]),   },    Utility: {      enumerable: true,      writable: false,      configurable: false,      value: Object.freeze({ SCRIPT: "MassEdit", HOOK_NAME: "dev.massEdit", STD_INTERVAL: 1500, BOT_INTERVAL: 750, CACHE_VERSION: 4, }),   }  });  main.capitalize = function (paramTarget) { return paramTarget.charAt(0).toUpperCase + paramTarget.slice(1); }; main.isThisAn = function (paramType, paramTarget) { return Object.prototype.toString.call(paramTarget) === "[object " + this.capitalize.call(this, paramType.toLowerCase) + "]"; }; main.isLegalInput = function (paramString) { return new RegExp("^[" + this.globals.wgLegalTitleChars +     "]*$").test(paramString); }; main.isInteger = function (paramEntry) { return new RegExp(/^[0-9]+$/).test(paramEntry.toString); }; main.startsWith = function (paramTarget, paramSearch) { return paramTarget.substring(0, 0 + paramSearch.length) === paramSearch; }; main.hasRights = function (paramMessaging) { return new RegExp(["(" + this.UserGroups.CAN_EDIT.join("|") + ((paramMessaging) ? "|" + this.UserGroups.CAN_MESSAGE.join("|") : "") + ")"].join("")).test(this.globals.wgUserGroups.join(" ")) || this.flags.testing; }; main.expandLinkAddress = function (paramParsedHTML) { return paramParsedHTML.replace(     /href="\/wiki/g,      "href=\"" + this.globals.wgServer + this.globals.wgScriptPath + "/wiki"    ); }; main.toggleFlag = function (paramFlagName) { if (     typeof paramFlagName !== "string" ||      $.inArray(paramFlagName.toUpperCase, Object.keys(this.Flags)) === -1    ) { return; }   (this.flags = this.flags || {})[paramFlagName] = this.flags[paramFlagName] || this.Flags[paramFlagName]; window.console.log(paramFlagName + ":",     this.flags[paramFlagName] = Boolean(this.flags[paramFlagName] ^ 1)); }; main.replaceDuplicates = function (paramArray) { var i, n, tempObject; for (i = 0, n = paramArray.length, tempObject = {}; i < n; i++) { tempObject[paramArray[i]] = true; }   return Object.keys(tempObject); }; main.buildJsonModel = function (paramHTML) { return JSON.stringify(this.assembleJsonModelObject( $.parseHTML(this.expandLinkAddress(paramHTML))[0], { "type": "doc", "content": [] }, [], []   ));  };  main.assembleJsonModelObject = function (paramElement, paramJsonModel,      paramStackP, paramStackA) { if (paramElement.nodeType === 3) { if (paramStackA.length) { paramStackA[paramStackA.length - 1].text = paramElement.nodeValue; } else if (paramStackP.length) { paramStackP[paramStackP.length - 1].content.push({         "type": "text",          "text": paramElement.nodeValue        }); }   } else if (paramElement.nodeType === 1) { var tag, child, attr, attrs, newLink; tag = paramElement.nodeName.toLowerCase; if (tag === "p") { paramStackP.push({         "type": "paragraph",          "content": []        }); } else if (tag === "a") { newLink = { "type": "text", "marks": [ {             "type": "link", "attrs": {} }         ]        };        attrs = Array.prototype.slice.call(paramElement.attributes).reduce(          function (attributes, attribute) {            attributes[attribute.name] = attribute.value;            return attributes;          }, Object.create(null)        ); for (attr in attrs) { if (attr === "href" || attr === "title") { newLink.marks[0].attrs[attr] = attrs[attr]; }       }        paramStackA.push(newLink); paramStackP[paramStackP.length - 1].content.push(newLink); }     if (paramElement.hasChildNodes) { child = paramElement.firstChild; while (child) { paramJsonModel = this.assembleJsonModelObject(child, paramJsonModel,           paramStackP, paramStackA); child = child.nextSibling; }     }      if (tag === "p") { paramJsonModel.content.push(paramStackP.pop); } else if (tag === "a") { paramStackA.pop; }   }    return paramJsonModel; }; main.replaceOccurrences = function (paramIsCaseSensitive, paramIsUserRegex,      paramTarget, paramReplacement, paramInstances) { var regex, replacement, counter; paramInstances = (paramInstances != null) ? paramInstances : []; regex = new RegExp((paramIsUserRegex)     ? paramTarget       : paramTarget        .replace(/\r/gi, "")        .replace(/([.*+?^=!:${}|\[\]\/\\])/g, "\\$1"),      ((paramIsCaseSensitive) ? "g" : "gi") + "m"   ); replacement = (!paramInstances.length) ? paramReplacement : function (paramMatch) { return ($.inArray(++counter, paramInstances) !== -1) ? paramReplacement : paramMatch; };   return function (paramString) { if (this.flags.debug) { window.console.log(regex, replacement); }     counter = 0; return paramString.replace(regex, replacement); }.bind(this); }; main.queryStorage = function (paramSceneName, paramSceneData) { var isSetting, lsKey, scenes; isSetting = (Array.prototype.slice.call(arguments).length == 2 &&     paramSceneData != null); lsKey = this.Utility.LS_PREFIX + this.globals.wgUserLanguage; try { scenes = this.modal.scenes = JSON.parse(mw.storage.get(lsKey)) || {}; } catch (paramError) { if (this.flags.debug) { window.console.error(paramError); }     scenes = this.modal.scenes = this.modal.scenes || {}; }   if (!isSetting) { return (scenes.hasOwnProperty(paramSceneName)) ? scenes[paramSceneName] : null; }   if (!scenes.hasOwnProperty(paramSceneName)) { scenes[paramSceneName] = paramSceneData; try { mw.storage.set(lsKey, JSON.stringify(scenes)); } catch (paramError) {} if (this.flags.debug) { try { window.console.log("modal.scenes: ", this.modal.scenes); window.console.log("localStorage: ",           JSON.parse(window.localStorage.getItem(lsKey))); } catch (paramError) {} }   }    return scenes[paramSceneName]; }; main.setDynamicTimeout = function self (paramCallback, paramInterval) { self.callback = paramCallback; self.interval = paramInterval; self.isPaused = false; self.isComplete = false; self.identify = -1; self.iterate; return self; }; main.setDynamicTimeout.cancel = function  { this.isComplete = true; window.clearTimeout(this.identify); }; main.setDynamicTimeout.pause = function  { if (this.isPaused || this.isComplete) { return; }   this.isPaused = true; window.clearTimeout(this.identify); }; main.setDynamicTimeout.resume = function  { if (!this.isPaused || this.isComplete) { return; }   this.isPaused = false; this.iterate; }; main.setDynamicTimeout.iterate = function (paramInterval) { if (this.isPaused || this.isComplete) { return; }   paramInterval = (paramInterval < this.interval || paramInterval == null) ? this.interval : paramInterval; this.identify = window.setTimeout(this.callback, paramInterval); }; main.sort = function self (paramArray, paramLeft, paramRight) { var args, index; args = Array.prototype.slice.call(arguments); if (args.length === 1 && this.isThisAn("Array", args[0])) { paramArray = args[0]; paramLeft = 0; paramRight = paramArray.length - 1; }   if (paramArray.length) { index = self.partition(paramArray, paramLeft, paramRight); if (paramLeft < index - 1) { self(paramArray, paramLeft, index - 1); }     if (index < paramRight) { self(paramArray, index, paramRight); }   }    return paramArray; }; main.sort.swap = function (paramArray, paramLeft, paramRight) { var swapped; swapped = paramArray[paramLeft]; paramArray[paramLeft] = paramArray[paramRight]; paramArray[paramRight] = swapped; }; main.sort.partition = function (paramArray, paramLeft, paramRight) { var pivot, leftPointer, rightPointer; pivot = paramArray[Math.floor((paramLeft + paramRight) / 2)]; leftPointer = paramLeft; rightPointer = paramRight; while (leftPointer <= rightPointer) { while (paramArray[leftPointer] < pivot) { leftPointer++; }     while (paramArray[rightPointer] > pivot) { rightPointer--; }     if (leftPointer <= rightPointer) { this.swap(paramArray, leftPointer++, rightPointer--); }   }    return leftPointer; }; main.getUserData = function (paramUsername) { return $.ajax({     type: "GET",      url: mw.util.wikiScript("api"),      data: {        action: "query",        list: "users|usercontribs|logevents",        usprop: "editcount",        ucprop: "timestamp",        uclimit: "1",        lelimit: "1",        ususers: paramUsername,        ucuser: paramUsername,        leuser: paramUsername,        format: "json"      }    }); }; main.postMessageWallThread = function (paramConfig) { return $.ajax({     method: "POST",      url: mw.util.wikiScript("wikia") + "?" + $.param({ controller: "Fandom\\MessageWall\\MessageWall", method: "createThread", format: "json", }),     data: $.extend(false, { token: mw.user.tokens.get("csrfToken"), attachments: "{\"contentImages\":[],\"openGraphs\":[],\"atMentions\":[]}" }, paramConfig),   }); }; main.postTalkPageTopic = function (paramConfig) { return $.ajax({     type: "POST",      url: mw.util.wikiScript("api"),      data: $.extend(false, { token: mw.user.tokens.get("csrfToken"), action: "edit", section: "new", format: "json", }, paramConfig),   }); }; main.getParsedWikitextContent = function (paramText) { return $.ajax({     type: "GET",      url: mw.util.wikiScript("api"),      data: {        action: "parse",        title: "API",        text: paramText,        contentmodel: "wikitext",        preview: true,        format: "json"      }    }); }; main.getNamespaceMembers = function (paramConfig) { return $.ajax({     type: "GET",      url: mw.util.wikiScript("api"),      data: $.extend(false, { action: "query", list: "allpages", apnamespace: "*", aplimit: (this.flags.debug) ? 5 : "max", rawcontinue: true, format: "json", }, paramConfig)   }); }; main.getCategoryMembers = function (paramConfig) { return $.ajax({     type: "GET",      url: mw.util.wikiScript("api"),      data: $.extend(false, { action: "query", list: "categorymembers", cmnamespace: "*", cmprop: "title", cmdir: "desc", cmlimit: (this.flags.debug) ? 5 : "max", rawcontinue: true, format: "json", }, paramConfig)   }); }; main.getTemplateTransclusions = function (paramConfig) { return $.ajax({     type: "GET",      url: mw.util.wikiScript("api"),      data: $.extend(false, { token: mw.user.tokens.get("csrfToken"), action: "query", list: "embeddedin", einamespace: "*", eilimit: (this.flags.debug) ? 5 : "max", rawcontinue: true, format: "json", }, paramConfig)   }); }; main.getPageContent = function (paramPage) { return $.ajax({     type: "GET",      url: mw.util.wikiScript("api"),      data: {        action: "query",        prop: "info|revisions",        titles: paramPage,        inprop: "protection",        rvprop: "content|timestamp",        rvlimit: "1",        indexpageids: "true",        format: "json"      }    }); }; main.postPageContent = function (paramConfig) { return $.ajax({     type: "POST",      url: mw.util.wikiScript("api"),      data: $.extend(false, { token: mw.user.tokens.get("csrfToken"), action: "edit", minor: true, bot: true, format: "json", }, paramConfig)   }); }; main.getValidatedEntries = function (paramEntries, paramType) { var i, n, entry, results, $deferred, prefix; results = []; $deferred = new $.Deferred; prefix = this.globals.wgFormattedNamespaces[{ categories: 14, namespaces: 0, templates: 10, }[paramType]] || ""; for (i = 0, n = paramEntries.length; i < n; i++) { entry = this.capitalize(paramEntries[i].trim); if (       paramType === "recipients" &&        this.startsWith(entry, this.globals.wgFormattedNamespaces[2])      ) { entry = entry.split(this.globals.wgFormattedNamespaces[2] + ":")[1]; }     if (!this.startsWith(entry, prefix)) { entry = prefix + ":" + entry; }     if (        (paramType !== "namespaces" && this.isLegalInput(entry)) ||        (paramType === "namespaces" && this.isInteger(entry))      ) { results.push(entry); } else { return $deferred.reject("logErrorSecurity"); }   }    if (!results.length) { $deferred.reject("logErrorNoWellformedPages"); } else { $deferred.resolve(results); }   return $deferred.promise; }; main.getActiveUsersData = function (paramEntries) { var counter, entries, names, $getData, $getUsers, $addUsers, $returnUsers, wallPrefix, user, usercontribs, logevents, lastEditDate, nDaysAgo; $addUsers = new $.Deferred; $returnUsers = new $.Deferred; counter = 0; wallPrefix = this.globals.wgFormattedNamespaces[ (this.flags.hasMessageWalls) ? 1200       : 3    ] + ":";    entries = []; $getUsers = this.getValidatedEntries(paramEntries, "recipients"); $getUsers.then(function (paramNames) {     if (this.flags.debug) {        window.console.log(paramEntries, paramNames);      }      names = paramNames;      $returnUsers.notify("logStatusCheckingUsernames");      this.timer = this.setDynamicTimeout(function  { if (counter === names.length) { return $addUsers.resolve(entries); }       $getData = $.when(this.getUserData(names[counter++])); $getData.always($addUsers.notify); }.bind(this), this.config.interval);   }.bind(this), $returnUsers.reject.bind(null)); $addUsers.progress(function (paramResult, paramStatus, paramXHR) {     if (this.flags.debug) {        window.console.log(paramResult, paramStatus, paramXHR);      }      if ( paramStatus !== "success" || !(paramXHR.status >= 200 && paramXHR.status < 300) ) {       $returnUsers.notify("logErrorNoUserData", names[counter - 1]);        return this.timer.iterate;      }      user = paramResult.query.users[0];      usercontribs = paramResult.query.usercontribs;      logevents = paramResult.query.logevents;      if (!user.hasOwnProperty("userid") || user.hasOwnProperty("missing")) {        $returnUsers.notify("logErrorNoUserData", names[counter - 1]);        return this.timer.iterate;      }      if ( user.editcount === 0 || (!usercontribs.length && !logevents.length) ) {       this.addModalLogEntry("logErrorNotAnEditor", names[counter - 1]);        return this.timer.iterate;      }      lastEditDate = new Date(usercontribs[0].timestamp);      nDaysAgo = new Date;      nDaysAgo.setDate(nDaysAgo.getDate - this.Utility.DAYS_ACTIVE);      if (this.flags.debug) {        window.console.log("nDaysAgo:", nDaysAgo.toLocaleString);        window.console.log("lastEditDate:", lastEditDate.toLocaleString);      }      if (nDaysAgo > lastEditDate) {        this.addModalLogEntry("logErrorInactiveEditor", names[counter - 1]);        return this.timer.iterate;      }      $returnUsers.notify("logSuccessUserExists", user.name);      entries.push({ name: wallPrefix + user.name, userid: user.userid });     return this.timer.iterate;    }.bind(this)); $addUsers.done(function {      if (entries.length) {        return $returnUsers.resolve(this.sort(entries)).promise;      } else {        return $returnUsers.reject("logErrorNoWellformedUsernames").promise;      }    }.bind(this)); return $returnUsers.promise; }; main.getMemberPages = function (paramEntries, paramType) { var i, n, names, data, entries, parameters, counter, config, $getPages, $addPages, $getEntries, $returnPages; $returnPages = new $.Deferred; $addPages = new $.Deferred; counter = 0; parameters = {}; names = [];    // Store names of user entries entries = [];  // New entries to be returned config = { categories: { query: "categorymembers", handler: "getCategoryMembers", continuer: "cmcontinue", target: "cmtitle", },     namespaces: { query: "allpages", handler: "getNamespaceMembers", continuer: "apcontinue", target: "apnamespace", },     templates: { query: "embeddedin", handler: "getTemplateTransclusions", continuer: "eicontinue", target: "eititle", },   }[paramType]; $getEntries = this.getValidatedEntries(paramEntries, paramType); $getEntries.then(function (paramResults) {     names = paramResults;    }, $returnPages.reject.bind($)); this.timer = this.setDynamicTimeout(function {      if (counter === names.length) {        $addPages.resolve;        if (entries.length) {          entries = this.sort(this.replaceDuplicates(entries));          return $returnPages.resolve(entries).promise;        } else {          return $returnPages.reject("logErrorNoWellformedPages").promise;        }      }      parameters[config.target] = names[counter];      $returnPages.notify((paramType === "templates") ? "logStatusFetchingTransclusions" : "logStatusFetchingMembers", names[counter]);     $getPages = $.when(this[config.handler](parameters));      $getPages.always($addPages.notify);    }.bind(this), this.config.interval); $addPages.progress(function (paramResults, paramStatus, paramXHR) {     if (this.flags.debug) {        window.console.log(paramResults, paramStatus, paramXHR);      }      if ( paramStatus !== "success" || !(paramXHR.status >= 200 && paramXHR.status < 300) ) {       $returnPages.notify("logErrorFailedFetch", names[counter++]);        return this.timer.iterate;      }      data = paramResults.query[config.query];      if (data == null || data.length === 0) {        $returnPages.notify("logErrorNoSuchPage", names[counter++]);        return this.timer.iterate;      }      for (i = 0, n = data.length; i < n; i++) {        entries.push(data[i].title);      }      if ( paramResults["query-continue"] || paramResults.hasOwnProperty("query-continue") ) {       parameters[config.continuer] =          paramResults["query-continue"][config.query][config.continuer];      } else {        parameters = {};        counter++;      }      return this.timer.iterate;    }.bind(this)); return $returnPages.promise; }; main.assembleElement = function (paramArray) { var type, attributes, counter, content; if (!this.isThisAn("Array", paramArray)) { return this.assembleElement.call(this,       Array.prototype.slice.call(arguments)); }   counter = 0; content = ""; type = paramArray[counter++]; attributes = (this.isThisAn("Object", paramArray[counter])) ? paramArray[counter++] : {};   while (counter < paramArray.length) { content += (this.isThisAn("Array", paramArray[counter])) ? this.assembleElement(paramArray[counter++]) : paramArray[counter++]; }   return mw.html.element(type, attributes, new mw.html.Raw(content)); }; main.assembleOverflowElement = function (paramText) { return this.assembleElement(     ["li", {        "class": this.Selectors.CLASS_PLACEMENT_OVERFLOW,        "id": this.Selectors.ID_PLACEMENT_LIST,       },        ["a", {          "id": this.Selectors.ID_PLACEMENT_LINK,          "href": "#",          "title": paramText,        },          paramText,        ],      ]    ); }; main.assembleTextfield = function (paramName, paramType) { var elementId, elementClass, prefix, placeholder, title, attributes; paramName = paramName.toLowerCase; paramType = paramType.toLowerCase; elementId = "ID_CONTENT_" + paramName.toUpperCase; elementClass = "CLASS_CONTENT_" + paramType.toUpperCase; prefix = "modal" + this.capitalize(paramName); placeholder = prefix + "Placeholder"; title = prefix + "Title"; attributes = { id: this.Selectors[elementId], class: this.Selectors[elementClass], placeholder: this.i18n.msg(placeholder).plain, };   if (paramType === "input") { attributes.type = "textbox"; }   return this.assembleElement(      ["div", {class: this.Selectors.CLASS_CONTENT_DIV},        ["span", {class: this.Selectors.CLASS_CONTENT_SPAN},          this.i18n.msg(title).escape,        ],        [paramType, attributes],      ]    ); }; main.assembleDropdown = function (paramName, paramValues, paramIndex) { var i, n, titleMessage, optionMessage, prefix, options, value, attributes, selectedIndex; paramName = paramName.toLowerCase; selectedIndex = window.parseInt(paramIndex, 10) || 0; options = ""; prefix = "modal" + this.capitalize(paramName); titleMessage = this.i18n.msg(prefix).escape; for (i = 0, n = paramValues.length; i < n; i++) { value = paramValues[i].toLowerCase; optionMessage = prefix + this.capitalize(value); attributes = { value: value, };     if (i === selectedIndex) { attributes.selected = "selected"; }     options += this.assembleElement(        ["option", attributes,          this.i18n.msg(optionMessage).escape,        ]      ); }   return this.assembleElement(      ["div", {class: this.Selectors.CLASS_CONTENT_DIV},        ["span", {class: this.Selectors.CLASS_CONTENT_SPAN},          titleMessage,        ],        ["select", {          size: "1",          name: paramName,          id: this.Selectors["ID_CONTENT_" + paramName.toUpperCase],          class: this.Selectors.CLASS_CONTENT_SELECT,        },          options,        ],      ]    ); }; main.injectModalStyles = function  { var selectors, colors, stringCSS, customColors; selectors = this.Selectors; colors = window.dev.colors; customColors = { logColor: "#757575", // Common ::placeholder text color in shadow DOM textfieldBackground: "#FFFFFF", textfieldColor: "#000000", modalBorder: "var(--theme-border-color)"  // UCP has dedicated 2nd border };   stringCSS = "." + selectors.CLASS_CONTENT_CONTAINER + " {" + "margin: auto !important;" + "position: relative !important;" + "width: 96% !important;" + "}" +     "." + selectors.CLASS_OOUI_BODY + " " + "." + selectors.CLASS_CONTENT_CONTAINER + " {" + "padding-bottom: " + this.Utility.BOTTOM_PADDING + "px !important;" + "}" +     "#" + selectors.ID_CONTENT_LOG + "," + "." + selectors.CLASS_CONTENT_SELECT + "," + "." + selectors.CLASS_CONTENT_TEXTAREA + "," + "." + selectors.CLASS_CONTENT_INPUT + " {" + "width: 99.6% !important;" + "padding: 0 !important;" + "resize: none !important;" + "background-color: $textfieldBackground !important;" + "color: $textfieldColor !important;" + "border: 1px solid !important;" + "border-color: $modalBorder !important;" + "}" +     "#" + selectors.ID_CONTENT_LOG + "," + "." + selectors.CLASS_CONTENT_TEXTAREA + " {" + "font-family: monospace !important;" + "height: 45px !important;" + "}" +     "#" + selectors.ID_CONTENT_MESSAGE + " " + "." + selectors.CLASS_CONTENT_TEXTAREA + "," + "#" + selectors.ID_CONTENT_LIST + " " + "." + selectors.CLASS_CONTENT_TEXTAREA + " {" + "height: 85px !important;" + "}" +     "#" + selectors.ID_CONTENT_ADD + " " + "." + selectors.CLASS_CONTENT_TEXTAREA + " {" + "height: 65px !important;" + "}" +     "#" + selectors.ID_CONTENT_LOG + " {" + "color: $logColor !important;" + "overflow: auto !important;" + "}" +     "." + selectors.CLASS_MODAL_BUTTON + " {" + "float: right !important;" + "margin-left: 5px !important;" + "font-size: 8pt !important;" + "}" +     "span." + selectors.CLASS_MODAL_BUTTON + "[disabled] {" + "display: none;" + "}" +     "." + selectors.CLASS_MODAL_LEFT + " {" + "float: left !important;" + "margin-left: 0px !important;" + "margin-right: 5px !important;" + "}" +     "." + selectors.CLASS_OOUI_BODY + " " + "#" + selectors.ID_PREVIEW_CONTAINER + " {" + "margin: 20px !important;" + "}" +     "#" + selectors.ID_PREVIEW_CONTAINER + " {" + "border: 1px solid $modalBorder;" + "padding: 10px !important;" + "overflow: auto !important;" + "min-height: 250px !important;" + "}" +     "#" + selectors.ID_PREVIEW_BODY + " .pagetitle {" + "display: none !important;" + "}" +     "#" + selectors.ID_PREVIEW_TITLE + " h2 {" + "display: inline-block !important;" + "}" +     "#" + selectors.ID_PREVIEW_CLOSE + " {" + "display: inline-block !important;" + "float: right !important;" + "}" +     "." + selectors.CLASS_PREVIEW_BUTTON + " {" + "border: none !important;" + "background: none !important;" + "color: $link !important;" + "cursor: pointer !important;" + "}" +     "." + selectors.CLASS_PREVIEW_BUTTON + ":hover," + "." + selectors.CLASS_PREVIEW_BUTTON + ":focus," + "." + selectors.CLASS_PREVIEW_BUTTON + ":active {" + "outline: none !important;" + "background: none !important;" + "text-decoration: underline !important;" + "}";   return colors.css(stringCSS, customColors); }; main.addModalLogEntry = function  { $("#" + this.Selectors.ID_CONTENT_LOG).prepend(     this.i18n.msg.apply(this, (arguments.length === 1 && arguments[0] instanceof Array) ? arguments[0] : Array.prototype.slice.call(arguments) ).escape + " "); }; main.resetModal = function  { if (this.timer && !this.timer.isComplete) { this.timer.cancel; }   if (arguments.length) { this.addModalLogEntry(Array.prototype.slice.call(arguments)); }   $("#" + this.Selectors.ID_CONTENT_FORM)[0].reset; this.toggleModalComponentsDisable("partial", false); }; main.toggleModalComponentsDisable = function (paramOption, paramDisable) { if ($.inArray(paramOption, ["all", "partial"]) === -1) { return; }   paramDisable = (paramOption === "all" || typeof paramDisable !== "boolean") || paramDisable; if (this.flags.debug) { window.console.log(paramOption, paramDisable); }   var i, n, $scene, isMessaging, buttons, button, $fieldset, isAll, defaultDisable; $scene = $("#" + this.Selectors.ID_CONTENT_SCENE)[0]; $fieldset = $("#" + this.Selectors.ID_CONTENT_FIELDSET); isMessaging = ($scene.value === "message" && $scene.selectedIndex === 2); isAll = paramOption === "all"; buttons = this.modal.modal.buttons; for (i = 0, n = buttons.length; i < n; i++) { button = buttons[i]; defaultDisable = this.Buttons[button.event.toUpperCase].DISABLED; button.setDisabled(isAll || (button.event === "preview")       ? (!isMessaging || paramDisable)        : Boolean(paramDisable ^ defaultDisable)); // Toggle mechanism $("#" + button.id).attr("disabled", button.disabled); }   $fieldset.attr("disabled", isAll || paramDisable); }; main.attachPreviewEvents = function  { var container, $button, $messaging; container = "#" + this.Selectors.ID_PREVIEW_CONTAINER; $button = $("#" + this.Selectors.ID_PREVIEW_BUTTON); $messaging = $("#" + this.Selectors.ID_CONTENT_MESSAGE); mw.hook("wikipage.content").fire(     $(container + " #" + mw.util.$content[0].id)); $button.on("click", this.handleClear.bind(this, { before: function { $(container).remove; $messaging.show; }.bind(this), after: this.toggleModalComponentsDisable.bind(this, "partial", false) })); };  main.buildPreviewContent = function  { return this.assembleElement(     ["div", {id: this.Selectors.ID_PREVIEW_CONTAINER},        ["div", {id: this.Selectors.ID_PREVIEW_TITLE},          ["h2", {},            "$1",          ],          ["div", {id: this.Selectors.ID_PREVIEW_CLOSE},            ["button", {              class: this.Selectors.CLASS_PREVIEW_BUTTON,              id: this.Selectors.ID_PREVIEW_BUTTON            },              "(" + this.i18n.msg("buttonClose").escape + ")",            ]          ]        ],        ["hr"],        ["div", {id: this.Selectors.ID_PREVIEW_BODY},         "$2",        ],      ]    ); }; main.displayPreview = function (paramBody) { var $scene, previewScene, contents, $byline, $messaging, $modal, isMessaging, modalBodyTarget; $scene = $("#" + this.Selectors.ID_CONTENT_SCENE)[0]; isMessaging = ($scene.value === "message" && $scene.selectedIndex === 2); $byline = $("#" + this.Selectors.ID_CONTENT_BYLINE).val; $messaging = $("#" + this.Selectors.ID_CONTENT_MESSAGE); modalBodyTarget = " ." + this.Selectors.CLASS_OOUI_BODY; $modal = $("#" + this.Selectors.ID_MODAL_CONTAINER + modalBodyTarget); if (!isMessaging || !this.modal.modal) { return; }   previewScene = this.queryStorage("preview"); contents = ((previewScene != null)     ? previewScene      : this.queryStorage("preview", this.buildPreviewContent)    ).replace("$1", $byline).replace("$2", paramBody); $messaging.hide; $modal.append(contents); }; main.attachModalEvents = function  { var i, n, element, elements, height; height = 0; elements = [ "CLASS_OOUI_HEAD",         // UCP modal header "CLASS_OOUI_FOOT",         // UCP modal footer "CLASS_CONTENT_CONTAINER", // Inner modal body content ];   for (i = 0, n = elements.length; i < n; i++) { element = "." + this.Selectors[elements[i]]; height += $(element).height; }   $("." + this.Selectors.CLASS_OOUI_FRAME).height(height +      (this.Utility.BOTTOM_PADDING * 2)); if (!this.modal.isReady) { $(document).on("change", "#" + this.Selectors.ID_CONTENT_SCENE,       this.handleClear.bind(this, true)); }   this.toggleModalComponentsDisable("partial", false); }; main.buildModalContent = function  { return this.assembleElement(     ["section", {        id: "$1",        class: this.Selectors.CLASS_CONTENT_CONTAINER,      },        ["form", {          id: this.Selectors.ID_CONTENT_FORM,          class: this.Selectors.CLASS_CONTENT_FORM,        },          ["fieldset", {id: this.Selectors.ID_CONTENT_FIELDSET},            "$2",            "$3",          ],          ["hr"],        ],        ["div", {class: this.Selectors.CLASS_CONTENT_DIV},          ["span", {class: this.Selectors.CLASS_CONTENT_SPAN},            this.i18n.msg("modalLog").escape,          ],          ["div", {            id: this.Selectors.ID_CONTENT_LOG,            class: this.Selectors.CLASS_CONTENT_DIV,          }],        ],      ]    ); }; main.buildModalScene = function (paramScene) { var i, j, m, n, tempScene, sceneNames, assembledScene, framework, enumScene, dropdownArgs, elements, enumSchema, enumArrays, selector, storedResults; storedResults = this.queryStorage(paramScene); if (storedResults != null && storedResults.length) { return storedResults; }   framework = this.buildModalContent; enumScene = this.Scenes[paramScene.toUpperCase]; sceneNames = []; for (tempScene in this.Scenes) { if (this.Scenes.hasOwnProperty(tempScene)) { sceneNames.push(this.Scenes[tempScene].NAME); }   }    dropdownArgs = ["scene", sceneNames, enumScene.POSITION]; if (this.flags.debug) { window.console.log(dropdownArgs); }   elements = ""; selector = "ID_CONTENT_" + enumScene.NAME.toUpperCase; for (i = 0, n = enumScene.SCHEMA.length; i < n; i++) { enumSchema = enumScene.SCHEMA[i]; enumArrays = enumSchema.PARAMETER_ARRAYS; for (j = 0, m = enumArrays.length; j < m; j++) { elements += this[enumSchema.HANDLER].apply(this, enumArrays[j]); }   }    assembledScene = framework .replace("$1", this.Selectors[selector]) .replace("$2", this.assembleDropdown.apply(this, dropdownArgs)) .replace("$3", elements); this.queryStorage(paramScene, assembledScene); return assembledScene; }; main.buildModal = function  { var modal; modal = { content: this.buildModalScene(this.Scenes[this.Utility.FIRST_SCENE].NAME), id: this.Selectors.ID_MODAL_CONTAINER, size: "large", title: this.i18n.msg("buttonScript").escape, };   modal.buttons = Object.values(this.Buttons).map(function (paramButton) {      if (paramButton.hasOwnProperty("HANDLER")) {        (modal.events = modal.events || {})[paramButton.EVENT] =          this[paramButton.HANDLER].bind(this);      }      return {        text: this.i18n.msg(paramButton.TEXT).escape,        event: paramButton.EVENT,        primary: false,        id: this.Selectors[paramButton.ID],        classes: paramButton.CLASSES.map(function (paramClass) { return this.Selectors[paramClass]; }.bind(this)),     };    }.bind(this)); return new window.dev.modal.Modal(modal); }; main.displayModal = function  { if (this.modal.modal != null) { this.modal.modal.show; return; }   this.injectModalStyles; this.modal.modal = this.buildModal; this.modal.modal.buttons.pop; this.modal.modal.create .then(this.modal.modal.show.bind(this.modal.modal)) .then(this.attachModalEvents.bind(this)) .then(function {        this.modal.isReady = true;        if (this.flags.debug) {          window.console.log("this.modal: ", this.modal);        }      }.bind(this)); }; main.handleSubmit = function  { if (this.timer && !this.timer.isComplete) { if (this.flags.debug) { window.console.dir(this.timer); }     return; }   var $action, $type, $case, $match, $content, $target, $indices, indices, $pages, pages, $byline, $summary, counter, config, data, pageIndex, newText, $getPages, $postPages, $getNextPage, $getPageContent, $postPageContent, error, $scene, isCaseSensitive, isUserRegex, isReplace, isAddition, isMessaging, isListing, $members, $selected, $body, pagesType, replaceOccurrences, isWikitextParsed; $scene = $("#" + this.Selectors.ID_CONTENT_SCENE)[0]; $action = $("#" + this.Selectors.ID_CONTENT_ACTION)[0]; $type = $("#" + this.Selectors.ID_CONTENT_TYPE)[0]; $case = $("#" + this.Selectors.ID_CONTENT_CASE)[0]; $match = $("#" + this.Selectors.ID_CONTENT_MATCH)[0]; $target = $("#" + this.Selectors.ID_CONTENT_TARGET).val; $indices = $("#" + this.Selectors.ID_CONTENT_INDICES).val; $content = $("#" + this.Selectors.ID_CONTENT_CONTENT).val; $pages = $("#" + this.Selectors.ID_CONTENT_PAGES).val; $summary = $("#" + this.Selectors.ID_CONTENT_SUMMARY).val; $selected = $("#" + this.Selectors.ID_CONTENT_TYPE + " option:selected"); $body = $("#" + this.Selectors.ID_CONTENT_BODY).val; $byline = $("#" + this.Selectors.ID_CONTENT_BYLINE).val; $members = $("#" + this.Selectors.ID_CONTENT_MEMBERS); isReplace = ($scene.value === "replace" && $scene.selectedIndex === 0); isAddition = ($scene.value === "add" && $scene.selectedIndex === 1); isMessaging = ($scene.value === "message" && $scene.selectedIndex === 2); isListing = ($scene.value === "list" && $scene.selectedIndex === 3); pagesType = ((isMessaging)     ? this.i18n.msg("modalTypeUsernames").escape      : $selected.text).toLowerCase; if (!isReplace && !isAddition && !isMessaging && !isListing) { return; } else if (!isListing && !this.hasRights(isMessaging)) { this.resetModal("logErrorUserRights"); return; } else if (isAddition && !$content) { this.addModalLogEntry("logErrorNoContent"); return; } else if (isReplace && !$target) { this.addModalLogEntry("logErrorNoTarget"); return; } else if (!$pages) { this.addModalLogEntry("logErrorNoPages", pagesType); return; } else if ($summary && $summary.length > this.Utility.MAX_SUMMARY_CHARS) { this.addModalLogEntry("logErrorOverlongSummary"); return; } else if (isMessaging && !this.isLegalInput($byline)) { this.addModalLogEntry("logErrorSecurity"); return; } else if (isMessaging && !$body) { this.addModalLogEntry("logErrorMissingBody"); return; }   this.addModalLogEntry(      (isReplace || isAddition)        ? "logStatusEditing"        : (isMessaging)          ? "logStatusMessaging"          : "logStatusGenerating"    ); this.toggleModalComponentsDisable("partial", true); if (isReplace) { indices = $indices.split(",").map(function (paramEntry) {       if (this.isInteger(paramEntry.trim)) {          return window.parseInt(paramEntry, 10);        }      }.bind(this)).filter(function (paramEntry) {        return paramEntry != null; // Avoid cases of [undefined]      }); isCaseSensitive = ($case.selectedIndex === 0 &&       $case.value === "sensitive"); isUserRegex = ($match.selectedIndex === 1 &&       $match.value === "regex"); replaceOccurrences = this.replaceOccurrences(isCaseSensitive,       isUserRegex, $target, $content, indices); if (this.flags.debug) { window.console.dir(replaceOccurrences); }   }    pages = $pages.split(/[\n]+/).filter(function (paramEntry) {      return paramEntry !== "";    }); counter = 0; config = {}; $postPages = new $.Deferred; $getNextPage = new $.Deferred; if (this.flags.debug) { window.console.log("hasMessageWalls: ", this.flags.hasMessageWalls); }   $getPages = new $.Deferred(function ($paramOuter) {      new $.Deferred(function ($paramInner) { (!isMessaging || this.flags.hasMessageWalls != null) ? $paramInner.resolve.promise : mw.config.get("wgMessageWallsExist").then(             function  {                return $paramInner.resolve(true).promise;              }.bind(this),              function  {                return $paramInner.resolve(false).promise;              }.bind(this)            ); }.bind(this)).then( function (paramHasWalls) { if (paramHasWalls != null) { this.flags.hasMessageWalls = paramHasWalls; }         return this[ (isListing || (!isMessaging && $type.value !== "pages")) ? "getMemberPages" : (isMessaging) ? "getActiveUsersData" : "getValidatedEntries" ](pages, ($type != null) ? $type.value : null); }.bind(this) ).then( $paramOuter.resolve.bind($), // $getPages.done $paramOuter.reject.bind($), // $getPages.fail $paramOuter.notify.bind($)  // $getPages.progress );   }.bind(this)); $getPages.done(function (paramResults) {     pages = paramResults;      if (this.flags.debug) {        window.console.log("$getPages: ", pages);      }      if (isListing) {        $members.text(pages.join("\n"));        $getNextPage.resolve;        $postPages.resolve("logSuccessListingComplete");        return;      }      this.timer = this.setDynamicTimeout(function  { if (counter === pages.length) { $getNextPage.resolve; $postPages.resolve("logSuccessEditingComplete"); } else { $getPageContent = (isReplace || isAddition) ? this.getPageContent(pages[counter]) : (isMessaging && this.flags.hasMessageWalls && !isWikitextParsed) ? this.getParsedWikitextContent($body) : new $.Deferred.resolve({}).promise; $getPageContent.always($postPages.notify); }     }.bind(this), this.config.interval);    }.bind(this)); $getPages.fail(this.resetModal.bind(this)); $getPages.progress(this.addModalLogEntry.bind(this)); $postPages.always(this.resetModal.bind(this)); $postPages.progress(function (paramResults) {     if (this.flags.debug) {        window.console.log("$postPages results: ", paramResults);      }      if (isAddition || isReplace) {        if ( paramResults.query == null || !paramResults.hasOwnProperty("query") ) {         this.addModalLogEntry("logErrorEditing", pages[counter++]);          return this.timer.iterate;        }        config = {          handler: "postPageContent",          parameters: {            title: pages[counter],            token: mw.user.tokens.get("csrfToken"),            summary: $summary,          }        };        pageIndex = Object.keys(paramResults.query.pages)[0];        data = paramResults.query.pages[pageIndex];      }      if (isAddition) {        if (!this.flags.testing) {          config.parameters[$action.value.toLowerCase + "text"] = $content;        }      } else if (isReplace) {        if ( !data.hasOwnProperty("revisions") || !this.isThisAn("Array", data.revisions) ) {         this.addModalLogEntry("logErrorEditing", pages[counter++]);          return this.timer.iterate;        }        if (pageIndex === "-1") {          this.addModalLogEntry("logErrorNoSuchPage", pages[counter++]);          return this.timer.iterate;        }        config.parameters.text = data.revisions[0]["*"];        newText = replaceOccurrences(config.parameters.text);        if (newText === config.parameters.text) {          this.addModalLogEntry("logErrorNoMatch", $target, pages[counter++]);          return this.timer.iterate;        } else {          if (!this.flags.testing) {            config.parameters.text = newText;          }        }      } else if (isMessaging) {        if ( paramResults.parse != null && paramResults.hasOwnProperty("parse") && !isWikitextParsed ) {         $body = this.buildJsonModel(paramResults.parse.text["*"]);          if (this.flags.debug) {            window.console.log("buildJsonModel: ", $body);          }        }        isWikitextParsed = isWikitextParsed || true;        config = [          {            handler: "postTalkPageTopic",            parameters: (this.flags.testing) ? {} : {              sectiontitle: $byline,              text: $body,              title: pages[counter].name,            }          },          {            handler: "postMessageWallThread",            parameters: (this.flags.testing) ? {} : {              title: $byline,              jsonModel: $body,              wallOwnerId: pages[counter].userid,            }          },        ][+this.flags.hasMessageWalls];      }      if (this.flags.debug) {        window.console.log("Config: ", config);      }      $postPageContent = $.when(this[config.handler](config.parameters)); $postPageContent.always($getNextPage.notify); }.bind(this));   $getNextPage.progress(function (paramData, paramStatus, paramXHR) { if (this.flags.debug) { window.console.log("$getNextPage results: ", paramData, paramStatus,         paramXHR); }     error = (paramData.error && paramData.error.code) ? paramData.error.code : "unknownerror"; if (       ( (!isMessaging || (isMessaging && !this.flags.hasMessageWalls)) && paramData.edit && paramData.edit.result === "Success" ) ||       (          isMessaging && this.flags.hasMessageWalls && paramStatus === "success" && paramXHR.status >= 200 && paramXHR.status < 300 )     ) {        this.addModalLogEntry("logSuccessEditing", (pages[counter].name == null)          ? pages[counter++]          : pages[counter++].name        ); } else if (error === "ratelimited") { this.addModalLogEntry("logErrorRatelimited",         (this.Utility.DELAY / 1000).toString); pages.push(pages[counter++]); } else { this.addModalLogEntry("logErrorEditing", (pages[counter].name == null)         ? pages[counter++]          : pages[counter++].name        ); }     this.timer.iterate(        (error === "ratelimited")          ? this.Utility.DELAY          : null      ); }.bind(this)); };  main.handlePreviewing = function  {    if (this.timer && !this.timer.isComplete) {      if (this.flags.debug) {        window.console.dir(this.timer);      }      return;    }    var $scene, $byline, $body, isMessaging, $previewMessage, contents;    $scene = $("#" + this.Selectors.ID_CONTENT_SCENE)[0];    $byline = $("#" + this.Selectors.ID_CONTENT_BYLINE).val;    $body = $("#" + this.Selectors.ID_CONTENT_BODY).val;    isMessaging = ($scene.value === "message" && $scene.selectedIndex === 2);    if (!isMessaging) {      return;    }    if (!$byline) {      this.addModalLogEntry("logErrorMissingByline");      return;    } else if (!$body) {      this.addModalLogEntry("logErrorMissingBody");      return;    }    $previewMessage = new $.Deferred(function ($paramOuter) { new $.Deferred(function ($paramInner) {       (this.flags.hasMessageWalls != null)          ? $paramInner.resolve(this.flags.hasMessageWalls).promise          : mw.config.get("wgMessageWallsExist").then( function { return $paramInner.resolve(true).promise; }.bind(this), function { return $paramInner.resolve(false).promise; }.bind(this) );     }.bind(this)).then(        function (paramHasWalls) {          if (this.flags.hasMessageWalls == null) {            this.flags.hasMessageWalls = paramHasWalls;          }          return this.getParsedWikitextContent($body);        }.bind(this)      ).then(        $paramOuter.resolve.bind($), // $previewMessage.done        $paramOuter.reject.bind($)   // $previewMessage.fail      ); }.bind(this));   $previewMessage.done(function (paramResults) { if (this.flags.debug) { window.console.log("$previewMessage results: ", paramResults); }     contents = paramResults.parse.text["*"]; this.handleClear({       before: this.displayPreview.bind(this, contents),        after: this.attachPreviewEvents.bind(this),      }); }.bind(this));   $previewMessage.fail(this.addModalLogEntry.bind(this, "logErrorNoPreview"));  };  main.handleToggle = function  {    if ( !this.timer || (this.timer && this.timer.isComplete) ) {     if (this.flags.debug) {        window.console.dir(this.timer);      }      return;    }    var toggle, config;    toggle = "#" + this.Selectors.ID_MODAL_TOGGLE + " ." +      this.Selectors.CLASS_OOUI_LABEL;    config = [      {        message: "logTimerPaused",        text: "buttonResume",        method: "pause",      },      {        message: "logTimerResume",        text: "buttonPause",        method: "resume",      }    ][+this.timer.isPaused];    this.addModalLogEntry(config.message);    $(toggle).text(this.i18n.msg(config.text).escape);    this.timer[config.method];  };  main.handleCancel = function  {    if ( !this.timer || (this.timer && this.timer.isComplete) ) {     if (this.flags.debug) {        window.console.dir(this.timer);      }      return;    } else {      this.resetModal("logTimerCancel");    }  };  main.handleClear = function (paramInput) {    if (this.timer && !this.timer.isComplete) {      if (this.flags.debug) {        window.console.dir(this.timer);      }      return;    }    var $scene, functions, visible, hidden, isTransitioning, modalBodyTarget;    isTransitioning = (typeof paramInput !== "boolean") ? false : paramInput;    $scene = $("#" + this.Selectors.ID_CONTENT_SCENE)[0];    modalBodyTarget = " ." + this.Selectors.CLASS_OOUI_BODY;    visible = {opacity: 1};    hidden = {opacity: 0};    functions = ( this.isThisAn("Object", paramInput) && paramInput.hasOwnProperty("before") && paramInput.hasOwnProperty("after") )     ? paramInput      : [          { // Standard form clear            before: this.resetModal.bind(this),            after: this.addModalLogEntry.bind(this, "logSuccessReset"),          },          { // Scene transition            before: this.modal.modal.setContent.bind(this.modal.modal, this.buildModalScene($scene.value)),           after: this.attachModalEvents.bind(this),          }        ][+isTransitioning];    this.toggleModalComponentsDisable("all");    $("#" + this.Selectors.ID_MODAL_CONTAINER + modalBodyTarget)      .animate(hidden, this.Utility.FADE_INTERVAL, functions.before)      .animate(visible, this.Utility.FADE_INTERVAL, functions.after);  };  main.init = function  {    var i, n, $toolItem, toolText, exports, flags, flag, publicMethod;    exports = {};    flags = Object.keys(this.Flags);    this.i18n.useUserLang;    this.modal = {};    this.timer = null;    this.flags = {      debug: this.Flags.DEBUG,      testing: this.Flags.TESTING,      hasMessageWalls: null    };    toolText = this.i18n.msg("buttonScript").plain;    $toolItem = $(this.assembleOverflowElement(toolText));    $toolItem.on("click", this.displayModal.bind(this));    $(this.config.placement.element)[this.config.placement.type]($toolItem); for (i = 0, n = flags.length; i < n; i++) { flag = flags[i].toLowerCase; publicMethod = "toggle" + this.capitalize(flag); exports[publicMethod] = this.toggleFlag.bind(this, flag); }   return exports; }; init.generateModuleName = function (paramType, paramPage) { return $.merge([paramType], paramPage.split(/[\/.]+/)[0].split(":").filter( function (paramItem) { return !paramItem.match(/^u$|^mediawiki$/gi); }   )).join("."); }; init.definePlacement = function (paramConfig) { var validatedConfig, loader; validatedConfig = {}; loader = window.dev.placement.loader; try { validatedConfig.element = loader.element(paramConfig.element); } catch (e) { validatedConfig.element = loader.element(this.Placement.DEFAULTS.ELEMENT); }   try { validatedConfig.type = loader.type(       (this.Placement.VALID_TYPES.indexOf(paramConfig.type) !== -1)          ? paramConfig.type          : this.Placement.DEFAULTS.TYPE      ); } catch (e) { validatedConfig.type = loader.type(this.Placement.DEFAULTS.TYPE); }   loader.script(this.Utility.SCRIPT); return Object.freeze(validatedConfig); }; init.defineInterval = function (paramInterval) { var isNumber; isNumber = (typeof paramInterval === "number" &&     window.isFinite(paramInterval) && !window.isNaN(paramInterval)); if (     this.globals.wgUserGroups.indexOf("bot") !== -1 &&      (paramInterval < this.Utility.BOT_INTERVAL || !isNumber)    ) { return this.Utility.BOT_INTERVAL; // Reset to max 80 edits/minute } else if (     this.globals.wgUserGroups.indexOf("user") !== -1 &&      (paramInterval < this.Utility.STD_INTERVAL || !isNumber)    ) { return this.Utility.STD_INTERVAL; // Reset to max 40 edits/minute } else { return window.parseInt(paramInterval, 10); } };  init.main = function (paramRequire, paramLang) { var i, n, configTypes, descriptor, parameter, lowercase, method, property, descriptorProperties, userConfig, field, instanceFields, initExports, instanceExports; delete this.modules; configTypes = ["Interval", "Placement"]; instanceFields = [ {       name: "i18n", value: paramLang, },     {        name: "config", value: {}, },     {        name: "globals", value: $.extend({}, this.globals), },   ];    userConfig = window.MassEditConfig || window.configMessage || {}; descriptor = {}; descriptorProperties = { enumerable: true, configurable: false, writable: false, };   for (i = 0, n = instanceFields.length; i < n; i++) { field = instanceFields[i]; descriptor[field.name] = $.extend({}, descriptorProperties); descriptor[field.name].value = field.value; }   for (i = 0, n = configTypes.length; i < n; i++) { property = configTypes[i]; method = "define" + property; lowercase = property.toLowerCase; parameter = (userConfig.hasOwnProperty(lowercase)) ? userConfig[lowercase] : null; Object.defineProperty(descriptor.config.value, lowercase,       $.extend($.extend({}, descriptorProperties), { value: this[method](parameter), })     );    }    initExports = { observeScript: window.console.dir.bind(this, this), observeUserConfig: window.console.dir.bind(this, userConfig), };   instanceExports = (this.instance = Object.create(main, descriptor)).init; Object.defineProperty(module, "exports",     $.extend($.extend({}, descriptorProperties), { value: Object.freeze($.extend(initExports, instanceExports)), })   );    mw.hook(this.Utility.HOOK_NAME).fire(module); }; init.load = function (paramDeferred) { var debug, articles, counter, numArticles, $loadNext, current, isLoaded, article, server, params, resource, moduleName; debug = false; counter = 0; articles = this.Dependencies.ARTICLES; numArticles = articles.length; $loadNext = new $.Deferred; this.globals = Object.freeze(mw.config.get(this.Globals)); paramDeferred.notify.progress(function (paramResponse) {     if (paramResponse != null) {        window.Promise.resolve(paramResponse).then(function (paramResponse) { if (debug) { window.console.log("paramResponse, mw.hook", paramResponse); }       }, function (paramError) { if (debug) { window.console.warn("paramError, mw.hook", paramError); }       });      }      if (counter === numArticles) {        $loadNext.resolve;        if (debug) {          window.console.log("$loadNext", $loadNext.state);        }        window.dev.i18n.loadMessages(this.Utility.SCRIPT, { cacheVersion: this.Utility.CACHE_VERSION, }).then(paramDeferred.resolve).fail(paramDeferred.reject);     } else {        if (debug) {          window.console.log((counter + 1) + "/" + numArticles);        }        $loadNext.notify(counter++);      }    }.bind(this)); $loadNext.progress(function (paramCounter) {     current = articles[paramCounter];      isLoaded =        (current.DEV && window.dev.hasOwnProperty(current.DEV)) ||        (current.WINDOW && window.hasOwnProperty(current.WINDOW));      if (isLoaded && current.HOOK) {        if (debug) {          window.console.log("isLoaded", current.ARTICLE);        }        return mw.hook(current.HOOK).add(paramDeferred.notify);      }      try {        article = window.importArticle({ type: current.TYPE, article: current.ARTICLE, });       if (debug) {          window.console.log("importArticle", article);        }        return (current.HOOK)          ? mw.hook(current.HOOK).add(paramDeferred.notify)          : $(article).on("load", paramDeferred.notify);      } catch (paramError) {        if (debug) {          window.console.error(this.Utility.SCRIPT, paramError);        }        server = "https://dev.fandom.com/load.php";        params = "?" + $.param({ mode: "articles", only: current.TYPE + "s", articles: current.ARTICLE, });       resource = server + params;        moduleName = this.generateModuleName(current.TYPE, current.ARTICLE);        if (debug) {          window.console.log(moduleName);        }        try {          mw.loader.implement.apply(null, $.merge([moduleName],            (current.TYPE === "script")              ? resource              : [null, {"url": {"all": [resource]}}]          ));        } catch (paramError) {          if (debug) {            window.console.error(paramError);          }        }        mw.loader.using(moduleName)          .then((current.HOOK) ? mw.hook(current.HOOK).add(paramDeferred.notify) : paramDeferred.notify)         .fail(paramDeferred.reject);      }    }.bind(this)); }; $.when(    mw.loader.using(init.Dependencies.MODULES),    new $.Deferred(init.load.bind(init)).promise) .then(init.main.bind(init)) .fail(window.console.error.bind(window.console, init.Utility.SCRIPT)); }((this.dev = this.dev || {}).massEdit = this.dev.massEdit || {}, this, this.jQuery, this.mediaWiki)); /**/ mw.loader.using('mediawiki.api').then(function { "use strict"; if (window.AjaxRename && window.AjaxRename.loaded) return window.AjaxRename.logMessage({ type: 'warn', message: 'Script double loaded, exiting...' }); window.AjaxRename = $.extend({		loaded: true,		renameReasons: null,		doKeybind: true,		check: {},		wg: mw.config.get([ 'wgPageName', 'wgArticlePath', 'wgUserGroups', 'wgNamespaceNumber', ]),		namespaces: mw.config.get('wgFormattedNamespaces'),		csrfToken: mw.user.tokens.values.csrfToken,		version: 0.5,		hooksCount: 0,		currentModal: null,		lang: null,		$modalContent: '#AjaxRenameModal > section',		$modal: '#AjaxRenameModal',		$modalTitle: '#AjaxRenameModal > header > h3',		hook: Object.freeze({ loaded: mw.hook('dev.ajaxrename.loaded'), modalLoading: mw.hook('dev.ajaxrename.modal.loading'), modalLoaded: mw.hook('dev.ajaxrename.modal.loaded'), modalClosed: mw.hook('dev.ajaxrename.modal.closed'), modalCancelled: mw.hook('dev.ajaxrename.modal.cancelled'), }),		checkboxList: Object.freeze({ 'SuppressRedirect': 'option-suppress-redirect', 'MoveSubpages': 'option-move-subpages', 'MoveTalk': 'option-move-talk', 'DeleteTargets': 'option-delete-targets', 'Watch': 'option-watch', 'IgnoreWarnings': 'option-ignore-warnings', }),		checkboxConversions: Object.freeze({ 'suppress-redirect': Object.freeze({				alt: 'leaveredirect',				value: 'leaveRedirect',				'default': true,				requirement: 'move',			}), 'watch': Object.freeze({				alt: 'watch',				value: 'watch',				'default': true,				requirement: 'move',			}), 'move-talk': Object.freeze({				alt: 'movetalk',				value: 'talk',				'default': false,				requirement: 'move',			}), 'move-subpages': Object.freeze({				alt: 'movesubpages',				value: 'subpages',				'default': false,				requirement: 'move',			}), 'delete-targets': Object.freeze({				alt: 'deletetargets',				value: 'deleteTargets',				'default': false,				requirement: 'delete',			}), 'ignore-warnings': Object.freeze({				alt: "ignorewarnings",				value: 'ignore',				'default': false,				requirement: 'move',			}), }),		imports: Object.freeze({ scripts: Object.freeze([				'u:dev:MediaWiki:UI-js/code.js',				'u:dev:MediaWiki:I18n-js/code.js',			]), style: Object.freeze([				'u:dev:MediaWiki:AjaxRename.css',			]), hooks: Object.freeze([				'dev.i18n',				'dev.qdmodal',				'dev.ui',			]), await: [ 'mediawiki.api', 'mediawiki.util', ],			otherOnloadPromises: [ $.ajax({					cache: true,					dataType: "script",					url: "https://dev.fandom.com/load.php?mode=articles&only=scripts&articles=MediaWiki:QDmodal.js"				}), ],		}),		rights: Object.freeze({ "global": Object.freeze([				'staff',				'helper',				'global-discussions-moderator',				'wiki-representative',				'wiki-specialist',								'soap',				]), "checkuser": Object.freeze([				'soap',				'helper',				'staff',				'global-discussions-moderator',								'wiki-representative',				'wiki-specialist',				'checkuser',				'util',			]), "block": Object.freeze([				'sysop',				'autoconfirmed',				'emailconfirmed',				'bureaucrat',				'global-discussions-moderator',				'wiki-representative',				'wiki-specialist',								'soap',			]), "delete": Object.freeze([				'content-moderator',				'threadmoderator',				'sysop',				'soap',				'autoconfirmed',				'emailconfirmed',				'global-discussions-moderator',				'wiki-representative',				'wiki-specialist',				'util',			]), "move": Object.freeze([				"user",				]), }),		hooks: function {			this.imports.hooks.forEach(function(v) { mw.hook(v).add(this.onHook.bind(this, v)); }.bind(this));			this['import'];		},		onHook: function(value, arg) {			++this.hooksCount;			switch (value) {				case("dev.i18n"): 					this.i18n = arg;					break;				case('dev.qdmodal'):					this.Modal = mw.libs.QDmodal;					break;				case('dev.ui'): 					this.ui = arg;					break;			}			if (this.hooksCount === 3) {				this.i18n.loadMessages('AjaxRename', { language: this.lang })					.then(this.init.bind(this))					.catch(function(e) { console.warn(e); });			} else return;		},		loadSpecialPageAliases: function {			return this.api.get({ action: 'query', meta: 'siteinfo', siprop: 'specialpagealiases', });		},		'import': function {			mw.loader.using('mediawiki.api').always(function { this.logMessage({ message: 'importing...' }); this.api = new mw.Api; Object.freeze(this.imports.await); this.loadSpecialPageAliases.always(function(res) {					this.parseSpecialPageAliases(res);					this.imports.otherOnloadPromises.push( mw.loader.using(this.imports.await), importArticles({							type: "script",							articles: this.imports.scripts,						}), importArticles({							type: "style",							articles: this.imports.style,							}) );				}.bind(this)); }.bind(this)).catch(function(e) { console.warn(e); });		},		init: function(i18n) {			this.i18n = i18n;			this.wg.wgArticlePath = this.wg.wgArticlePath.replace('$1', ''),			this.getParamValue = mw.util.getParamValue;			Object.freeze(this.wg);			this.logMessage({ message: 'Ready' });			this.hook.loaded.fire;			this.i18n.useUserLang;			$(document).on('click', 'a[href]', this.onDocumentClick.bind(this));			this.addKeydownEvents;		},		getRights: function(action) {			action = action.toLowerCase;			switch(action.toLowerCase) {				case("global"): return this.rights[action];				case("checkuser"): return this.rights[action];				case("block"): return this.rights[action];				case("protect"):				case("delete"):	return this.rights["delete"];				case("move"): return this.rights[action];			}		},		hasRights: function(level) {			var rights = this.getRights(level),				len = rights.length;			while (len--) {				if (this.wg.wgUserGroups.indexOf(rights[len]) !== -1) { return true; }			}			return false; },		canRun: function { return this.hasRights("move"); },		parseSpecialPageAliases: function(d) { var data = d.query.specialpagealiases.filter(function(page) {					return page.realname === "Movepage";				})[0], specialpages = [data.realname].concat(data.aliases); this.specialPageAliases = specialpages; return specialpages; },		deletePage: function(data, cb, cbCond) { return this.apiPost({				action: 'delete',				reason: data.reason,				title: data.title,			}); },		movePage: function(data, cb, cbCond) { return this.apiPost({				action: 'move',				reason: data.reason,				from: data.from,				to: data.to,				movetalk: data.movetalk,				movesubpages: data.movesubpages,				noredirect: data.noredirect,				watchlist: this.isNullish(data.watchlist, 'nochange')			}); },		apiPost: function(data) { var defaultParams = { watchlist: 'preferences', token: mw.user.tokens.values.csrfToken, bot: true, title: data.title || ((data.action === 'delete') ? this.wg.wgPageName : undefined), };			var params = $.extend(data, defaultParams); return this.api.post(params); },		logPromiseResponse: function(data) { var success = data.success, fail = data.fail; fail.notification = fail.notification || {}; success.notification = success.notification || {}; if (typeof(data.res) === "object") { return this.logMessage({ 					type: success.type || 'success', 					message: success.message.replace(/"\[+|\]+"/g, ''),					showNotification: success.showNotification,				}); } else { return this.logMessage({					type: fail.type || 'warn', 					message: fail.message.replace(/"\[+|\]+"/g, ''),					showNotification: fail.showNotification,				}); }		},		logMessage: function(data){ var funcKeys = { 'notify': console.log, 'confirm': console.log, 'success': console.log, 'warn': console.warn, 'error': console.error, undefined: console.log, },				logKeys = { 'notify': 'LOG', 'confirm': 'LOG', 'success': 'LOG', 'warn': 'WARN', 'error': 'ERROR', undefined: 'LOG', };			data.type = (data.type || 'success').toLowerCase; data.message = Array.isArray(data.message) ? data.message : [ data.message ]; data.message.unshift('[AjaxRename: v' + this.version + '] [' + logKeys[data.type] + ']:'); funcKeys[data.type].apply(window.console, data.message); var notificationMessage = Array.from(data.message); notificationMessage.shift; notificationMessage = notificationMessage.join(' '); data.message = data.message.join(' '); if (data.showNotification) { mw.notify(notificationMessage, { type: data.type }); }			return data.message; },		msg: function { return this.i18n.msg.apply(null, arguments).plain; },		getPage: function(url, type) { type = type || 'from'; if (!this.isValidLink(url)) return; if (type.toLowerCase === 'from') { return this.getParamValue('wpOldTitle', url) || (url.match(/\/wiki\/.+?\/([^\n\?]+)/) || [])[1]; } else if (type.toLowerCase === 'to') { return this.getParamValue('wpNewTitle', url); }		},		isValidLink: function(url) { var isMoveable = this.specialPageAliases.some(function(alias) {				return new RegExp(alias, 'i').test(decodeURI(url));			}); return isMoveable; },		getBooleanUrlParam: function(url, param) { return Boolean(this.findUrlParam(url, param)); },		getCheckConfigValue: function(name, type) { var checkboxData = this.modalOptions.check, conversions = this.checkboxConversions, name = name.toLowerCase.replace('option-', ''), data = conversions[name], alt = data.alt, configVal = data.value, defaultRet = this.nullishDefault(this.check[configVal] || this.check[alt], data['default']); if (!this.isNullish(type)) { return data[type]; } else { return defaultRet !== undefined ? defaultRet : false; }		},		getCheckboxStates: function { var result = {}; Object.keys(this.checkboxList).forEach(function(id) {				var name = this.checkboxList[id],					name = name.toLowerCase.replace('option-', '');				result[name] = $('#AjaxRename-Checkbox-' + id).prop('checked');			}.bind(this)); return result; },		getUrlParams: function(url) { var booleanKeys = { 'move-talk': 'wpMovetalk', 'move-subpages': 'wpMovesubpages', 'suppress-redirect': 'wpLeaveRedirect', 'delete-targets': 'wpDeleteTargets', 'watch': 'wpWatch', 'ignore-warnings': 'wpIgnore', },				ret = {}; ret.check = {}; Object.keys(booleanKeys).forEach(function(k) {				var v = booleanKeys[k],					urlParam = this.getParamValue(v, url);				ret.check[k] = !this.isNullish(urlParam) ? Boolean(Number(urlParam)) : urlParam;			}.bind(this)); ret.reason = this.getParamValue('wpReason', url); return ret; },		getInputReason: function { var dropdownValue = $('#AjaxRename-InputFieldOptions-RenameReasons').val, otherValue = $('#AjaxRename-InputFieldOther-OtherRenameReason').val, ret = dropdownValue ? dropdownValue + (otherValue ? ': ' + otherValue : '') : otherValue; this.renameReason = ret; return ret; },		generateCheckbox: function(data) { var name = 'AjaxRename-Checkbox-' + data.id, ret = { type: 'div', attr: { id: name + '-Wrapper', },					condition: data.requirement, children: [{ type: 'input', attr: { type: "checkbox", name: name, id: name, checked: data.checked ? data.checked : undefined, },					}, {						type: "label", text: this.msg(data.label), attr: { id: name + '-Label', 'for': name, 'class': 'AjaxRename-CheckboxLabel', },					}],				};			if (!data.checked) delete ret.children[0].attr.checked; return ret; },		isNullish: function(v) { return v === null || v === undefined; },		nullishDefault: function(v, $default) { return this.isNullish(v) ? $default : v; },		buildOptionsDropdown: function(data) { if (!data) return null; var arr = [], objData = Object.entries(data); for (var i1 in objData) { var entries = objData[i1], key = entries[0], value = entries[1], subObjData = Object.entries(value); if (typeof(value) === "object") { var tmpObj = { type: "optgroup", children: [], attr: { label: key, },					};					for (var i2 in subObjData) { var entrs = subObjData[i2], k = entrs[0], v = entrs[1]; tmpObj.children.push({							type: "option",							text: k,							attr: {								value: v,							}						}); }					arr.push(tmpObj); } else { arr.push({						type: "option",						text: key,						attr: {							value: value,						},					}); }			}			arr.unshift({				type: 'option',				value: '',				text: 'Other',				}); return arr; },		addButton: function { function _addButton(data) { var $obj = { 'class': "qdmodal-button", html: data.text, click: data.click, };				$obj = $.extend($obj, data.attrs); $('#AjaxRenameModal > footer').append($(' ', $obj)); }			if (arguments.length > 1) { Array.prototype.forEach.call(arguments, function(v) {					_addButton(v);				}); } else { _addButton(arguments[0]); }		},		generateModalForm: function(data) { var arr = []; function _generateHeader(data) { return { type: 'div', style: { 'margin-bottom': '1.3em', 'margin-top': '0.5em', 'border-bottom': '1.5px solid lightgray', },					text: data.text, };			}			Object.keys(this.checkboxList).forEach(function(k, i) {				var v = this.checkboxList[k],					getCheckData = this.getCheckConfigValue.bind(this),					checked = !this.isNullish(data.check[v.replace('options-', )]) ? data.check[v.replace('options-', )] : getCheckData(v),					subpageExists;				if (i === 1 || i === 2) {					subpageExists = 						i === 1 							? !!data.subpages							: !!data.talkSubpages;				} else {					subpageExists = true;				}				arr.push(this.generateCheckbox({					id: k,					label: v,					checked: checked,					requirement: this.hasRights(getCheckData(v, 'requirement') || 'move') && subpageExists,				}));				if (i === 3) {					arr.push(_generateHeader({						text: this.msg('extra-options'),					}));									}			}.bind(this)); arr.unshift(_generateHeader({ text: this.msg('rename-options'), }));			var modalForm = this.ui({				type: "div",				children: [{					type: 'p',					html: this.i18n.msg('modal-text', data.from, this.msg('option-suppress-redirect')).parse,				}, { 					type: 'div',					html: data.warning,					condition: data.warning,					classes: [ "mw-warning-with-logexcerpt" ],				}, {					type: "div",					html: this.i18n.msg('file-warning', data.from).parse,					classes: [ "mw-warning-with-logexcerpt" ],					condition: this.wg.wgNamespaceNumber === 6,				}, {					type: "fieldset",					style: {						"margin": "none !important",					},					children: [{						type: 'legend',						children: [ this.msg('modal-title', data.from) ]					}, {						type: 'form',						attr: {							method: ,							name: ,						},						classes: ['WikiaForm'],						children: [							{								type: 'span',								attr: {									id: "AjaxRename-Inputs"								},								children: [									this.generateInputField({ fieldLabel: this.msg('input-new-title'), otherInput: { id: "NewTitle", value: data.to, },										optionsDropdown: {}, }),									this.generateInputField({ fieldLabel: this.msg('reason-prompt'), optionsDropdown: { id: "RenameReasons", select: this.renameReasons, },										otherInput: { id: "OtherRenameReason", value: data.reason, }									}),								],							},							{								type: 'div'	,								children: arr,							},							{								type: 'div',								id: 'AjaxRenameExtraPages',								html: data.logHtml,							}						],					}],				}],			}); this.modalForm = modalForm; return modalForm; },		generateInputField: function(data) { var ret = { type: "div", children: [ {						type: 'span', html: data.fieldLabel + ': ', },					{						type: 'select', attr: { id: 'AjaxRename-InputFieldOptions-' + data.optionsDropdown.id, },						children: this.buildOptionsDropdown(data.optionsDropdown.select) || [], condition: !!data.optionsDropdown.select, },					{						type: data.optionsDropdown.select ? 'div' : 'span', children: [{ type: "input", attr: { id: 'AjaxRename-InputFieldOther-' + data.otherInput.id, value: data.otherInput.value, },						}],					},				],			};			if (this.isNullish((data.otherInput || {}).value)) delete ret.children[2].children[0].attr.value; return ret; },		requestMoveData: function(page) { return $ .get(this.wg.wgArticlePath + 'Special:MovePage/' + (page || this.wg.wgPageName)) .then(function(res) {					var $document = $(res),						$content = $document.find('#mw-content-text'),						data = {};					if (!$document.find('#mw-returnto').length) { 					var $sel = $document.find('.movepage-wrapper')								.first								.nextUntil,						$htmlText = function {							var arr = [' '];							$sel.each(function { arr.push($(this).prop('outerHTML')); });							arr.push(' '); 							return arr.join('');						},						$html = $($htmlText),						noLog = !!$html.find('.mw-warning-logempty').length;					function _findSubpages(num, arr) {						$html.find('ul:nth-of-type(' + num + ') > li > a').each(function(a, b, c) { arr.push($(this).html); });						return $html.find('ul:nth-of-type(' + num + ')').length ? arr : null;					}					var subpages = _findSubpages(noLog ? 1 : 2, []),						talkSubpages = _findSubpages(noLog && subpages ? 2 : !subpages && noLog ? 1 : 3, []),						$warning = $content.find('[class^="mw-warning"]').first;					var ret = {						warning: $warning.html,						content: $htmlText,						subpages: subpages,						talkSubpages: talkSubpages, 					};					this.moveData = ret;					return ret;					} else {						return false;					}				}.bind(this)) .catch(function(e) {					console.warn(e);					}); },		showModal: function(options) { if ($(this.$modal).length) { $(this.$modal).parent.remove; }			var modal = new this.Modal('AjaxRenameModal'); this.hideModal = function { try { modal.hide; } catch(ignore) {} this.currentModal = null; this.hook.modalClosed.fire; };			modal.show({				content: '',				title: this.msg('loading') + '...',				buttons: [],				onHide: function {					this.currentModal = null;					this.hook.modalClosed.fire;				}.bind(this),			}); this.currentModal = modal; $(this.$modalContent).addClass('mw-ajax-loader').css({ width: '900px', height: '500px' }); $('#AjaxRename .qdmodal-button, .qdmodal-close').click(this.hideModal.bind(this)); this.requestMoveData(options.from).then(function(moveData) {				if (!moveData) {					$(this.$modalContent).removeClass('mw-ajax-loader');					$(this.$modalTitle).html(this.msg('title-noexist-header'));					$(this.$modalContent).html(this.i18n.msg('title-noexist', options.from).parse);					this.addButton({ text: this.msg('button-cancel'), click: this.hideModal.bind(this), });					this.logMessage({ message: 'Page does not exist, exiting...' });					return;				}				$(this.$modalContent).html(this.currentModal = this.generateModalForm({ 					title: options.modalTitle,					check: options.check,					warning: moveData.warning,					logHtml: moveData.content,					reason: options.reason,					from: options.from,					to: options.to,					subpages: moveData.subpages,					talkSubpages: moveData.talkSubpages,				}));				this.addButton({ text: this.msg('button-rename'), click: this.renameHandler.bind(this, moveData, {						normal: moveData.subpages,						talk: moveData.talkSubpages, 					}), }, {					text: this.msg('button-cancel'), click: this.hideModal.bind(this), });				$(this.$modalTitle).html(options.modalTitle);				$(this.$modalContent).removeClass('mw-ajax-loader').css({ width: 'fit-content', height: 'fit-content', });				$('#AjaxRename-InputFieldOther-NewTitle').focus;				$('#AjaxRename-InputFieldOther-NewTitle').val(options.from);				$('#AjaxRename-InputFieldOther-OtherRenameReason, #AjaxRename-InputFieldOther-NewTitle')					.keydown(function(event) { if (event.key.toLowerCase === 'enter') { $('.qdmodal-button').first.click; }						});				this.logMessage({ message: 'Successfully showed the modal!' });				this.hook.modalLoaded.fire;			}.bind(this)).catch(function(e) {				this.logMessage({ message: e, type: 'error' });			}.bind(this)); return modal; },		renameHandler: function(moveData, subpages, event) { moveData.from = this.modalOptions.from; moveData.to = $('[id$="NewTitle"]').first.val; var check = this.getCheckboxStates, watch = check.watch ? 'watch' : "preferences", reason = this.getInputReason; var ext1 = moveData.from.match(/\.([a-z]+)$/) || [], ext2 = moveData.to.match(/\.([a-z]+)$/) || []; if (!$('#AjaxRename-InputFieldOther-NewTitle').val) { alert(this.msg('no-title', this.modalOptions.from)); this.logMessage({ message: 'Failed to rename' + moveData.from + ': No title to rename to', type: 'warn' }); return; }			if (moveData.from === $('#AjaxRename-InputFieldOther-NewTitle').val) { alert(this.msg('selfmove', this.modalOptions.from)); this.logMessage({ message: 'Failed to rename' + moveData.from + ': Old title is same as new title', type: 'warn' }); return; }			if (( ext1[1] !== ext2[1] || !moveData.to.match(/^File:/) ) && this.wg.wgNamespaceNumber === 6) { alert(this.msg('file-cannot-move', moveData.from, moveData.to)); this.logMessage({ message: this.msg('file-cannot-move', moveData.from, moveData.to), type: 'warn' }); return; }			this.hideModal.call(this); function _mergePagesList(replaceNew) { var arr = new Array; if (!subpages.normal) subpages.normal = []; if (!subpages.talk) subpages.talk = []; function _iter(a) { a.forEach(function(v) {						arr.push(replaceNew ? v.replace(moveData.from, moveData.to) : v);					}); }				subpages.normal.unshift(moveData.from); if (!check['move-subpages']) { subpages.normal.splice(1); }				_iter(subpages.normal); if (check['move-talk']) { var talkPage, temp = check['move-subpages'] ? subpages.talk : []; if (moveData.to.match(':')) { talkPage = moveData.to.replace('^([^:]+):', function(_, $1) {							return $1 + ' Talk';							}); } else { talkPage = 'Talk:' + moveData.to; }					temp.unshift(talkPage); _iter(temp); }				return arr; }			var newPages = _mergePagesList(true), oldPages = _mergePagesList(false); var _delete = function(newPage) { promises.deletions.push(this.deletePage({ title: newPage, reason: this.msg('move-delete-reason', newPage.replace(moveData.to, moveData.from)), watch: watch, }));				}.bind(this), promises = {}, pages = {}, _move = function { return this.movePage({						reason: reason,						from: moveData.from,						to: moveData.to,						noredirect: !check['suppress-redirect'],						movesubpages: check['move-subpages'],						movetalk: check['move-talk'],						ignorewarnings: check['ignore-warnings'],						watchlist: watch,					}); }.bind(this); promises.deletions = []; pages.deletions = []; if (check['delete-targets']) { for (var i in newPages) { var v = newPages[i]; _delete(v); pages.deletions.push(v); }			}			function _finishPromises(promises, responseCallback) { return $.when.apply($, promises).always(function {					$.each(arguments, responseCallback)	;				}); }			_finishPromises(promises.deletions, function(i, res) {				this.logPromiseResponse({ res: res, success: { message: this.msg('log-success-delete', pages.deletions[i]), showNotification: false, },					fail: { message: this.msg('log-fail-delete', pages.deletions[i], res), showNotification: false, },				});				}.bind(this)).always(function {								_move					.always(function(res) { this.logPromiseResponse({							res: res,							success: {								message: this.msg('log-success-move', moveData.from, moveData.to, reason),								showNotification: true,							},							fail: {								message: this.msg('log-fail-move', moveData.from, moveData.to, res),								showNotification: true,							},						}); }.bind(this));			}.bind(this)); },		fireModal: function(link) { var query = (link || '').match(/\?(\S+)$/), modalOptions = { id: "AjaxRenameModal", modalTitle: decodeURI(this.msg('modal-title', this.getPage(link))), };			if (!this.isValidLink(decodeURI(link))) return; modalOptions.from = this.getPage(decodeURI(link)); modalOptions.to = this.getPage(decodeURI(link), 'to'); $.extend(modalOptions, this.getUrlParams(decodeURI(link))); this.modalOptions = modalOptions; this.modalOptions.from = this.modalOptions.from.replace(/[_\+]/g, ' '); this.showModal(modalOptions); this.hook.modalLoading.fire; },		onDocumentClick: function(event) { var $clickedElem = $(event.target), clickedLink = $clickedElem ? $clickedElem.prop('href'): null; if (event.shiftKey || event.ctrlKey) return; if (!this.isValidLink(decodeURI(clickedLink))) return; event.preventDefault; this.fireModal(clickedLink); },		addKeydownEvents: function { if (!this.doKeybind) return; function _addEvent(Mousetrap) { Mousetrap.bind('m', function {					this.fireModal( window.location.href .replace(this.wg.wgArticlePath, this.wg.wgArticlePath + 'Special:MovePage/') );				}.bind(this)); }			_addEvent.call(this, window.Mousetrap); },	}, window.AjaxRename);	if (!AjaxRename.canRun) return AjaxRename.logMessage({ message: 'User does not have neccessary rights to run, exiting...' });	AjaxRename.hooks; }).fail(function(e) {	console.warn(e); }); /**/ (function($, mw) {	var userGroups = mw.config.get("wgUserGroups"),		specialPage = mw.config.get("wgCanonicalSpecialPageName"),		supportedPages = [			[				'Listredirects',				'Lonelypages',				'Ancientpages',				'Fewestrevisions',				'Withoutinterwiki',				'Shortpages',				'Uncategorizedfiles',				'Uncategorizedpages',				'Uncategorizedtemplates',				'Unorganizedtemplates',				'Unusedcategories',				'Unusedtemplates',				'BrokenRedirects',				'Unusedcategories',				'Unusedtemplates',				'Deadendpages',				'Shortpages',			], [				'Allpages',				'Prefixindex',				'Whatlinkshere',			], [				'Unusedimages',			],		];	var logger = (function { Object.keys(this).forEach(function(method) {			this[method] = this[method].bind(null, '[MultipleFileDelete] [' + method.toUpperCase + ']:');		}, this); return this; }).call({ error: console.error, warn: console.warn, log: console.log, debug: mw.log, });	if (!supportedPages.flat.includes(specialPage) // not from list || !/staff|helper|sysop|content-moderator|autoconfirmed|emailconfirmed|soap/.test(userGroups.join('\n')) || window.mfdLoaded || (window.mfdExclude && (window.mfdExclude === page || window.mfdExclude.indexOf(page) >= 0)) ) {			return logger.log('Page is not supported, or script is double loading, exiting...');		}	window.mfdLoaded = true;	var btnProps = {			css: {				cursor: 'pointer',				height: 'initial',				'margin-left': 3,			}		},		i18n = {},		$wrapper = $,		$oldButton,		specialPageType = supportedPages.findIndex(function(pages) { return pages.indexOf(specialPage) >= 0; }) + 1,		time = 0,		wgArticlePath = mw.config.get('wgArticlePath').replace(/\$1/, '');		api = new mw.Api,		i18Messages = [			'start', 			'delete', 			'check',			'uncheck', 			'enter', 			'reason',			'noselect', 			'error', 			'success',			'uninvert',			'invert',		];	function preload(i18nLoaded) {		i18Messages.forEach(function(msg) { i18n[msg] = i18nLoaded.msg(msg).plain; });		init;	}	function init {		$wrapper = $(' ', { html: $(' ', $.extend({ class: 'btn-mfd-start', text: i18n.start, click: start, }, btnProps)) });		$([			'.mw-allpages-body', '.mw-prefixindex-body', '.mw-spcontent > p:first-of-type', '.mw-spcontent > p:last-of-type', 'body.mw-special-Whatlinkshere #mw-content-text > p:first-of-type', ].join(', ')).before($wrapper);		$([ '.mw-prefixindex-body', '.mw-allpages-body', 'body.mw-special-Whatlinkshere #mw-content-text' ].join(', ')).after($wrapper.clone);	}	function start {		$('.btn-mfd-start').after( $(' ', $.extend({ class: 'btn-mfd-delete', text: i18n['delete'], click: performDelete, }, btnProps)), $(' ', $.extend({ class: "btn-mfd-check", text: i18n.check, click: performCheck, }, btnProps)), $(' ', $.extend({ class: "btn-mfd-invert", text: i18n.invert, click: invertSelection, }, btnProps)) );		$oldButton = $('.btn-mfd-start').remove;		var $chk = $(' ', { class: "selectiveDel", type: "checkbox", });		switch (specialPageType) {			case 1:				mw.util.$content.find('ol li a:first-child').each(function { $(this).before($chk.clone); selectHax(this); });				break;			case 2:				if ($('.mw-allpages-chunk').length) { // Allpages					$('.mw-allpages-chunk li > a').each(function { $(this).before($chk.clone); selectHax(this); });				} else if ($('#mw-whatlinkshere-list').length) { // WhatLinksHere					$('#mw-whatlinkshere-list > li > a').each(function { $(this).before($chk.clone); selectHax(this); });				} else { //PrefixIndex					$('.mw-prefixindex-list > li a, .gallery-image-wrapper').each(function { $(this).before($chk.clone); selectHax(this); });				}				break;			default:				$('.gallerytext > a, .gallery-image-wrapper').each(function { $(this).has('.image.lightbox').before($chk.clone); selectHax(this); });		}	}	function performDelete {		var selected = $('.selectiveDel:checked');		if (!selected.length)			return alert(i18n.noselect);		var deleteReason = prompt(i18n.enter, i18n.reason);		if (!deleteReason)			return;		$(this)			.attr('disabled', true)			.text("Deleting Pages...")			.css({ 'background-repeat': 'no-repeat', 'background-position': 'center' });		selected.each(function(i) { var $link = $(this).parent.find('a').first; var page; if (specialPageType === 3) { page = $link.attr('href') .replace(wgArticlePath, '') .replace(mw.config.get('wgServer'), ''); } else { page = $link.attr('title') || $link.text; }			apiDelete(				page,				deleteReason,				$link,				i+1,				selected.length			); });	}	function performCheck {		var $btn = $('.btn-mfd-check');		var $checkboxes = $('.selectiveDel');		if ($btn.first.text === i18n.uncheck) {			$checkboxes.each(function { this.checked = false; });			$btn.text(i18n.check);		} else {			$checkboxes.each(function { this.checked = true; });			$btn.text(i18n.uncheck);		}		displayCount;	}	function selectHax(elem) { 		var $elem = $(elem);		var $parent = $elem.parent;		$parent.hover(function { $(this).css({				cursor: 'pointer',				background: 'rgba(0,0,0,.2)'			}); }, function { $(this).css({				background: 'initial'			}); });		$parent.click(function(e) { if (e.target === this) { var input = $(this).children('input')[0]; input.checked = !input.checked; }			displayCount; });	}	function invertSelection {		$('.selectiveDel').each(function { this.checked = !this.checked; });		$(this).text($(this).text === i18n.invert ? i18n.uninvert : i18n.invert);		displayCount;	}	function displayCount {		$('.btn-mfd-delete').text( i18n['delete'] + ' ('			+ $('.selectiveDel:checked').length			+ ')');	}	function reset {		$('.btn-mfd-delete')			.attr('disabled', false)			.text(i18n['delete'])			.css({ 'background-image': "", });		$('.btn-mfd-check').text(i18n.check);		$('.btn-mfd-invert').text(i18n.invert);	}	function apiDelete(page, reason, $link, cur, count) {		page = decodeURIComponent(page);	  	api.postWithEditToken({ format: 'json', action: 'delete', title: page, reason: reason, bot: true }).then(function(d) { mw.notify('Successfully deleted ' + page); logger.log('Successfully deleted ' + page); var $target = specialPageType === 3 ? $link.parent.parent.parent : $link.parent; $target.remove; if (cur === count) { reset; }		}, function(_, e) { mw.notify('Failed to delete deleted ' + page + ": " + e.error.info, { type: "warn" }); logger.warn('Failed to delete deleted ' + page + ": " + e.error.info); });	}	importArticle({ type: 'script', article: 'u:dev:MediaWiki:I18n-js/code.js' });	mw.hook('dev.i18n').add(function(i18n) { $.when( 			i18n.loadMessages('MultipleFileDelete'),			mw.loader.using('mediawiki.api')		).then(preload); }); })(this.jQuery, this.mediaWiki); /**/ mw.loader.using('mediawiki.api', function {    if ( window.MassRenameLoaded || !/sysop|wiki_guardian|content-moderator|bot|bot-global|autoconfirmed|emailconfirmed|wiki-representative|global-discussions-moderator|content-volunteer|wiki-specialist|soap/.test(mw.config.get('wgUserGroups').join) ) {       return;    }    window.MassRenameLoaded = true;    var i18n,        placement,        renameModal,        preloads = 3,        paused = false;    function formHtml  {        return $(' ', { 'class': 'WikiaForm' }).append( $(' ').append(               $(' ', { text: i18n.msg('instructions').plain }),               $(' ', {                    text: i18n.msg('instructions2').plain }),               $(' ', {                    'for': 'redirect-check', text: i18n.msg('redirect').plain }).append( $(' ', {                       type: 'checkbox',                        id: 'redirect-check'                    }) ),               $(' '),                $(' ', {                    'for': 'custom-summary', text: i18n.msg('custom-summary').plain }).append( $(' ', {					   id: 'custom-summary'					}) ),               $(' ', {                    id: 'text-rename', placeholder: 'old_name new_name' }),               $(' ', {                    id: 'text-error-output', text: i18n.msg('outputInitial').plain, append: ' ' })           )        ).prop('outerHTML');    }    function preload  {        if (--preloads === 0) {            placement = window.dev.placement.loader;            window.dev.i18n.loadMessages('MassRename').then(init);        }    }    function init (i18nData) {        i18n = i18nData;        placement.script('MassRename');        $(placement.element('tools'))[placement.type('prepend')]( $('').append(               $('', { id: 't-mr', text: i18n.msg('title').plain, click: click })           )        );    }    function click  {        if (renameModal) {            renameModal.show;            return;        }        renameModal = new window.dev.modal.Modal({ content: formHtml, id: 'form-mass-rename', size: 'medium', title: i18n.msg('title').escape, buttons: [ {                   id: 'mr1-start', text: i18n.msg('initiate').escape, primary: true, event: 'start' },               {                    id: 'mr1-pause', text: i18n.msg('pause').escape, primary: true, event: 'pause', disabled: true },               {                    text: i18n.msg('close').escape, event: 'close' }           ],            events: { pause: pause, start: start }       });        renameModal.create;        renameModal.show;    }    function pause  {        paused = true;        document.getElementById('mr1-pause').setAttribute('disabled', );        document.getElementById('mr1-start').removeAttribute('disabled');    }    function start  {        paused = false;        document.getElementById('mr1-start').setAttribute('disabled', );        document.getElementById('mr1-pause').removeAttribute('disabled');        process;    }    function process  {        if (paused) {            return;        }        var txt = document.getElementById('text-rename'),            pages = txt.value.split('\n'),            page = pages[0];        if (!page) {            $('#text-error-output').append( i18n.msg('finished').escape + ' ' +               i18n.msg('nothingLeftToDo').escape + ' '           );            pause;        } else {            rename(page);        }        pages = pages.slice(1, pages.length);        txt.value = pages.join('\n');    }    function rename (name) {        if (name.split(' ').length !== 2) {            $('#text-error-output').append(i18n.msg('invalidInput', name).escape + ' ');        } else {            var oldName = name.split(' ')[0],                newName = name.split(' ')[1],                config = {                    action: 'move',                    from: oldName.replace('_', ' '),                    to: newName.replace('_', ' '),                    noredirect: '',                    reason:                    	($('#custom-summary')[0].value.length > 0 && $('#custom-summary')[0].value) ||                        window.massRenameSummary ||                        i18n.inContentLang.msg('summary').plain, bot: true, token: mw.user.tokens.get('csrfToken') };           if (document.getElementById('redirect-check').checked) { delete config.noredirect; }           new mw.Api.post(config) .done(function (d) {               if (!d.error) {                    console.log(i18n.msg('renameDone', oldName, newName).plain);                } else {                    console.error(i18n.msg('renameFail', oldName, newName).escape + ': ' + d.error.code);                    $('#text-error-output').append(i18n.msg('renameFail', oldName, newName).escape + ': ' + d.error.code + ' ');                }            }) .fail(function (error) {               console.error(i18n.msg('renameFail', oldName, newName).plain + ': ' + error);                $('#text-error-output').append(i18n.msg('renameFail2', oldName, newName).escape + ' ');            }); }       setTimeout(process, window.massRenameDelay || 1000); }   mw.hook('dev.i18n').add(preload); mw.hook('dev.modal').add(preload); mw.hook('dev.placement').add(preload); importArticles(       {            type: 'script',            articles: [                'u:dev:MediaWiki:I18n-js/code.js',                'u:dev:MediaWiki:Modal.js',                'u:dev:MediaWiki:Placement.js'            ]        },        {            type: 'style',            articles: ['u:dev:MediaWiki:MassRename.css']        }    ); }); /**/ (function { var config = mw.config.get([       'wgCanonicalSpecialPageName',        'wgContentLanguage',        'wgUserGroups',        'wgUserLanguage'    ]); if (       !(/DoubleRedirects|BrokenRedirects/g.test(config.wgCanonicalSpecialPageName)) ||        window.RedirectManagementLoaded ||        ( !(/sysop|autoconfirmed|emailconfirmed|content-moderator|content-volunteer|wiki-specialist|wiki-representative|soap/.test(config.wgUserGroups)) && config.wgCanonicalSpecialPageName === 'BrokenRedirects' )   ) {        return; }   window.RedirectManagementLoaded = true; if (!window.dev || !window.dev.i18n) { // Importing I18n-js library importArticle({           type: 'script',            article: 'u:dev:MediaWiki:I18n-js/code.js'        }); }   var RedirectManagement = { init: function(i18n) { this.i18n = i18n; this.api = new mw.Api; this.double = config.wgCanonicalSpecialPageName === 'DoubleRedirects'; this.addButton; },       onClick: function { var summary = window.RedirectManagementSummary || this.i18n.inContentLang.msg(this.double ? 'editSummary' : 'deleteReason').plain; $('.special > li').each($.proxy(function(_, el) { var children = $(el).children; if (children.length !== 4) { // Already resolved return; }               var page = $(children[0]).text, newpage = $(children[3]).text, reason = summary .replace(/\$1/g, page) .replace(/\$2/g, newpage); this.api.postWithEditToken($.extend({ title: page, watchlist: 'nochange', bot: true }, this.double ? {                   action: 'edit', text: '#REDIRECT ' + newpage + '', summary: reason, minor: true, bot: true } : {                   action: 'delete', reason: reason })).done($.proxy(function(d) { if (d.error) { console.error(this.i18nPrefix('error', page) + ': ' + d.error.code); } else { console.info(this.i18nPrefix('success', page)); }               }, this)) .fail($.proxy(function { console.error(this.i18nPrefix('error', page)); }, this)); }, this)); setTimeout(function {               location.reload;            }, 15000); },       i18nPrefix: function(k, param) { return this.i18n.msg([k + (this.double ? 'Double' : 'Broken')], param).plain; },       addButton: function { if (window.RedirectManagementSitewide) { $('.mw-spcontent p').first.append(                   $(' ').append( $('', {                           'class': 'wds-button',                            style: 'cursor: pointer;',                            id: 'btn-resolve-redirects',                            text: this.msg('button')                        }) )               );            } else { $('.page-header__contribution-buttons, .page-header__actions').append(                   $('', { 'class': 'wds-button', id: 'btn-resolve-redirects', title: this.msg('button'), text: this.msg('button') })               );            }            $('#btn-resolve-redirects').click($.proxy(this.onClick, this)); },       msg: function(name) { return this.i18n.msg(name).plain; }   };    mw.loader.using([        'mediawiki.api',        'mediawiki.user'    ], function {        mw.hook('dev.i18n').add(function(i18no) { i18no.loadMessages('RedirectManagement').done(               $.proxy(RedirectManagement.init, RedirectManagement)            ); });   }); }); /**/
 * (function (module, window, $, mw) {