User:Eurodyne/common.js

// mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Krinkle/Tools/Global_SUL.js&action=raw&ctype=text/javascript'); /** * Note: this is based on https://meta.wikimedia.org/w/index.php?title=User:Krinkle/Tools/Global_SUL.js&oldid=3516641 * * This script provides an extra Special-page action called "Create Global Userpage" which * allows easy auto-creation and editing of your userpage and js/css subpages on all local wikis. * After enabling the script, the tool is accessible from Special:BlankPage/globalpage. * * Requires installation of Krinkle's Global SUL script first. * * @source //meta.wikimedia.org/w/index.php?title=User:PiRSquared17/Global_Userpage.js * @revision 0.3 (2013-10-26) (based on Krinkle's Global Sul version 3 (2012-01-29)) * @stats none */ (function ($, mw) {   if (!$.support.cors) {        return alert('Your browser does not support CORS! Try Firefox.');   }    // Edit page using CORS (works on modern browsers except IE)    function editPage(info) {        var params = {            format: 'json',            action: 'edit',            title: info.title,            summary: info.summary,            origin: location.origin,            assert: 'user', // must be logged in!            token: info.token        };        if (info.editaction === "createonly") {            params['text'] = info.text;            params['createonly'] = 'true';        } else {            params[info.editaction] = info.text;        }        $.ajax({ url: info.url, type: 'POST', dataType: 'json', data: params, xhrFields: { withCredentials: true }       })            .done(function (data) { if (data && data.edit && data.edit.result && data.edit.result == 'Success' && typeof info.success === 'function') { info.success(data); } else if (typeof info.error === 'function') { info.error(data); }           })            .fail(function  { if (typeof info.error === 'function') { info.error; }           });    }    function getEditToken(apiPath, success) {        $.ajax({ url: apiPath, dataType: 'json', data: { action: 'tokens', type: 'edit', format: 'json', origin: location.origin, },           'success': success, xhrFields: { withCredentials: true }       });    }    function initGlobalUP {        var $content, $fieldset, $subtitle, $table,            $status, $btnStart, $progress, $done, $log,            globalaccountinfo;        $content = $('#bodyContent').empty;        $fieldset = $(' ');        $subtitle = $(' ');        $table = $( ' '       );        $status = $table.find('#mw-globalpage-status');        $btnStart = $table.find('#mw-globalpage-start');        $log = $table.find('tbody');        $progress = $table.find('#mw-globalpage-progress');        $done = $table.find('#mw-globalpage-done');        function doUpdate(wiki, msg, iterationNr, listLength) {            $status.text(wiki + ': ' + msg);            $log.append('  ' + new Date.toString.replace(/^\w+ /, ).replace(/:[^:]+$/, ) + '  ' + wiki + '  ' + mw.html.escape(msg) + '  ');            if (iterationNr && listLength) {                $progress.text((Math.round(((iterationNr) / listLength) * 100 * 10) / 10) + '%');                $done.text('(' + iterationNr + '/' + listLength + ' wikis)');            }        }        function getGlobalAccountInfo(ok, err) {            $.ajax({ url: mw.util.wikiScript('api'), dataType: 'json', data: { format: 'json', action: 'query', meta: 'globaluserinfo', guiuser: mw.user.name, guiprop: 'merged|unattached' },               success: function (data) { if (data && data.query && data.query.globaluserinfo) { ok(data.query.globaluserinfo); } else { err; }               },                error: err });       }        // Build front-end        $('#firstHeading').text('Global User Page');        document.title = 'Global User Page - ' + mw.config.get('wgSiteName');        $fieldset            .text('Check all public Wikimedia wikis and modify or create user pages (with possible exceptions).')            .append('

User User talk :' + mw.config.get('wgUserName') + '' + ' (Main userpage) ' + '/common.js ' + '/common.css ' + ' /(other...) ' + ' ' + '')            .append('&lt;!-- IMPORTANT: REMOVE THIS LINE (ESPECIALLY IF JS OR CSS) AND REPLACE WITH CONTENT --> ')            .append('Select which wikis to edit: ')           .append(' Please read the documentation before using, and try out this content on at least three wiki (one where userpage exists, RTL wiki, non-Wikipedia). Summary :  ')           .append('What should be done to existing pages? ' + ' Skip existing (createonly) ' + ' Append (you should manually insert newline at beginning) ' + ' Replace all existing content on page ' + ' Prepend (insert newline at end of text) ' + ' ')           .prepend($(' ').text('Create userpage globally (v0.3)'))            .append($table);        $.ajax('/w/api.php', { dataType: 'json', data: { format: 'json', action: 'sitematrix' },   success: function (data) { var matrix = data.sitematrix, list = [], table = $(' Language Wikipedia Wiktionary Wikibooks Wikinews <th class="mw-tmpmatrix-wikiquote">Wikiquote <th class="mw-tmpmatrix-wikisource">Wikisource <th class="mw-tmpmatrix-wikiversity">Wikiversity <th class="mw-tmpmatrix-wikivoyage">Wikivoyage  '), tr; for (var i = 0;; i++) { if (typeof matrix[i] === 'undefined') break; tr = $(' <td class="mw-tmpmatrix-lang-' + matrix[i].code + '">' + matrix[i].code + ' <td class="mw-tmpmatrix-wiki"> <td class="mw-tmpmatrix-wiktionary"> <td class="mw-tmpmatrix-wikibooks"> <td class="mw-tmpmatrix-wikinews"> <td class="mw-tmpmatrix-wikiquote"> <td class="mw-tmpmatrix-wikisource"> <td class="mw-tmpmatrix-wikiversity"> <td class="mw-tmpmatrix-wikivoyage"> '); for (var j = 0;; j++) { if (typeof matrix[i].site[j] === 'undefined') break; tr.find('.mw-tmpmatrix-' + matrix[i].site[j].code).append('<input type="checkbox" id="skip-' + matrix[i].site[j].dbname + '" checked />'); }           table.append(tr); }       table.find('tr').find('td:first').append(' / ').find('button').click(function  {            $(this).parent.parent.find('td input').click        }); table.find('tr:first th:gt(0)').append(' / ').find('button').click(function {            $('.' + $(this).parent.attr('class')).find('input').click;        }); table.append(' Specials ') for (i = 0; i < matrix.specials.length; i++) { table.append('<tr class="mw-tmpmatrix-special"> ' + matrix.specials[i].dbname + '<input type="checkbox" id="skip-' + matrix.specials[i].dbname + '" checked /> '); }       table.insertAfter('#mw-globalpage-skipwiki'); } });       // Bind events        $btnStart.click(function (e) { var iterator, mergedList, unattachedList, attemptedList, regex = /^(.*?)\.(.*?)(?:\.org)?$/, editaction = $('#mw-globalpage-editaction').val, text = $('#mw-globalpage-text').val, title = $('#mw-globalpage-namespace').val + ':' + mw.config.get('wgUserName'); if ($('#mw-globalpage-select').val !== 'main') { title += '/'; if ($('#mw-globalpage-select').val === 'other') { title += $('#mw-globalpage-otherpage-input').val; } else { title += $('#mw-globalpage-select').val; }           }            //console.log(skipList); $(this).remove; doUpdate('', 'Initializing...'); iterator = new mw.siteMatrix.Iterator({               centralApiPath: mw.util.wikiScript('api'),                onIteration: function (instance, wikiObj, iterationNr, listLength) {                    var img, url, hostname;                    // All WMF wikis support https, but canonical is still 'http'                    // convert API absolute urls to relative urls so that                     // users of this gadget can be on either http or https and it works                    url = wikiObj.url.replace(/^https?:/, );                    hostname = url.replace(/^\/\/?/, );                    //doUpdate(hostname, 'checking...', iterationNr, listLength);                    if ($.inArray(wikiObj.dbname, mergedList) !== -1) {                        //doUpdate(hostname, 'acct is merged');                        if ((!$('#skip-' + wikiObj.dbname).attr('checked')) || (wgDBname == wikiObj.dbname)) { doUpdate(hostname, 'skipping'); setTimeout(instance.next, 1); return; } else { doUpdate(hostname, 'trying to edit...'); getEditToken(url + '/w/api.php', function (data) {                               editPage({ url: url + '/w/api.php', title: title, text: text, editaction: editaction, summary: $("#mw-globalpage-summary").val + ((hostname === 'mr.wikipedia.org') ? ' [presumed mr-0]' : ''), token: data.tokens.edittoken, success: function { doUpdate(hostname, 'Success!'); setTimeout(instance.next, 100); },                                   error: function  { doUpdate(hostname, 'error/fail'); setTimeout(instance.next, 100); }                               });                            });                            attemptedList.push(hostname); }                   } else if ($.inArray(wikiObj.dbname, unattachedList) !== -1) { doUpdate(hostname, 'unattached acct'); setTimeout(instance.next, 1); } else { doUpdate(hostname, 'no local acct'); setTimeout(instance.next, 1); }               },                onComplete: function (instance, wikiObj, listLength) { doUpdate('', 'Finished.', listLength, listLength); $status.html('Made ' + attemptedList.length + ' auto-create attempts.'); if (attemptedList.length > 0) { $status.append('<ul><li>' + attemptedList.join('</li><li>') + '</li></ul>'); }               }            });            doUpdate('', 'Getting global account info...');            getGlobalAccountInfo(function (gui) { doUpdate('', 'Global account info received'); mergedList = []; unattachedList = []; attemptedList = []; if (gui.merged) { $.each(gui.merged, function (i, obj) {                       mergedList.push(obj.wiki);                    }); }               if (gui.unattached) { $.each(gui.unattached, function (i, obj) {                       unattachedList.push(obj.wiki);                    }); }               doUpdate('', 'Loading wiki SiteMatrix...'); iterator.start; }, function { doUpdate('', 'Download of global account info failed!'); });       });        // Output $content.append($subtitle, $fieldset); // add defaults var defaults = { 'main': '\n' + '\n ' + 'Hello. I do not edit here much, but I am a member of the Small Wiki Monitoring Team. ' + 'You can find me on Meta or Wikipedia/Wiktionary/whatever in xyz language:' + ' m:User:$1, m:xyz:User:$1.\n \n' + 'm:   :$1', 'common.js': '// Created using m:User:PiRSquared17/Global Userpage (feel free to remove this line)\n' + 'mw.loader.load(\'//meta.wikimedia.org/w/index.php?title=User:$2/global.js&action=raw&ctype=text/javascript\');', 'common.css': '/* Created using m:User:PiRSquared17/Global Userpage (feel free to remove this line) */\n' + '@import "//meta.wikimedia.org/w/index.php?title=User:$2/global.css&action=raw&ctype=text/css";', 'other': '' };       $('#mw-globalpage-select').on('change', function (e) {            $('#mw-globalpage-text').val(defaults[$(this).val] .replace(/\$1/g, mw.config.get('wgUserName')) .replace(/\$2/g, encodeURIComponent(mw.config.get('wgUserName'))));           if ($(this).val === 'other') {                $('#mw-globalpage-otherpage-input').show;            } else {                $('#mw-globalpage-otherpage-input').hide;            }        }); $('#mw-globalpage-skipwiki').on('keyup', function (e) {           //console.log(0);            var skip = $('#mw-globalpage-skipwiki').val.split(',');            var regex = /^(.*?)\.(.*?)(?:\.org)?$/;            $('#mw-globalpage-skip').empty;            for (var i = 0; i < skip.length; i++) {                if (skip[i].match(regex) === null) continue;                $('#mw-globalpage-skip').append('<li>' + skip[i].match(regex).splice(1).join("."));            }        }); $('#mw-globalpage-text').val(defaults['main'].replace(/\$1/g, mw.config.get('wgUserName'))); }   // Enqueue init if (mw.config.get('wgCanonicalSpecialPageName') === 'Blankpage' && mw.config.get('wgTitle').indexOf('/globalpage') > 2) { mw.loader.using('mediawiki.util', initGlobalUP); } }(jQuery, mediaWiki));