Male user:Vogone/Global UP.js

From Wikipedia

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/**
 * 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 ([[File:Krinkle_Global_SUL.js]])
 */
(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 = $('<fieldset>');
        $subtitle = $('<div id="contentSub"></div>');
        $table = $(
            '<table class="wikitable" style="width: 100%;"><tbody>' + '<tr><th>Status</th><th>Progress</th><th>N/A</th></tr>' + '<tr>' + '<td id="mw-globalpage-status">Ready for action! (please read docs!) <button id="mw-globalpage-start">Start</button></td>' + '<td style="vertical-align: top;"><span id="mw-globalpage-progress">0%</span>' + '<span id="mw-globalpage-done" style="float: right;"></span>' + '</td><td>N/A</td>' + '</tr>' + '<th>Time</th><th>Wiki</th><th>Action</th>' + '</tbody></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('<tr><td>' + new Date().toString().replace(/^\w+ /, '').replace(/:[^:]+$/, '') + '</td><td>' + wiki + '</td><td>' + mw.html.escape(msg) + '</td></tr>');
            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('<br /><br /><select id="mw-globalpage-namespace"><option value="User">User</option><option value="User_talk">User talk</option></select>:' + mw.config.get('wgUserName') + '<select id="mw-globalpage-select">' + '<option value="main"> (Main userpage)</option>' + '<option value="common.js">/common.js</option>' + '<option value="common.css">/common.css</option>' + '<option value="other">/(other...)</option>' + '</select>' + '<input style="display:none" id="mw-globalpage-otherpage-input" value="monobook.js">')
            .append('<textarea id="mw-globalpage-text" cols="80" rows="10">&lt;!-- IMPORTANT: REMOVE THIS LINE (ESPECIALLY IF JS OR CSS) AND REPLACE WITH CONTENT --></textarea>')
            .append('Select which wikis to edit:<br /><span id="mw-globalpage-skipwiki"></span>')
            .append('<br /><b>Please read the documentation before using, and try out this content on at least three wiki (one where userpage exists, RTL wiki, non-Wikipedia).<br /><label for="mw-globalpage-summary">Summary</label>: <input id="mw-globalpage-summary" value="Editing global userpage" /><br />')
            .append('What should be done to existing pages? <select id="mw-globalpage-editaction">' + '<option value="createonly">Skip existing (createonly)</option>' + '<option value="appendtext">Append (you should manually insert newline at beginning)</option>' + '<option value="text">Replace all existing content on page</option>' + '<option value="prependtext">Prepend (insert newline at end of text)</option>' + '</select>')
            .prepend($('<legend>').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 = $('<table id="mw-tmpmatrix" class="wikitable sortable" width="30%"><tr><th>Language</th><th class="mw-tmpmatrix-wiki">Wikipedia</th><th class="mw-tmpmatrix-wiktionary">Wiktionary</th><th class="mw-tmpmatrix-wikibooks">Wikibooks</th><th class="mw-tmpmatrix-wikinews">Wikinews</th><th class="mw-tmpmatrix-wikiquote">Wikiquote</th><th class="mw-tmpmatrix-wikisource">Wikisource</th><th class="mw-tmpmatrix-wikiversity">Wikiversity</th><th class="mw-tmpmatrix-wikivoyage">Wikivoyage</th></tr>'),
            tr;
        for (var i = 0;; i++) {
            if (typeof matrix[i] === 'undefined') break;
            tr = $('<tr><td class="mw-tmpmatrix-lang-' + matrix[i].code + '">' + matrix[i].code + '</td><td class="mw-tmpmatrix-wiki"></td><td class="mw-tmpmatrix-wiktionary"></td><td class="mw-tmpmatrix-wikibooks"></td><td class="mw-tmpmatrix-wikinews"></td><td class="mw-tmpmatrix-wikiquote"></td><td class="mw-tmpmatrix-wikisource"></td><td class="mw-tmpmatrix-wikiversity"></td><td class="mw-tmpmatrix-wikivoyage"></td></tr>');
            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('<button>/</button>').find('button').click(function () {
            $(this).parent().parent().find('td input').click()
        });
        table.find('tr:first th:gt(0)').append('<button>/</button>').find('button').click(function () {
            $('.' + $(this).parent().attr('class')).find('input').click();
        });
        table.append('<tr><th width="100">Specials</th></tr>')
        for (i = 0; i < matrix.specials.length; i++) {
            table.append('<tr class="mw-tmpmatrix-special"><td width="100">' + matrix.specials[i].dbname + '<input type="checkbox" id="skip-' + matrix.specials[i].dbname + '" checked /></td></tr>');
        }
        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': '<!--This is just an example. Edit it to make it yours. PLEASE CHANGE THE BABEL AND CONTENT. THIS IS 100% YOUR RESPONSIBILITY. -->\n' + '{{#babel:<!--ADD BABEL HERE, UPDATE LANGUAGE LIST before #default (see right:)-->' + 'en-N|es-2|fr-1|' + '}}\n<div class="mw-content-ltr" lang="en" dir="ltr">' + 'Hello. I do not edit here much, but I am a member of [[m:Special:MyLanguage/Small Wiki Monitoring Team|the Small Wiki Monitoring Team]]. ' + 'You can find me on Meta or Wikipedia/Wiktionary/whatever in xyz language:' + '<!--Do not remove m: from link unless you know what you are doing (see docs for more info) --> [[m:User:$1]], [[m:xyz:User:$1]].\n</div>\n' + '<!--This can be used to make a redirect arrow.-->[[File:Redirect arrow without text.svg|46px|link=]][[m:User talk:$1|m:{{ns:3}}:$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));