Jump to content

User:Wolfgang42/thirdparty/thirdparty.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
$(document).ready(function() {
mw.loader.using('mediawiki.api',function(){
mw.loader.using('mediawiki.user',function(){
    var pagePrefix = 'User:Wolfgang42/thirdparty/';
    if (mw.config.get('wgPageName').indexOf(pagePrefix) != 0) return; // Not relevant to us
    var command=mw.config.get('wgPageName').slice(pagePrefix.length);
    var api=new mediaWiki.Api();
    var allowedDomains=new mw.Map();
    api.get({action:'query',prop:'revisions',rvprop:'content',titles:'User:'+mw.user.getName()+'/ThirdParty allowed domains.js'},function(result){
        for(var key in result.query.pages) {
            var page = result.query.pages[key];  // get first property
            result.query.pages[key] = 0;            // Save over property just in case "delete" actually deletes the property contents instead of just removing it from the object
            delete result.query.pages[key];         // remove the property from the object
            break;                        // "break" because this is a loop
        }
        if (page.missing == null) {
            page.revisions[0]['*'].split("\n").forEach(function(element, index, array) {
                var line=element.split(" ");
                if (line[0]=="*") {
                    allowedDomains.set(line[1],line[2]);
                }
            });
        }
    });
    jQuery.getScript('https://raw.github.com/allmarkedup/jQuery-URL-Parser/master/purl.js', function () { // TODO use mw.Uri instead
        if (command=="Permission" || command=="Install") { // Either page does the same thing, this just helps the user.
            var redirect=$.url().param('thirdpartyRedirect');
            if (redirect==null) return; // Apparently this isn't an auth request
            var domain=$.url(redirect).attr('host');
            if(thirdpartyDomainAllowed(domain)) {
                $("#mw-content-text").text("Authenticated successfully.");
                document.location=redirect;
            } else {
                api.get({action:'query',meta:'userinfo',uiprop:'rights'},function(result) {
                    var rightsList={'edit':'Edit unprotected pages.',
                    'createpage':'Create new pages.',
                    'createtalk':'Create new talk pages.',
                    'move':'Rename the titles of unprotected pages.',
                    'movefile':'Rename pages in the "File" namespace.',
                    'move-subpages':'Move subpages along with page.',
                    'move-rootuserpages':'Move root pages in the "User" namespace.',
                    'createaccount':'Create new user accounts.',
                    'upload':'Create new images and files.',
                    'reupload':'Overwrite existing images and files.',
                    'reupload-own':'Overwrite existing images and files uploaded by you.',
                    'reupload-shared':'Replace images and files from a shared repository (if one is set up) with local files.',
                    'upload_by_url':'Upload by entering the URL of an external image.',
                    'editprotected':'Edit protected pages (without cascading protection).',
                    'delete':'Delete or undelete pages.',
                    'bigdelete':'Delete pages with larger than $wgDeleteRevisionsLimit.',
                    'deletedhistory':'View deleted history entries, but not seeing or restoring revisions.',
                    'deletedtext':'View (but not restore) deleted revisions.',
                    'undelete':'Undelete pages.',
                    'browsearchive':'Search prefixes for titles of deleted pages through Special:Undelete.',
                    'mergehistory':'Access to Special:MergeHistory, to merge non-overlapping pages.',
                    'protect':'Lock a page to prevent edits and moves, and edit or move locked pages.',
                    'block':'Block IP addresses, CIDR ranges, and registered users, including preventing editing and registering new accounts, and autoblocking other users on the same IP address.',
                    'blockemail':'Prevent use of the Special:Emailuser interface when blocking.',
                    'hideuser':'Hide the user/IP from the block log, active block list, and user list when blocking.',
                    'userrights':'Use the user rights interface, which allows the assignment or removal of groups to any user.',
                    'userrights-interwiki':'Allow changing user rights on other wikis.',
                    'rollback':'Allow one-click reversion of edits.',
                    'markbotedits':'Allow rollbacks to be marked as bot edits.',
                    'patrol':'Mark edits as legitimate.',
                    'editinterface':'Edit the MediaWiki namespace, which contains interface messages.',
                    'editusercssjs':'Edit *.css / *.js subpages of any user.',
                    'editusercss':'Edit *.css subpages of any user.',
                    'edituserjs':'Edit *.js subpages of any user.',
                    'suppressrevision':'Prevent deleted revision information from being viewed by sysops and prevents sysops from undeleting the hidden info.',
                    'deletelogentry':'Delete/undelete information (action text, summary, user who made the action) of specific log entries.',
                    'deleterevision':'Delete/undelete information (revision text, edit summary, user who made the edit) of specific revisions.',
                    'siteadmin':'Lock and unlock the database (which blocks all interactions with the web site except viewing).',
                    'import':'Import one page per time from another wiki ("transwiki").',
                    'importupload':'Import several pages per time from XML files.',
                    'trackback':'Remove trackbacks.',
                    'unwatchedpages':'Access Special:Unwatchedpages, which lists pages that no user has watchlisted.',
                    'bot':'Hide edits from recent changes lists and watchlists by default.',
                    'noratelimit':'not affected by rate limits (prior to the introduction of this right, the configuration variable $wgRateLimitsExcludedGroups was used for this purpose)',
                    'autopatrol':'Automatically mark all edits by the user as patrolled.',
                    'suppressredirect':'Move a page without automatically creating a redirect.'};
                    var rights="";
                    result.query.userinfo.rights.forEach(function(right, index, array) {
                        if (rightsList[right] != null) rights += "<li>"+rightsList[right]+"</li>";
                    });
                    $("#mw-content-text").html("<p>The domain <b>"+domain+"</b> is requesting access to your Wikipedia account.</p><p>If you grant access, the website will be able to edit Wikipedia in your name while you are logged in. It will <i>not</i> be able to edit using your account while you are logged out. You can revoke this permission at any time.</p><p>If you grant access, <b>"+domain+"</b> will be able to:</p><ul><li>Access your Wikipedia username</li><li>Edit Wikipedia using your account</li><li>Change your preferences</li><li>Edit your watchlist</li>"+rights+"</ul><p>Only allow this site access if you trust it. Do you wish to grant <b>"+domain+"</b> access to your Wikipedia account?</p>");
                    var allowLink=document.createElement("a");
                    allowLink.href="#";
                    allowLink.innerHTML="<b>Yes,</b> allow "+domain+" to edit Wikipedia using my account";
                    allowLink.onclick=function(event) {
                        console.log("allow");
                        allowedDomains.set(domain,"all");
                        thirdpartySaveAllowedDomains("Added "+domain,function(){document.location=redirect;});
                        return false;
                    }
                    $("#mw-content-text").append(allowLink);
                });
            }
        } else if (command=="API") {
            window.addEventListener('message', function(event) {
                eventdata=JSON.parse(event.data);
                var result={'request':eventdata,'status':'error','message':''};
                if (thirdpartyDomainAllowed($.url(event.origin).attr('host'))) {
                    if (eventdata.command == "ping") {
                        result.status='ok';
                    } else if (eventdata.command == "api") {
                        var query;
                        if (eventdata.method == 'get') {
                            query=api.get(eventdata.request);
                        } else {
                            query=api.post(eventdata.request);
                        }
                        query.done(function (data) {
                            result.status="ok";
                            result.data=data;
                            event.source.postMessage(JSON.stringify(result),event.origin);
                        });
                        query.fail(function (error) {
                            result.status="apierror";
                            result.error=error;
                            event.source.postMessage(JSON.stringify(result),event.origin);
                        });
                        return;
                    } else if (eventdata.command == 'render') {
                        $.get('/w/index.php?action=render&title='+encodeURIComponent(eventdata.page)).complete(function(response){
                            result.status="ok"; // TODO not necessarily?
                            result.response=response;
                            event.source.postMessage(JSON.stringify(result),event.origin);
                        });
                        return;
                    } else {
                        result.status="error";
                        result.message="Unknown command";
                    }
                } else {
                    result.status="permissiondenied";
                }
                event.source.postMessage(JSON.stringify(result),event.origin);
            }, false);
        }
    });
    function thirdpartyDomainAllowed(domain) {
        return allowedDomains.exists(domain);
    }
    function thirdpartySaveAllowedDomains(summary,callback) {
        var text="";
        for(var domain in allowedDomains.values) {
            text += "* "+domain+" "+allowedDomains.get(domain)+"\n";
        }
        api.post({'action':"edit",'title':'User:'+mw.user.getName()+'/ThirdParty allowed domains.js',
                'text':text,'summary':summary,'token':mw.user.tokens.get('editToken')},callback);
    }
});});});

// JSON.stringify()
// TODO is this available in MediaWiki somewhere?
(function() { function g(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null"; else if("function"==b&&"undefined"==typeof a.call)return"object";return b};function h(a){a=""+a;if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/"[^"\\\n\r\u2028\u2029\x00-\x08\x10-\x1f\x80-\x9f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,"")))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);}function i(a,b){var c=[];j(new k(b),a,c);return c.join("")}function k(a){this.a=a} function j(a,b,c){switch(typeof b){case "string":l(b,c);break;case "number":c.push(isFinite(b)&&!isNaN(b)?b:"null");break;case "boolean":c.push(b);break;case "undefined":c.push("null");break;case "object":if(null==b){c.push("null");break}if("array"==g(b)){var f=b.length;c.push("[");for(var d="",e=0;e<f;e++)c.push(d),d=b[e],j(a,a.a?a.a.call(b,""+e,d):d,c),d=",";c.push("]");break}c.push("{");f="";for(e in b)Object.prototype.hasOwnProperty.call(b,e)&&(d=b[e],"function"!=typeof d&&(c.push(f),l(e,c),c.push(":"), j(a,a.a?a.a.call(b,e,d):d,c),f=","));c.push("}");break;case "function":break;default:throw Error("Unknown type: "+typeof b);}}var m={'"':'\\"',"\\":"\\\\","/":"\\/","\u0008":"\\b","\u000c":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},n=/\uffff/.test("\uffff")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g; function l(a,b){b.push('"',a.replace(n,function(a){if(a in m)return m[a];var b=a.charCodeAt(0),d="\\u";16>b?d+="000":256>b?d+="00":4096>b&&(d+="0");return m[a]=d+b.toString(16)}),'"')};window.JSON||(window.JSON={});"function"!==typeof window.JSON.stringify&&(window.JSON.stringify=i);"function"!==typeof window.JSON.parse&&(window.JSON.parse=h); })();