User:StrawberryMaster/global.js

/** * This file loads for myself. * For skin specific variants see User:StrawberryMaster/monobook.js and User:StrawberryMaster/wikia.js * for monobook and oasis respectively * * Please test any changes made to this file. * Jshint  can catch syntax errors to help testing. * Alternatively, Wikia's code editor has jshint embedded to make life extra simple. * * The scripts here follow Wikia JS guidelines or MediaWiki coding standards where the Wikia * guidelines do not specify: * -  * -  * * The scripts have extremely high usage across Wikia, please do not deploy without * extensive testing. Be aware that these scripts must be ES3 compliant due to the * minifier used by ResourceLoader. * * The majority of the scripts here are for personal use as they modify parts of the Oasis/Monobook skin violating Wikia's Terms of Use. * * Some of the scripts here were taken from: Iynque, Dorumin, Slyst, Cheeseskates and Cqm, alongside GitHub and the Dev Wiki. * * Note: Update global.js version at the end of the page. As of February 22, 2017, it is version 63. */ /* %|global|% mw, wgServer, wgScriptPath, wgPageName, wgArticleId, wgAction, importArticles:true, href:true, link:true, specialpage

/* %|jshint|% bitwise:true, browser:true, camelcase:true, curly:false, devel:true, eqeqeq:true, es5:true, forin:true, immed:true, jquery:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, onevar:false, plusplus:true, quotmark:single, undef:true, unused:false, strict:true, trailing:true asi:true, boss:true, debug:true, eqnull:true, evil:true, expr:true, lastsemic:true, loopfunc:true, moz:true, proto:true, scripturl:true

/* Adds an 'AJAX UNDO' link next into the undo link on page histories/diff pages. * Something I found on Dorumin's global.js.  * See w:c:dev:AjaxUndo (stable?) for info & attribution. */ (function($) { function render(input) {    return $("").text("AJAX Undo").attr("href", "#").click(function { var target = $(this); var unmd = /&undo=([^&]*)/.exec(input)[1]; var requestUrl; var gurl = wgServer + wgScriptPath + "/api.php?action=query&prop=info|revisions&intoken=edit&titles=" + encodeURIComponent(wgPageName) + "&format=json"; var d = $("#mw-diff-ntitle2 .mw-userlink").html || (target.closest("li").find(".mw-userlink").html || "nil"); var encodedValue = prompt("Undo summary", "Undo revision " + unmd + " by " + d + " (talk)"); if (null !== encodedValue) { if (!encodedValue) { encodedValue = "Undo revision " + unmd + " by " + d + " (talk)"; }       target.html(' '); $.getJSON(gurl, function(d) {         requestUrl = d.query.pages[wgArticleId].edittoken;          $.ajax({ url : wgScriptPath + "/api.php?", data : "action=edit&format=json&title=" + encodeURIComponent(wgPageName) + "&undo=" + encodeURIComponent(unmd) + "&bot=1&summary=" + encodeURIComponent(encodedValue) + "&token=" + encodeURIComponent(requestUrl), dataType : "json", type : "POST", success : function(data) { if (data.edit && "Success" === data.edit.result) { target.text("(undone)"); } else { if (data.error && "undofailure" === data.error.code) { target.text("(error)"); alert(data.error.info); } else { target.text("(error)"); alert("Error: Unknown result from API."); }             }            },            error : function { target.text("(error)"); }         });        });      }    });  }  $(window).click(function(event) { var $link = $(event.target); if ($.find.matchesSelector($link[0], '#quickdiff-modal a[data-action="undo"]')) { event.preventDefault; var match = $link.attr("href"); event = /&undo=([^&]*)/.exec(match)[1]; match = /\/wiki\/([^?]*)/.exec(match)[1]; var unmd = mw.user.tokens.get("editToken"); var nil = $("#quickdiff-modal .diff-ntitle .mw-userlink").html || "nil"; var encodedValue = prompt("Undo summary", "Undo revision " + event + " by " + nil + " (talk)"); if (null !== encodedValue) { if (!encodedValue) { encodedValue = "Undo revision " + nil + " by " + nil + " (talk)"; }       $link.html(' '); $.ajax({         url : wgScriptPath + "/api.php?",          data : "action=edit&format=json&title=" + encodeURIComponent(match) + "&undo=" + encodeURIComponent(event) + "&bot=1&summary=" + encodeURIComponent(encodedValue) + "&token=" + encodeURIComponent(unmd),          dataType : "json",          type : "POST",          success : function(data) {            if (data.edit && "Success" === data.edit.result) {              $link.text("(undone)");            } else {              if (data.error && "undofailure" === data.error.code) {                $link.text("(error)");                alert(data.error.info);              } else {                $link.text("(error)");                alert("Error: Unknown result from API.");              }            }          },          error : function {            $link.text("(error)");          }        }); }   }  });  if ($(".mw-history-undo > a").length && "history" === wgAction) {    $(".mw-history-undo > a").each(function { var result = $(this).attr("href"); result = render(result); $(this).replaceWith(result); }); } else {    if ($("table.diff").length && "undefined" !== typeof $.getUrlVar("diff")) {      var target = $("table.diff").find(".diff-ntitle > #mw-diff-ntitle1 a:last");      var result = target.attr("href");      result = render(result);      target.replaceWith(result);    }  } })(this.jQuery, this.mediaWiki); /////////////////////////////////////////////////////////////////////////////// /**/ ///————————————————————— Minor Direct JavaScript code ———————————————————————/// /**/ /////////////////////////////////////////////////////////////////////////////// /* header credit to Cheeseskates */

/* Unchecks redirects when moving files */ if (c.wgPageName.indexOf("Special:MovePage/File:") !== -1) $('#wpLeaveRedirect').removeAttr('checked'); /* Show abuse log entries in Special:Log/newusers */ if ("Special:Log/newusers".indexOf(c.wgPageName) !== -1) { $('.mw-logline-newusers').each(function {		$(this).find('.mw-usertoollinks').find('a:last').after(' | abuse');	}); } /* Revision delete */ if (c.wgAction == 'revisiondelete' || c.wgCanonicalSpecialPageName == 'Revisiondelete') { $('#wpHidePrimary,#wpHideComment,#wpHideUser').attr('checked','checked'); $('#wpReason').val('spam'); } /* Thread history return to thread */ if (c.wgCanonicalNamespace == "Thread" && c.wgAction == "history") $('.SortingBar').after('Back to thread'); /* Special:WhatLinksHere on redirect page */ if ($('#WikiaPageHeader h2').text.indexOf('Redirected from') != -1) $('#WikiaPageHeader h2').append(' (links) (history)'); /* Always go to IP contributions, not userpage */ if (c.wgNamespaceNumber == 2 && c.wgTitle.split('.').length == 4) location.replace(articlePath + 'Special:Contributions/' + c.wgTitle);

/* Auto-submit bugged pages for deletion */ if (c.wgAction == "delete" && $('#ca-edit').text.trim == "Create") $('#mw-img-deleteconfirm,#deleteconfirm').submit; /* Create dupe file list button */ if (c.skin === 'monobook') { mw.util.addPortletLink('p-tb', '/index.php?title=Special:BlankPage&blankspecial=listdupefiles', 'List dupe files', 't-ld'); } else { $('#my-tools-menu').prepend(' List dupe files</a></li>'); } // Add edit links on Special:WhatLinksHere if (mw.config.get("wgCanonicalSpecialPageName") === "Whatlinkshere") { $("#mw-whatlinkshere-list > li").each(function(dataAndEvents, context) {   var fontSize = $(context).children("a").attr("href") + "?action=edit";    $(context).find(".mw-whatlinkshere-tools > a:last-child").after(" | ", $("</a>").attr("href", fontSize).text("edit"));  }); }

// Add separate list of uncreated categories on Special:Categories if (mw.config.get("wgCanonicalSpecialPageName") === "Categories") { var $newCats = $(" ").css("float", "right").text("Uncreated categories:"); var $newCatsList = $("<ul></ul>").appendTo($newCats); $(".mw-spcontent > ul").before($newCats); $(".mw-spcontent > ul > li").has(".newcategory").clone.appendTo($newCatsList); }

// Disable 5 sec. edit save delay GlobalTriggers.bind("WikiaEditorReady", function(point) { if (point.controls) {    point.controls.editform.off("submit").on("submit", function { point.setState(3); }); } });

// Display user's registration date in masthead $(function { mw.loader.using("mediawiki.api").then(function { function displayWindowSize { $(".globaledit-label").html($(".globaledit-label").html + " " + textStatus); }   var textStatus; var load; (new mw.Api).get({     action : "query",      list : "users",      ususers : $("#UserProfileMasthead h1").text,      usprop : "registration"    }).done(function(client) {      if (client.query.users) {        textStatus = (new Date(client.query.users[0].registration)).toLocaleString;        if (load) {          displayWindowSize;        }      }    }); var poll = setInterval(function {     if ($(".globaledit-label").length > 0) {        clearInterval(poll);        load = true;        if (textStatus) {          displayWindowSize;        }      }    }, 100); }); });

/////////////////////////////////////////////////////////////////////////////// //———————————————————————————————————————————————————————————————————————————— // Script Configurations /* All of the confgurations below contribute to how the JavaScript imports function. It only works with imports like this, not direct JavaScript code, hence why it is in between here and the mentioned section above. */ //————————————————————————————————————————————————————————————————————————————

/////////////////////////////////////////////////////////////////////////////// /* again, header credit goes to Cheeseskates */

/* Auto updating recent changes opt-in. * Something I found on Dorumin's global.js. <c:User:Dorumin/global.js> * See w:c:dev:AjaxRC for info & attribution. */ window.ajaxIndicator = 'http://vignette2.wikia.nocookie.net/dev/images/8/82/Facebook_throbber.gif'; window.ajaxRefresh = 1E3; window.AjaxRCRefreshText = 'Auto-refresh'; window.AjaxRCRefreshHoverText = 'Automatically refresh the page'; window.ajaxPages = [

/// // ——————————————————— Temporary Watchlist (for vandals) ———————————————————— / /// //Add below when necessary. /*———————————————————————————————————————————————————————————————————————————————— ———————————————————————————————————————————————————————————————————————————————— /* ////* English (en) *//// "Special:WikiActivity", "Special:RecentChanges", "Special:Watchlist", "Special:AbuseLog", "Special:Log", "Special:Log/upload", "Special:Images", "Special:Videos", "Special:Newwikis", "Report:Vandalism", "Report:Spam", "Report:User profile headers", "Report:Users and IPs needing checked", ////* German (Deutsch) (de) *//// "Spezial:WikiActivity", "Spezial:Letzte_Änderungen", "Spezial:Logbuch", ////* Spanish (Español) (es) *//// "Especial:WikiActivity", "Especial:CambiosRecientes", "Especial:Registro", ////* Suomi (Finnish) (fi) *//// "Toiminnot:WikiActivity", "Toiminnot:Tuoreet_muutokset", "Toiminnot:Loki", ////* French (Français) (fr) *//// "Spécial:WikiActivity", "Spécial:Modifications_récentes", "Spécial:Journal", ////* Italian (Italiano) (it) *//// "Speciale:WikiActivity", "Speciale:UltimeModifiche", "Speciale:Registri", ////* Japanese (日本語) (ja) *//// "特別:WikiActivity", "特別:最近の更新", "特別:ログ", ////* Korean (한국어) (ko) *//// "특수기능:위키활동내역", "특수기능:최근바뀜", "특수기능:기록", ////* Nederlands (nl) *//// "Speciaal:WikiActivity", "Speciaal:RecenteWijzigingen", "Speciaal:Logboeken", ////* Polish (Polski) (pl) *//// "Specjalna:Aktywność_na_wiki", "Specjalna:Ostatnie_zmiany", "Specjalna:Rejestr", ////* Brazilian Portuguese (Português do Brasil) (pt-br) *//// "Especial:Mudanças_recentes", ////* Russian (Русский) (ru) *//// "Служебная:WikiActivity", "Служебная:RecentChanges", "Служебная:Log", ////* Vietnamese (Tiếng Việt) (vi) *//// "Đặc_biệt:Hoạt_động_wiki", "Đặc_biệt:Thay_đổi_gần_đây", "Đặc_biệt:Nhật_trình", ////* Chinese (中文) (zh) *//// "Special:最近更改", "Special:日志", ////* Chinese (Taiwan) ( 中文(台灣) ) (zh-tw) *//// "特殊:WikiActivity", "特殊:近期變動", "特殊:日誌", ////* Afrikaans (af) *//// "Spesiaal:WikiActivity", "Spesiaal:Onlangse_wysigings", "Spesiaal:Logboek", ////* Arabic (العرب) (ar) *//// "خاص:WikiActivity", "خاص:أحدث_التغييرات", "خاص:سجل", ////* Belorussian (Беларуская) (be) *//// "Адмысловае:WikiActivity", "Адмысловае:RecentChanges", "Адмысловае:Log", ////* Bulgarian (Български) (bg) *//// "Специални:WikiActivity", "Специални:Последни_промени", "Специални:Дневници", ////* Catalan (Català) (ca) *//// "Especial:Canvis_recents", "Especial:Registre", ////* Greek (Ελληνικά) (el) *//// "Ειδικό:WikiActivity", "Ειδικό:ΠρόσφατεςΑλλαγές", "Ειδικό:Μητρώο", ////* Estonia (Eesti) (et) *//// "Eri:WikiActivity", "Eri:Viimased_muudatused", "Eri:Logid", ////* Farsi (فارسی) (fa) *//// "ویژه:WikiActivity", "ویژه:تغییرات_اخیر", "ویژه:سیاهه‌ها", ////* Galician (Galego) (gl) *//// "Especial:Cambios_recentes", "Especial:Rexistros", ////* Hungarian (Magyar) (hu) *//// "Speciális:WikiActivity", "Speciális:Friss_változtatások", "Speciális:Rendszernaplók", ////* Indonesian (Bahasa Indonesia) (id) *//// "Istimewa:WikiActivity", "Istimewa:Perubahan_terbaru", "Istimewa:Catatan", ////* Limburg (Limburgs in Dutch) (li) *//// /* Note: Wikiactivity is the same as the Nederlands' WikiActivity page, so it is not included. */ "Speciaal:Lètste_verangeringe", "Speciaal:Logbeuk", ////* Lithuanian (Lietuvių) (lt) *//// "Specialus:WikiActivity", "Specialus:Naujausi_keitimai", "Specialus:Sąrašas", ////* Norwegian Bokmål ( ‪Norsk (bokmål) ‬) (no) *//// "Spesial:WikiActivity", "Spesial:Siste_endringer", "Spesial:Logg", ////* Occitan (oc) *//// "Especial:Darrièrs_cambiaments", "Especial:Jornal", ////* Romanian (Română) (ro) *//// "Special:Schimbări_recente", "Special:Jurnal", ////* Serbian / serbian (Српски / Srpski) (sr) *//// "Посебно:WikiActivity", "Посебно:СкорашњеИзмене", "Посебно:Извештај", ////* Ukrainian (Українська) (uk) *//// "Спеціальна:WikiActivity", "Спеціальна:RecentChanges", "Спеціальна:Log" //// // —————————————————————————— End AjaxRC Section ———————————————————————————— // ////
 * // Interlanguage Wiki Pages //                           |
 * Note 1: The order is according to the Language Brigade Wiki.                    |
 * Note 2: The first language name is the English word. The second language        |
 * name is the language's word/original word. The two letters after are the        |
 * abbreviations for the second language names.                                    |
 * 1. Always add the language names in this order: English word -> Original ↓      |
 * -> Abbreviation (e.g. fr for french)                                            |
 * 2. Always add the page names in this order: WikiActivity -> RecentChanges -> Log |
 * Note 3: The Chinese and Romanian's WikiActivity are the same as the English     |
 * WikiActivity page, and the Brazilian Portuguese (including their Log page),     |
 * Catalan, Galician, and occitan's WikiActivity are the same as the Spanish       |
 * WikiActivity page. Because of this, They are not added to prevent duplication.  |
 * WikiActivity page, and the Brazilian Portuguese (including their Log page),     |
 * Catalan, Galician, and occitan's WikiActivity are the same as the Spanish       |
 * WikiActivity page. Because of this, They are not added to prevent duplication.  |

];

/* Create userpage script. * See w:c:dev:QuickCreateUserPage for info & attribution. */

window.qtUserPageTemplate = ''; window.qtEnableUserPageOverwrite = true;

/* Vector skin configuration. * See w:c:dev:Pseudo-Vector JS for info & attribution. */ window.pseudoVector = { loadCss: true, addReadTab: true, addContributionsTab: true, disableWatchIcon: false, newDiffStyle: true };

/* Removes backlinks from pages. * See w:c:dev:Linksweeper for info & attirbution. */ window.linkSweepConfirmation = true; window.LinkSweeperDelay = 1000;

/* Places "QuickToolsv2" button on the "My Tools" section. * Something I found on Zmario's global.js. <c:User:Zmario/global.js> * See w:c:dev:QuickToolsv2 for info & attribution. */ window.QuickToolsAdvancedtop = false;

///////////////////////////////////////////////////////////////////////////////

//———————————————————————————————————————————————————————————————————————————— // Imports /* Imports minify the rest of the JavaScript or CSS code and combines multiple HTTP requests into a single data transfer, making it save space and load faster than direct code. It is recommended to import this way. */ //———————————————————————————————————————————————————————————————————————————— /////////////////////////////////////////////////////////////////////////////// /* again, header credit goes to Cheeseskates */

//--- /* importscriptURL */ //--- // Advisor - Helps with editing suggestions such as whitespace removal, headings nest, etc. importScriptURI("https://en.wikipedia.org/w/index.php?title=User:Cameltrader/Advisor.js&action=raw&ctype=text/javascript"); // AutoFormatter - Formats a page automatically to fix common mistakes in wiki-markup importScriptURI("https://de.wikipedia.org/w/index.php?title=Benutzer:TMg/autoFormatter.js&action=raw&ctype=text/javascript"); // AutoLink - Parses wikilinks, [external links], {templates}, and URLs into clickable links importScriptURI("https://en.wikipedia.org/w/index.php?title=User:Lenore/autolink.js&action=raw&ctype=text/javascript"); //--- /* importArticles */ //---

$(function {   importArticles({ type: 'script', articles: [ // ...           'u:dev:MediaWiki:AjaxRC/code.js', // Special:RecentChanges live update 'u:dev:MediaWiki:AjaxBatchDelete/code.2.js', // Batch delete 'u:dev:MediaWiki:AjaxBatchUndelete.js', 'u:dev:MediaWiki:AjaxBlock/code.js', // Blocks users quickly 'u:dev:MediaWiki:AjaxPatrol/code.js', 'u:dev:MediaWiki:ArchiveTool/code.js', 'u:dev:MediaWiki:DisplayClock/code.js', // Show UTC clock 'u:dev:MediaWiki:ExpandGlobalNavDropdownsOnHover/code.js', // 'u:dev:MediaWiki:FastDelete/beta.js', // ↳ disabled while another code is here (below) 'u:dev:MediaWiki:Linksweeper/code.js', 'u:dev:MediaWiki:MassBlock/code.js', 'u:dev:MediaWiki:MassCategorization/code.js', 'u:dev:MediaWiki:MassProtect/code.js', 'u:dev:MediaWiki:MassRename/code.js', 'u:dev:MediaWiki:MassUserRights/code.js', 'u:dev:MediaWiki:Pseudo-Vector.js', 'u:dev:MediaWiki:QuickCreateUserPage/code.js', 'u:dev:Mediawiki:QuickToolsv2/code.js', // Quick tools // ↳ Not used very often; Wikimarks handles a lot of this anyway 'u:dev:MediaWiki:ThreadIndicator/code.js', // Indicates thread stats // 'u:dev:MediaWiki:WHAM/code.2.js' // Quick tools 'u:dev:User:Dorumin/wikia.js' // betas here // ...       ]	}); });

// these have to be defined here for reasons I don't understand // Monch tells me IFFE's can mess with the run order of js but neither of us know why or how. // #confused

function importScriptPage( p, w ) { var s = document.createElement( 'script' ); s.type = 'text/javascript'; s.src = 'http://' + w + '.wikia.com/index.php?title=' + p.replace( / /g, '_' ) + '&action=raw&ctype=text/javascript&maxage=0&smaxage=0'; document.getElementsByTagName( 'body' )[0].appendChild( s ); } function importScript( p ) { var s = document.createElement( 'script' ); s.type = 'text/javascript'; s.src = '/index.php?title=' + p.replace( / /g, '_' ) + '&action=raw&ctype=text/javascript&maxage=0&smaxage=0'; document.getElementsByTagName( 'body' )[0].appendChild( s ); }

( function ( $, mw, importArticles ) {   'use strict';    var self = {        /**         * @desc Loads functions conditionally         */        init: function  {            var config = mw.config.get( [ 'wgCanonicalSpecialPageName', 'wgNamespaceNumber', 'wgTitle' ] );           self.imports;            if ( $( '#UserProfileMasthead' ).length ) {                self.mastheadEditcount;            }            if ( config.wgCanonicalSpecialPageName === 'Movepage' && ( /File/ ).test( config.wgTitle ) ) {               self.uncheckFileRedirects;            }        },        /**         * @desc Defines variables for imported scripts and import said scripts         *         * @author Cqm         */        imports: function  {            var scripts = [],                config = mw.config.get( [ 'wgAction', 'wgCityId', 'wgCanonicalSpecialPageName', 'wgNamespaceNumber' ] );            /**             * Create an array of scripts to be imported conditionally             * See imported pages for documentation             * @todo Find a way to turn these on/off from console or something             */            // always load these            scripts.push( // CSS testing input // 'u:dev:PortableCSSPad/code.js', // Add CSS injector to toolbar // ↳ Not necessary with modern browser debug/developer tools // Customisable On The Wiki tab // 'u:dev:Wikimarks/code.js', // Fix search for Special pages // 'u:rs:User:Cqm/specialsearchfix.js' );           if ( config.wgAction === 'view' ) {                scripts.push( // Icon to link to header tags // 'u:dev:HeaderLinks/code.js' );               if ( $( '#ca-delete' ).length ) {                    // Fast Delete buttons                    // scripts.push( 'u:dev:FastDelete/code.js' );                    scripts.push( 'u:dev:FastDelete/beta.js' );                }                if ( config.wgNamespaceNumber === 6 ) {                    scripts.push( // Changes file pages back to original styling // @todo fix this up at some point // 'u:rs:User:Cqm/oldfilepages.js' );               }                if ( [ 'Allpages', 'Prefixindex' ].indexOf( config.wgCanonicalSpecialPageName ) > 1 ) {                    scripts.push( // Adds a hide redirect button to AllPages & PrefixIndex // 'u:dev:AllPagesHideRedirect/code.js' );               }                if ( config.wgAction === 'history' || $( '#mw-history-searchform' ).length ) {                    scripts.push( // Add an undo link to page diffs and histories // 'u:dev:AjaxUndo/code.js' );               }            }            /**             * Import the filled arrays             */            importArticles( { type: 'script', articles: scripts } );        },        /**         * @desc Adds a link to Special:Editcount on the user profile masthead         *         * @author Matthew2602 <http://c.wikia.com/User:Matthew2602>         * @author Cqm         */         /*        mastheadEditcount: function  {            var config = mw.config.get( [ 'wgCanonicalNamespace', 'wgTitle' ] ),               user = config.wgTitle,                link;            if ( config.wgCanonicalNamespace === 'Special' ) {                user = user.split( '/' )[1];            }            link = $( '' )                .attr( { href: '/wiki/Special:Editcount/' + user, title: 'Special:Editcount' } )               .text( $( '#UserProfileMasthead .tally em' ).text );           $( '#UserProfileMasthead .tally em' ).html( link );        },        */        /**         * @desc Uncheck file redirects on Special:MovePage         *         * File redirects are normally bad because they will create false positives on Special:WantedFiles         * In very rare cases it's reasonable to have them, but those are so rare it's better to have this as         * the default behaviour.         *         * @author Cqm         */        uncheckFileRedirects: function  {            $( '#wpLeaveRedirect' ).removeAttr( 'checked' );        },    };    $( self.init ); }( this.jQuery, this.mediaWiki, this.importArticles ) );

/* - END of User:StrawberryMaster/global.js */ /* Header slightly modified from Iynque. <w:c:User:Iynque> */ console.info('Loaded User:StrawberryMaster/global.js version 63');