User:Blupo/wikia.js

var wordmarks = [ "https://vignette.wikia.nocookie.net/swordburst2/images/8/89/Wiki-wordmark.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/a/ab/Wiki-wordmark-arcadia1.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/0/00/Wiki-wordmark-arcadia2.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/3/3b/Wiki-wordmark-pvp1.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/1/1f/Wiki-wordmark-pvp2.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/5/59/Wiki-wordmark-pvp3.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/d/db/Wiki-wordmark-virhst1.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/1/1d/Wiki-wordmark-virhst2.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/a/ad/Wiki-wordmark-virhst3.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/0/08/Wiki-wordmark-virhst4.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/5/58/Wiki-wordmark-virhst5.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/9/9e/Wiki-wordmark-virhst6.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/0/0f/Wiki-wordmark-redveil1.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/b/ba/Wiki-wordmark-redveil2.png/revision/latest", "https://vignette.wikia.nocookie.net/swordburst2/images/a/a6/Wiki-wordmark-redveil3.png/revision/latest", ];

$(".wds-community-header__wordmark img").attr("src", wordmarks[Math.floor(Math.random * wordmarks.length)]);

window.abuseLog_autoRefresh = false; window.abuseLog_autoRefreshInterval = 30; window.abuseLog_entries = 10; window.abuseLog_showRCFirst = false; window.abuseLog_checkIfPagesExist = true;

// abuse log uses date and time // https://github.com/Wikia/app/tree/dev/languages/messages for date formats var timeFormats = { "ISO 8601": "xnY-xnm-xnd\"T\"xnH:xni:xns", "de": { "dmyt": "j. M Y, H:i", "dmyts": "j. M Y, H:i:s", "dmy": "H:i, j F Y", "ymd": "H:i, Y F j", },   "en": { "mdy": "H:i, F j, Y", "dmy": "H:i, j F Y", "ymd": "H:i, Y F j", "ISO 8601": "xnY-xnm-xnd\"T\"xnH:xni:xns", },   "es": { "dmy": "H:i j M Y", },   "fr": { "mdy": "F j, Y à H:i", "dmy": "j F Y à H:i", "ymd": "Y F j à H:i", },   "it": { "mdy": "H:i, M j, Y", "dmy": "H:i, j M Y", "ymd": "H:i, Y M j", },   "ja": { "ja": "Y年n月j日 (D) H:i", "nengo": "xtY年n月j日 (D) H:i", },   "pl": { "mdy": "H:i, M j, Y", "dmy": "H:i, j M Y", "ymd": "H:i, Y M j", },   "pt-br": { "dmy": "H\"h\"i\"min\" \"de\" j \"de\" F \"de\" Y"   }, "ru": { "mdy": "H:i, xg j, Y", "dmy": "H:i, j xg Y", "ymd": "H:i, Y xg j", "ISO 8601": "xnY-xnm-xnd\"T\"xnH:xni:xns" },   "zh": { fallback: "zh-hans" },   "zh-hans": { "zh": "Y年n月j日 (D) H:i", },   "zh-tw": { "zh": "Y年n月j日 (D) H:i", "minguo": "xoY年n月j日 (D) H:i", "minguo shorttext": "民xoY年n月j日 (D) H:i", "minguo text": "民國xoY年n月j日 (D) H:i", "minguo fulltext": "中華民國xoY年n月j日 (D) H:i", "CNS 7648": "\"R.O.C.\" xoY-m-d (D) H:i", "CNS 7648 compact": "\"ROC\" xoY-m-d (D) H:i", } };

// credit to the authors of AbuseLogRC // todo: cache checking, proper date formatting (function {    "use strict";    if (window.abuseLogActive) {        console.log("AbuseLog: Already running");        return;    }    window.abuseLogActive = true;    var userConfig = mw.user.options.get([ "date", "language" ]);   var mwData = mw.config.get([ "wgCanonicalSpecialPageName", "wgUserGroups", "wgUserLanguage", "wgDefaultDateFormat", ]);   var userGroups = mwData.wgUserGroups.join(" ");    if (!/user/.test(userGroups)) { return }    if (mwData.wgCanonicalSpecialPageName != "Recentchanges") { return }    var timezoneOffset = new Date.getTimezoneOffset;    var timeFormatString;    var config = {        "autoRefreshInterval": window.abuseLog_autoRefreshInterval || 60,        "entries": window.abuseLog_entries || 10,        "checkIfPagesExist": (typeof window.abuseLog_checkIfPagesExist !== "undefined") ? window.abuseLog_checkIfPagesExist : false,        "autoRefresh": (typeof window.abuseLog_autoRefresh !== "undefined") ? window.abuseLog_autoRefresh : false,        "urgencyIntervals" : window.abuseLog_urgencyIntervals || [2, 12, 24],        "useFormattedTimes" : false,    };    config.urgencyIntervals.sort(function(a, b) { return a - b });    var isSysop = /sysop/.test(userGroups);    var itemsSince = null;    var itemIds = []; var refreshTimer = null; var loadLock = false; function sentenceCase(string) { return string.charAt(0).toUpperCase + string.slice(1); }   function clamp(num, min, max) { return num <= min ? min : num >= max ? max : num; }   function getDateFormat(lang, format) { var language = timeFormats[lang]; if (!language) { langaugeForamts = timeFormats.en; } var formatString = language[format]; if (!formatString) { formatString = language[mwData.wgDefaultDateFormat]; } if (!formatString) { if (language.fallback) { formatSring = getDateFormat(langauge.fallback, format); } else { formatString = languages["ISO 8601"]; }       }        return formatString; }   timeFormatString = getDateFormat(userConfig.language, userConfig.date); mw.loader.using(["mediawiki.api", "mediawiki.jqueryMsg"], function {       var Api = new mw.Api;        function apiQuery(data) {            data.action = "query";            data.format = "json";            return Api.get(data);        }        // https://www.mediawiki.org/wiki/Manual:Messages_API#Getting_the_messages_to_the_client        function loadMessages(messages) {            return apiQuery({ meta: "allmessages", ammessages: messages.join("|"), amlang: mwData.wgUserLanguage, }).then(function(data) { $.each(data.query.allmessages, function(i, message) {                   if (message.missing !== "") {                        mw.messages.set(message.name, message["*"]);                    }                }); });       }        var pageExistsCache = {};        function pageExists(name, id) {            var element = $(id);            if (!config.checkIfPagesExist) { return; }            if (typeof pageExistsCache[name] !== "undefined") {                element.addClass(pageExistsCache[name] ? "" : "new");               return;            }            apiQuery({ titles: name }).done(function(response) { if (!response.error) { for (var i in response.query.pages) { var item = response.query.pages[i]; if (item.title == name) { pageExistsCache[name] = item.missing !== ""; element.addClass(pageExistsCache[name] ? "" : "new"); return; }                   }                }            });        }        function urgencyClass(timeDiff) {            for (var i in config.urgencyIntervals) {                var interval = config.urgencyIntervals[i] * 3600 * 1000;                var urgencyLevel = Number(i) + 1;                if (timeDiff <= interval) {                    return "abUrgency" + urgencyLevel;                }            }            return "abNonUrgent";        }        function refreshData{            $('#abLog-list').empty;            $('#abLog-error').hide;            itemIds = [];            itemsSince = null;            loadData;        }        function loadCompleted {            if (config.autoRefresh && !refreshTimer) {                refreshTimer = window.setTimeout(loadData, config.autoRefreshInterval * 1000);            }            $("#ab-lastRefreshed").text("Updated at " + (new Date).toLocaleTimeString); $("#ab-forceRefresh").prop("disabled", false); $("#abLoader").hide; }       function localiseABAction(action) { if (action == "noactions") { return mw.msg("abusefilter-log-noactions"); }           return mw.msg("abusefilter-action-" + action); }       function makeUI { var abInputsTable = " " + " " + " " + " " + " ";           var abTools = " " + " " +               " Turn " + (config.autoRefresh ? "off" : "on") + " auto-refresh | " + " " + (config.checkIfPagesExist ? "Don't check" : "Check") + " if pages exist " + " " +               "" + " | " +               "" + mw.msg("abusefilter") + " | " + "" + mw.msg("abusefilter-topnav-log") + "" + " " +               " " +                " ";            var abFieldset = " " + mw.msg("abusefilter-log-search") + " " + abInputsTable + abTools + " "; var container = " " + abFieldset + " " + mw.msg("abusefilter-log") + "  "; $('#mw-content-text').before(container); }       function loadData { if (loadLock) { return; } else { loadLock = true; } refreshTimer = null; $("#abLoader").show; $("#ab-forceRefresh").prop("disabled", true); var isSysop = /sysop/.test(userGroups); var itemQuery = { "afllimit": config.entries, "afldir": "older", "list": "abuselog", "aflprop": "ids|user|title|action|result|filter|timestamp|hidden" };           if (itemsSince) { itemQuery.itemend = itemsSince; } if (config.user) { itemQuery.afluser = config.user; } if (config.filterId) { itemQuery.aflfilter = config.filterId; } if (config.title) { itemQuery.afltitle = config.title; } apiQuery(itemQuery).done(function(response) {               if (!response.error) {                    if (response.query.abuselog.length > 0) {                        for (var i in response.query.abuselog) {                            var item = response.query.abuselog[i];                            // Remove duplicates which may occur during autorefresh                            if ($.inArray(item.id, itemIds) > -1) { continue; }                            if (itemIds.length >= config.entries) { refreshData; }                            itemIds.push(item.id);                            // Time                            // query timestamps are UTC in ISO format                            var now = new Date,                                then = new Date(item.timestamp),                            // Set time limit for next requests                            itemsSince = item.timestamp; var results = item.result ? item.result.split(",") : ["noactions"]; results = results.map(localiseABAction); var timeStr = "" + then.toLocaleString(mwData.wgUserLanguage) + " "; //"" var userLink = "" + item.user + "</a>"; var userTools = " (" +                               "" + mw.msg("wall-message-wall-shorten") + "</a>" + mw.msg("pipe-separator") +                                "" + mw.msg("contribslink") + "</a>" +                                (isSysop ? mw.msg("pipe-separator") + "" + mw.msg("blocklink") + "</a>)" :                               ""                                ) + ") ";                           var filter = "" + mw.msg("abusefilter-log-detailedentry-local", item.filter_id) +                                "</a>";                            var pageLink = "" +  item.title + "</a>";                            var filterTools = "" + mw.msg("abusefilter-log-detailslink") + "</a>" + mw.msg("pipe-separator") +                                "" + mw.msg("abusefilter-changeslist-examine") + "</a>"; var entry; if (isSysop) { entry = mw.msg("abusefilter-log-detailedentry-meta", timeStr, userLink + " " + userTools, filter, item.action, pageLink, results.join(", "), item.filter, filterTools); } else { entry = mw.msg("abusefilter-log-entry", timeStr, userLink + " " + userTools, item.action, pageLink, results.join(", "), item.filter); }                           $("#abLog-list").append("<li id='abLog-entry'>" + entry + "</li>"); pageExists(item.title, "#entry-" + item.id); }                   } else { $("#abLog-list").append("<li>No results</li>"); }               }                loadCompleted; loadLock = false; });       }        apiQuery({ meta: "siteinfo", siprop: "extensions", }, function(response) { var o = response.query.extensions, found = false; if ($.isArray(o)) { for ( var i = 0; i < o.length && !found; ++i ) { found = o[i].name === "Abuse Filter"; }           }            if (!found) { console.log("AbuseLog: Abuse Filter is not enabled"); return; }       });        loadMessages([ "abusefilter", "abusefilter-log", "abusefilter-topnav-log", "abusefilter-log-search", "abusefilter-log-search-filter", "abusefilter-log-search-title", "abusefilter-log-search-user", "abusefilter-log-entry", "abusefilter-log-detailedentry-meta", "abusefilter-action-block", "abusefilter-action-blockautopromote", "abusefilter-action-degroup", "abusefilter-action-disallow", "abusefilter-action-rangeblock", "abusefilter-action-tag", "abusefilter-action-throttle", "abusefilter-action-warn", "abusefilter-log-noactions", "abusefilter-log-detailedentry-local", "abusefilter-changeslist-examine", "abusefilter-log-detailslink", "wall-message-wall-shorten", "talkpagelinktext", "contribslink", "blocklink", "pipeseparator", "seconds", ]).then(makeUI).then(function { $("#ab-clearInputs").click(function {               config.user = null;                config.filterId = null;                config.title = null;                $("#abInput-userText").text("");                $("#abInput-filterIdText").text("");                $("#abInput-titleText").text("");                $("#abInput-user").prop("value", "");                $("#abInput-filterId").prop("value", "");                $("#abInput-title").prop("value", "");                $("#abInput-autoRefreshInterval").prop("value", "");                $("#abInput-numEntries").prop("value", "");            }); $("#ab-updateInputs").click(function {               var newRefreshInterval = Number(parseInt($("#abInput-autoRefreshInterval").val, 10));                var newEntries = Number(parseInt($("#abInput-numEntries").val, 10));                var user = $("#abInput-user").val;                var filterId = $("#abInput-filterId").val;                var title = $("#abInput-title").val;                newRefreshInterval = (typeof newRefreshInterval == "number") ? newRefreshInterval : config.autoRefreshInterval;                newEntries = (typeof newEntries == "number") ? newEntries : config.entries;                newRefreshInterval = !isNaN(newRefreshInterval) ? newRefreshInterval : config.autoRefreshInterval;                newEntries = !isNaN(newEntries) ? newEntries : config.entries;                config.autoRefreshInterval = (newRefreshInterval >= 5) ? newRefreshInterval : 5; config.entries = clamp(newEntries, 1, 500); config.user = user || null; config.filterId = filterId || null; config.title = title || null; $("#abInput-autoRefreshIntervalText").text("(" + mw.msg("seconds", config.autoRefreshInterval) + ")"); $("#abInput-numEntriesText").text("(" + config.entries + ")"); $("#abInput-userText").text(config.user ? "(" + config.user + ")" : ""); $("#abInput-filterIdText").text(config.filterId ? "(" + config.filterId + ")" : ""); $("#abInput-titleText").text(config.title ? "(" + config.title + ")" : ""); });           $("#ab-checkIfPagesExistToggle").click(function { config.checkIfPagesExist = !config.checkIfPagesExist; $(this).text(config.checkIfPagesExist ? "Don't check" : "Check"); });           $("#ab-autoRefreshToggle").click(function  { config.autoRefresh = !config.autoRefresh; if (config.autoRefresh) { if (!refreshTimer) { refreshTimer = window.setTimeout(loadData, config.autoRefreshInterval * 1000); }               } else { if (refreshTimer) { window.clearTimeout(refreshTimer); refreshTimer = null; }               }                $(this).text(config.autoRefresh ? "off" : "on"); });           $("#ab-forceRefresh").click(refreshData);            }).then(loadData); }); });

// FontPicker // use localstorage instead of cookies (function {   "use strict";    if (window.fontPicker) {        console.log("FontPicker.js: Already loaded");        return;    }    window.fontPicker = true;    const STORAGE_KEY = "SB2_WIKI_FONTPREF";    const FALLBACK_FONTS = "'Helvetica Neue', Helvetica, Arial, sans-serif";    // config    var defaultFontKey = "Helvetica";    var localStorage;    // check if Storage is available    // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Testing_for_availability    function storageAvailable(type) {        try {            var storage = window[type],                x = '__storage_test__';            storage.setItem(x, x);            storage.removeItem(x);            return true;        }        catch(e) {            return e instanceof DOMException && ( // everything except Firefox e.code === 22 || // Firefox e.code === 1014 || // test name field too, because code might not be present // everything except Firefox e.name === 'QuotaExceededError' || // Firefox e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&               // acknowledge QuotaExceededError only if there's something already stored                storage.length !== 0;        }    }    if (storageAvailable('localStorage')) {        localStorage = window.localStorage;    } else {        console.log("FontPicker.js: localStorage is not available");        return;    }    // key: { css: "font name in css", txt: "picker text" }    // if txt is missing it will use css as the display text    var fontOptions = {        Helvetica: { css: "Helvetica", },        Rubik: { css: "Rubik" },        Zekton: { css: "Zekton" },        Dyslexic: { css: "OpenDyslexic", txt: "Dyslexic" },        NGNL: { css: "NGNL", txt: "NGNL (joke)" },        LeviBrush: { css: "Levi Brush", txt: "Levi Brush (joke)" },        Sheikah: { css: "BotW Sheikah", txt: "Sheikah (joke)" }    };    var pageContent = $("#WikiaMainContent"); var pageRail = $("#WikiaRail"); var pickerLabelText = "Select a font: "; var pickerLabel = $("<label for='page-font'> ").text(pickerLabelText); var picker = $("<select id='page-font'> "); function buildFontOption(fontOption) { var fontOptionObj = $(" " + (fontOption.txt || fontOption.css) + " "); fontOptionObj.attr("value", key); picker.append(fontOptionObj); return fontOptionObj; }   function changeFont(key) { var font = fontOptions[key]; if (!font) { var newFontOption = { css: FALLBACK_FONTS, txt: "Unknown font (key is " + key + ")" }; fontOptions[key] = newFontOption; buildFontOption(newFontOption); font = newFontOption; }       if (pageContent) { pageContent.css("font-family", font.css); } if (pageRail) { pageRail.css("font-family", font.css); } }   defaultFontKey = localStorage.getItem(STORAGE_KEY) || defaultFontKey; for (var key in fontOptions) { var fontOption = fontOptions[key]; var fontOptionObj = buildFontOption(fontOption); if (key == defaultFontKey) { fontOptionObj.attr("selected", "true"); changeFont(key); }   }    picker.change(function {        changeFont(picker.val);        localStorage.setItem(STORAGE_KEY, picker.val);    }); var fontPickerContainer = $(" ").css("margin", "10px 0"); fontPickerContainer.append(pickerLabelText); fontPickerContainer.append(picker); var content = $("#PageHeader")[0] || $("#UserProfileMasthead")[0] || $("#EditPageHeader h1")[0]; if (!content) { return true } fontPickerContainer.insertAfter(content); });

// MarketPrices // Lets you view the Market price of items without having to visit the Market page // localStorage might be for caching the Market page so we don't have to request it on every page load // todo: allow getting prices of other items (function {   "use strict";    var mwData = mw.config.get([ "wgNamespaceNumber", "wgTitle" ]);   if (mwData.wgNamespaceNumber !== 0) { return; }    mw.loader.using(["mediawiki.api", "mediawiki.util"], function { var Api = new mw.Api; var util = mw.util; function getMarketSource { return Api.get({               action: "parse",                format: "json",                prop: "wikitext",                page: "Market",            }); }       var marketPriceContainers = $(".market-price"); if (!marketPriceContainers) { return; } getMarketSource.done(function(response) {           if (!response.error) {                var wikitext = response.parse.wikitext["*"];                marketPriceContainers.each(function(index) { var marketPriceContainer = $(this); var itemName = marketPriceContainer.find("#itemname"); itemName = itemName ? itemName.text : mwData.wgTitle; var itemPrices = []; var itemPriceRegex = new RegExp("\\|" + mwData.wgTitle + "\\s*\\(?(Clean|Max)?\\)?\\s*=\\s*(.+?)\\n", "g"); var itemPriceMatch; while ((itemPriceMatch = itemPriceRegex.exec(wikitext)) !== null) { itemPrices.push([itemPriceMatch[1], itemPriceMatch[2]]); }                   var marketLink = $(" (See Market</a>) "); var priceText; switch (itemPrices.length) { case 1: priceText = $(" " + itemPrices[0][0] + " "); break; case 2: // Clean & Max priceText = $("<ul id='price'><li>Clean: " + itemPrices[0][1] + "</li><li>Max: " + itemPrices[1][1] + "</li></ul>"); break; default: console.log("MarketPrice.js: Item price not found"); return; }                   marketPriceContainer.append(priceText).append(marketLink); });           }        });    }); });

/* CheckWarnings (function {    "use strict";    if (window.checkWarningsActive) {        return;    }    window.checkWarningsActive = true;    var config = mw.config.get([ "wgNamespaceNumber", "wgTitle" ]);   if (config.wgNamespaceNumber != 1200) { return; }    var warningsContainer = $(" ");    var warningsList = $("</ul>");    warningsContainer.append(warningsList);    $('#mw-content-text #Wall').before(warningsContainer);    var warningsCountWikiText = " " +    "\ncategory=User warning" +    "\nprefix=" + config.wgTitle +    "\nmode=count" +    " ";    var warningsListWikitext = " " +    "\ncategory=User warning" +    "\nprefix=" + config.wgTitle +    "\nmode=list" +    "\naddauthor=true" +    "\naddcreationdate=true" +    "\naddlastedit=false" +    "\nordermethod=created" +    " ";    $.getJSON(mw.util.wikiScript("api"), { action: "parse", contentmode: "wikitext", format: "json", text: warningsCountWikiText }).done(function(response) { if (!response.error) { var count = $(response.parse.text["*"]).text; var heading = " This user has received " + (count != 0 ? count : "no") + (count == 1 ? " warning." : " warnings.") + (count != 0 ? " The warnings are provided below:" : "") + " ";           warningsContainer.prepend(heading); if (count != 0) { $.getJSON(mw.util.wikiScript("api"), {                   action: "parse",                    contentmode: "wikitext",                    format: "json",                    text: warningsListWikitext                }).done(function(response) {                    if (!response.error) {                        warningsList.append(response.parse.text["*"]);                    }                }); }       }    }); });

/* sketchfab (function {    function isBoolNum(val) {        return (val == 1) || (val == 0);    }    $(".sketchfab").each(function { var sketchfab = $(this); var sketchId = sketchfab.find("#sketch-id"); var width = sketchfab.find("#width"); var height = sketchfab.find("#height"); var transparent = sketchfab.find("#transparent"); var autostart = sketchfab.find("#autostart"); var autospin = sketchfab.find("#autospin"); if (!sketchId) { return; } if (!sketchId.text) { return; } sketchId = sketchId.text; width = width ? parseInt(width.text, "10") : "300" ; height = height ? parseInt(height.text, "10") : "300"; transparent = transparent ? transparent.text : "1"; autostart = autostart ? autostart.text : "0"; autospin = autospin ? autospin.text : "0"; transparent = isBoolNum(transparent) || "1"; autostart = isBoolNum(autostart) || "0"; autospin = isBoolNum(autospin) || "0"; var sketchfabEmbed = "<iframe " + "class='sketchfab-embed' " + "src='https://sketchfab.com/models/" + sketchId + "/embed?transparent=" + transparent + "&autostart=" + autostart + "&autospin" + autospin + "' " + "width='" + width + "' " + "height='" + height + "' " + "allowvr= allowfullscreen= mozallowfullscreen= webkitallowfullscreen= onmousewheel='' frameborder='0'" + "> ";       sketchfab.after(sketchfabEmbed); sketchfab.remove; }); });