User:Dominic1743/global.js

importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:DiscussionTemplates.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:QuickLogs/code.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:DiscussionsRC.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:PatrolRC/code.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:AjaxUserRights.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:OnPageForms.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:PortableListUsers.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:RedirectManagement/code.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:UserAndIPTools.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:UserInfo.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:QuickContribs/code.js'    ] }); importArticle({   type: 'script',    article: 'u:dev:MediaWiki:AdminDashboard block/code.js',    }); var MessageBlock = { title : 'Blocked', message : 'You have been blocked for $2 for $1.', autocheck : true }; importArticles({   type: 'script',    articles: [        'u:dev:MessageBlock/code.js'    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:ArchiveTool/code.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:PowerDelete/code.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:AjaxDiff/code.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:CategoryRenameAuto-update/code.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:MultiUpload/code.js',    ] }); importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:AjaxEdit.js',    ] }); /* Redirect to base page if ends with '/' */ if (window.location.href.match("/$")) { window.location.href = window.location.href.slice(0, -1); } /* 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); });   } }); /* Standard Edit Summary config */ window.dev = window.dev || {}; window.dev.editSummaries = { select: [ '(click to browse)', 'Quick', [ 'Credit to the wikia watchers', 'Redlink removal', 'Duplicate image', 'Removing vandalism', 'Fixing error(s)', 'Corrected spelling/grammar', 'Corrected formatting/layout' ],       'General', [ 'Testing', 'Testing (will revert shortly if fails)', 'Testing complete', 'Added/removed/corrected wikilink(s)', 'Added/removed/corrected interwiki link(s)', 'Added/removed/corrected external link(s)', 'Cleanup', 'Comment', 'Correction(s), coding', 'Expanded', 'Formatting', 'Grammar', 'Headings (adjusting, etc.)', 'HTML &rarr; wikicode', 'Layout', 'Mini-wikifying', 'Punctuation', 'Redlink removal', 'Refactoring', 'Removing RTE refuse', 'Re-ordering/re-organizing', 'Reply', 'Revised', 'Signing', 'Spelling', 'Style/layout', 'Suggestion', 'Tidying', 'Updating', 'Wikifying', 'Factual correction', 'Added/removed/corrected sources/appearances' ],       'Removal/Reversion', [ 'Reverted vandalism', 'Reverted test edit', 'Reverted vanity edit', 'Removed fanon', 'Removed libel/slander', 'Removed copyvio', 'Removed spam' ],       'Templates', [ 'Added/removed/corrected template(s)', 'Added/removed/corrected infobox(es)', 'Substituting template(s)', ],       'Categories', [ 'Added category(ies)', 'Alphabetised category(ies)', 'Creating Category page', 'Modified category(ies)', 'Removed category(ies)', 'Removed defunct category(ies)', 'Removed duplicate category(ies)' ],       'Images/Files', [ 'Adding image(s)', 'Modifying image(s)' ]   ] }; /* Show bot edits on RecentChanges */ if (wgPageName == "Special:RecentChanges") { if (window.location.href.indexOf("hidebots=") == -1 && window.location.href.indexOf("?") == -1) { window.location.href = window.location.href + "?hidebots=0"; } else if (window.location.href.indexOf("hidebots=") == -1 && window.location.href.indexOf("?") !== -1) { window.location.href = window.location.href + "&hidebots=0"; } } else if (wgPageName == "Special:Newwikis") { if (window.location.href.indexOf("language=") == -1 && window.location.href.indexOf("?") == -1) { window.location.href = window.location.href + "?language=en"; } else if (window.location.href.indexOf("language=") == -1 && window.location.href.indexOf("?") != -1) { window.location.href = window.location.href + "&language=en"; } } /* Block links */ $(function {   if ($('#UserProfileMasthead').length) {        $('.tag-container').after('Block');    }    // Threads    if (wgNamespaceNumber != 1201) return;    for (var i in $('.msg-toolbar')) {        var usr = $('.msg-toolbar:eq(' + i + ')').parent.find('.edited-by a').text;        $('.msg-toolbar:eq(' + i + ')').find('.WikiaMenuElement li').last.before('Block');    } }); /* Add gender tag to global masterhead */ $(function {   if($("#UserProfileMasthead").length === 0) {        return;    }    mw.loader.using('mediawiki.api').then(function { new mw.Api.get({           action: 'parse',            text: ''        }).done(function(d) {            if(d.parse.text['*'].indexOf('thisisjustsomethingstupid') === -1) {                $('.masthead-info hgroup').append(' ' + d.parse.text['*'] + ' ');            }        }); }); }); /* Create user page on link click */ $('', {id: 'qcup',}) .html('Create user page') //create the link .prependTo('#my-tools-menu') //put it in the toolbar .click(function { //when clicked   $.ajax( { //create the userpage type: 'POST', url: mw.util.wikiScript( 'api' ), dataType: 'json', data: { action: 'edit', title: 'User:Dominic1743', //at this page summary: 'Creating user page (script)', //with this edit summary text: '', //using this tempalte format: 'json', token: mw.user.tokens.get( 'editToken' ) }   } ).done( function ( data ) { if ( data.edit.result === 'Success' ) { new BannerNotification("Successfully created user page!","confirm").show; //say we created the page } else { new BannerNotification("An error occurred while creating user page.","error").show; //say we didn't create the page }   } ).fail( function ( data ) { new BannerNotification("An error occurred while creating user page.","error").show; //say we didn't create the page } ); }); /* Create message wall greeting on link click */ $.ajax({   type: 'HEAD', //see if    url: wgServer + '/wiki/Message_Wall:Dominic1743', //my message wall exists    success: function { //if it exists        $('', {id: 'qcmwg',})        .html('Create Greeting') //create the link        .prependTo('#my-tools-menu') //put it in the my tools menu on the toolbar        .click(function { //when clicked $.ajax( { //create the message wall greeting           type: 'POST',            url: mw.util.wikiScript( 'api' ),            dataType: 'json',            data: {                action: 'edit',                title: 'Message_Wall_Greeting:Dominic1743', //at this page                summary: 'Creating message wall greeting (script)', //with this edit summary                text: '', //using this template                format: 'json',                token: mw.user.tokens.get( 'editToken' )            }            } ).done( function ( data ) {                if ( data.edit.result === 'Success' ) {                    new BannerNotification("Successfully created message wall greeting!","confirm").show; //say we created the page                } else {                    new BannerNotification("An error occurred creating while message wall greeting.","error").show; //say we didn't create the page }           } ).fail( function ( data ) { new BannerNotification("An error occurred while creating message wall greeting.","error").show; //say we didn't create the page } );       });    },    error: function { //if it doesn't exist return; //do nothing } }); /* Revert buttons */ //@author-Prince(ss)_Platinum (http://community.wikia.com/wiki/User:Prince(ss)_Platinum/vda.js) // Reverting tools V6.6 Gold (Original coding by VegaDark, modified by Ajraddatz and Manyman) function getElementsByClass(searchClass,node,tag) { // Function from http://www.dustindiaz.com/getelementsbyclass/  var classElements = new Array;  if ( node === null )    node = document;  if ( tag === null )    tag = '*';  var els = node.getElementsByTagName(tag);  var elsLen = els.length;  var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");  for (i = 0, j = 0; i < elsLen; i++) {    if ( pattern.test(els[i].className) ) {      classElements[j] = els[i];      j++;    }  }  return classElements; } // _GET code from NoGray JS Library http://www.nogray.com/new_site/ var _GET = new Array; var _uri = location.href; var _temp_get_arr = _uri.substring(_uri.indexOf('?')+1, _uri.length).split("&"); var _temp_get_arr_1 = new Array; for(_get_arr_i=0; _get_arr_i<_temp_get_arr.length; _get_arr_i++){ _temp_get_arr_1 = _temp_get_arr[_get_arr_i].split("="); _GET[decodeURI(_temp_get_arr_1[0])] = decodeURI(_temp_get_arr_1[1]); } delete _uri; delete _temp_get_arr; delete _temp_get_arr_1; function getMessage (where, user1, user2) { var message = prompt ('Enter undo message below:', ''); window.location = 'http://'+ location.hostname + '/index.php?title=' + _GET['title'] + '&action=edit&oldid=' + _GET['oldid'] + '&'+where+'=2&user1='+user1+'&user2='+user2+'&message='+message; } function AGFMessage (where, user1, user2) { var message = prompt ('Enter undo message below:', ''); window.location = 'http://'+ location.hostname + '/index.php?title=' + _GET['title'] + '&action=edit&oldid=' + _GET['oldid'] + '&'+where+'=3&user1='+user1+'&user2='+user2+'&message='+message; } addOnloadHook(function { if (location.href.match(/diff=/)) {    // Get username of submitter    var user1 = getElementsByClass('diff-otitle',null,'td'); user1 = user1[0].getElementsByTagName('a')[2].innerHTML;    var user2 = getElementsByClass('diff-ntitle',null,'td'); user2 = user2[0].getElementsByTagName('a')[3].innerHTML;    $('#mw-content-text').prepend(' ');    document.getElementById('vda-cont').innerHTML = 'Custom Speculation</a></b> <b>Revert (Vandalism)</a> </b> <b>Revert (Good faith)</a> </b> <b>Revert (Spam)</a> </b>' + ; } else if (location.href.match(/revert=1/)) {    document.getElementById('wpSummary').value = 'Reverted Vandalism by $1 (talk | block) to last version by $2';    document.getElementById('editform').submit;  } else if (location.href.match(/revert=6/)) {    document.getElementById('wpSummary').value = 'Reverted good faith edits';    document.getElementById('editform').submit;  } else if (location.href.match(/revert=3/)) {    document.getElementById('wpSummary').value = 'Speculation';    document.getElementById('editform').submit;  } else if (location.href.match(/revert=2/)) {    document.getElementById('wpSummary').value =  +_GET['message']+ '';    document.getElementById('editform').submit; } else if (location.href.match(/revert=4/)) { document.getElementById('wpSummary').value = 'Reverted spam'; document.getElementById('editform').submit; } }); /* AjaxBlock config */ window.AjaxBlock = {   blockReasons: {        'Vandalism': 'Vandalism',        'Spam': 'Spam',        'Repeated policy violations': 'Repeated violations',        'Sockpuppetry/Ban Evasion': 'Sockpuppetry',        'Moved to a new account': 'Moved',        'Removing content/blanking pages': 'Page blanking',        'Inserting false information or nonsense': 'Gibberish',        'Intimidating behaviour/harassment/trolling': 'Troll/Harassment',        'Unacceptable username, avatar, or global masthead': 'Name/avatar',        'Under the legal age': 'COPPA',        'Failing to comply with the File Policy': 'File Policy',        'Posting/Discussing leaked content': 'Leaks'    },    check: {        creation: true,        talk: true,        autoBlock: true,        override: true    } }; /* Show removed replies */ $(".message-removed.hide").removeClass("hide").each(function {   var $this = $(this),    id = $this.attr('data-id'),    relativeid = $this.attr('id'),    isBoardThread = !!$('.voting-controls').length,    Api = new mw.Api;    Api.get({ action: 'query', prop: 'revisions', rvprop: 'timestamp|user', pageids: id, rvlimit: 500 }).done(function(ts) { var rev = ts.query.pages[id].revisions[0], name = rev.user, time = rev.timestamp, d = new Date(time), // this may be a readable string, but the code certainly isn't :P readableTime = d.getHours + d.getTimezoneOffset / 60 + ':' + d.getMinutes + ', ' + wgMonthNames[d.getMonth + 1] + ' ' + d.getDate + ', ' + d.getFullYear; $.get('/api/v1/User/Details', {           ids: name,            size: 50        }).done(function(avi) {            avi = avi.items[0].avatar;            Api.get({ action: 'parse', pageid: id           }).done(function(d) { var html = d.parse.text['*'], $avatar = $(' ', {                   class: 'speech-bubble-avatar'                }).append($('', { href: wgArticlePath.replace('$1', 'Message_Wall:' + name), append: $(' ', {                       src: avi,                        width: '30',                        height: '30',                        class: 'avatar',                        alt: name                    }) })),               $msg = $(' ', {                    class: 'speech-bubble-message'                }).append($(' ', { class: 'MiniEditorWrapper', 'data-min-height': '100', 'data-max-height': '400', append: [ $(' ', {                           class: 'edited-by',                            append: [                                $('', { text: name, href: wgArticlePath.replace('$1', 'Message_Wall:' + name) }),                               $('', { class: 'subtle', href: wgArticlePath.replace('$1', 'Message_Wall:' + name) })                           ]                        }),                        $(' ', {                            class: 'editarea',                            'data-space-type': 'editarea',                            append: [                                $(' ', { class: 'msg-body', id: 'WallMessage_' + id, html: html }),                               $(' ', {                                    class: 'loading-indicator', 'data-space-type': 'loading-status', append: [ $(' ', {                                           class: 'loading-background'                                        }), $(' ', {                                           class: 'loading-message',                                            append: [                                                $(' ', { class: 'loading-throbber', html: ' ' }),                                               $(' ', {                                                    class: 'loading-text', html: 'Loading editor' })                                           ]                                        })                                    ]                                })                            ]                        }),                        $(' ', {                            class: 'toolbar',                            'data-space-type': 'toolbar'                        }), $(' ', {                           class: 'msg-toolbar',                            append: [                                $(' ', { class: 'timestamp', append: $('', {                                       class: 'permalink',                                        tabindex: '-1',                                        href: '#' + relativeid,                                        append: [                                            $(' ', { class: 'timeago abstimeago', title: time, alt: readableTime, each: function { $(this).timeago; }                                           }),                                            $(' ', {                                                class: 'timeago-fmt', text: readableTime })                                       ]                                    })                                })/*, not adding buttons  coz it's way too hard (also idk why you'd want to quote a removed message)                                $(' ', { class: 'buttonswrapper', append: the_buttons :P })*/                           ]                        })                    ]                }));                $this.append($avatar, $msg); console.log(d); });       });    }); }); /* PageCreator config */ window.pageCreatorAvatar = true; window.pageCreatorTimestamp = true; window.pageCreatorNamespaces = Object.keys(mw.config.get("wgFormattedNamespaces")).map(Number); /* LastEdited config */ window.lastEdited = { namespaces: { include: Object.keys(mw.config.get("wgFormattedNamespaces")).map(Number) } }; window.PRAoptions = { editSummary: 'Links' } /* Imports */ window.batchDeleteDelay = 100; importArticles({   type: "script",    articles: [        'u:dev:MediaWiki:AjaxBatchDelete/code.js',        'u:dev:MediaWiki:AjaxBatchDelete/code.2.js',        'u:dev:MediaWiki:AjaxBatchUndelete.js',        'u:dev:MediaWiki:CatFilter/code.js',        'u:dev:MediaWiki:CategoryRenameAuto-update/code.js',        'u:dev:MediaWiki:FastDelete/code.js',        'u:dev:MediaWiki:CacheCheck/code.js',        'u:dev:MediaWiki:MarkBlocked.js',        'u:dev:MediaWiki:AjaxRC/code.js',        'u:dev:MediaWiki:AnchoredRollback/code.js',        'u:dev:MediaWiki:AjaxDelete/code.js',        'u:dev:MediaWiki:AjaxPatrol/code.js',        'u:dev:MediaWiki:LastEdited/code.js',        'u:dev:MediaWiki:AjaxUndo/code.js',        'u:dev:MediaWiki:PageCreator/code2.js',        'u:dev:MediaWiki:HoverEditCount/code.js',        'u:dev:MediaWiki:UserAccountAge/code.js',        'u:dev:MediaWiki:ContribsLink/code.js',        'u:dev:MediaWiki:DupImageList/code.js', 'u:dev:MediaWiki:DisplayTimer/code.js', 'u:dev:MediaWiki:CodeQuickLinks/code.js', 'u:dev:MediaWiki:Linksweeper/code.js', 'u:dev:MediaWiki:WorkingMoreUsersCount.js', 'u:dev:MediaWiki:ToggleSideBar/code.js', 'u:dev:MediaWiki:WHAM/code.2.js', 'u:dev:MediaWiki:FastOldImageDelete/code.js', 'u:dev:MediaWiki:ListFiles/code.js', 'u:dev:MediaWiki:WallGreetingButton/code.js', 'u:dev:MediaWiki:MassCreate/code.js', 'u:dev:MediaWiki:MassProtect/code.js', 'u:dev:MediaWiki:MassNullEdit/code.js', 'u:dev:MediaWiki:MassRename/code.js', 'u:dev:MediaWiki:MassRenameRevert/code.js', 'u:dev:MediaWiki:FileUsageAuto-update/code.js', 'u:dev:MediaWiki:PageRenameAuto-update/code.js', 'u:dev:MediaWiki:QuickToolsv2/code.js', 'u:dev:MediaWiki:OldFilePages/code.js', 'u:dev:MediaWiki:Standard_Edit_Summary/code.js', 'u:dev:MediaWiki:Thread Inspection/code.js', 'u:dev:MediaWiki:SeeMoreActivityButton/code.js', 'u:dev:MediaWiki:RecentChangesMultiple/code.2.js', 'u:kocka:MediaWiki:AjaxCommentDelete/code.js', 'u:kocka:MediaWiki:AjaxThreadDelete/code.js', 'u:kocka:User:KockaAdmiralac/UnhideUserMasthead.javascript', 'u:admintools:MediaWiki:Common.js/Maintenance.js', 'u:noreply:MediaWiki:HideWikiaLogs.js', 'u:noreply:MediaWiki:FileUsage.js', 'u:dev:MediaWiki:WhatLinksHere/code.js', 'u:dev:MediaWiki:MultipleFileDelete/code.js', 'u:dev:MediaWiki:MassEdit/code.js', 'u:dev:MediaWiki:PurgeButton/code.js', 'u:dev:MediaWiki:AjaxBatchDelete.js', 'u:dev:MediaWiki:HistoryKey/code.js', ] }); // /*    if ($('#t-mc').length)        return;    // Replace \    var FormMC = '\    <form method="" name="" class="WikiaForm "> \       \           Mode: \               <select id="select-mc"> \                 Add \                 Remove \               \           \           Category: \               <input type="text" id="category-name" value="" /> \           Matching: \               \               <label for="normal-removal"><input type="radio" id="normal-removal" name="mass-categorization-removal" value="1" checked="checked"/>General (does not account for piped categories) \	       \               <label for="broad-removal"><input type="radio" id="broad-removal" name="mass-categorization-removal"/ value="2">Broad (also match possible further characters of the specified category e.g. Foo and Foo123, but takes care of pipes) \           \           \               <label for="no-include"><input type="checkbox" id="no-include" name="mass-categorization-noinclude"/ value="1">Do not include in transclusion (for templates) \ \          \           Put the name of each page you want to categorize on a separate line. \              <textarea style="height: 20em; width: 80%;" id="text-categorization"/> \ \      <div id="text-error-output" style="height:10em; width: 80%; margin: 5px auto 0px auto; color: #000; background-color: #ffbfbf; height: 150px; border: 1px solid black; font-weight: bold; overflow: scroll">Any errors encountered will appear below  \ ',   delay = window.massCategorizationDelay || 500; //Support for Monobook if (mw.config.get('skin') === 'monobook') { mw.util.addPortletLink('p-tb', '#', 'Mass Categorization', 't-mc'); } else { $('#my-tools-menu').prepend(' Mass Categorization</a></li>'); }   document.getElementById('t-mc').addEventListener('click', function  {        $.showCustomModal('Mass Categorization', FormMC, { id: 'form-categorization', width: 500, buttons: [{ message: 'Cancel', handler: function { $('#form-categorization').closeModal; }           }, {                message: 'Add category contents', defaultButton: true, handler: function { addCategoryContents; }           }, {                id: 'start-button', message: 'Initiate', defaultButton: true, handler: function { init; }           }]        });    });    function addCategoryContents { var category = prompt('Please enter the category name (no category prefix):').replace('_',' '); new mw.Api.get({           action: 'query',            list: 'categorymembers',            cmtitle: "Category:"+category,            cmlimit: 5000        }) .done(function(d) {           if (!d.error) {                var data = d.query;                if (data.categorymembers) {                    for (var i in data.categorymembers) {                        $('#text-categorization').append(data.categorymembers[i].title+'\n');                    }                }                else {                    $('#text-error-output').append(category + ' does not exist!\n');                }            }            else {                $('#text-error-output').append('Failed to get contents of '+ category +' : '+ d.error.code +' ');            }        }) .fail(function {           $('#text-error-output').append('Failed to get contents of '+ category +'! ');       });    }     function init { var catName = document.getElementById('category-name').value, txt = document.getElementById('text-categorization'), pages = txt.value.split('\n'), page = pages[0]; if (!catName) { alert('Please enter the category name!'); return; }       document.getElementById('start-button').setAttribute('disabled','disabled'); if (!page) { document.getElementById('start-button').removeAttribute("disabled"); $.showCustomModal('Finished!', 'Nothing left to do, or next line is blank.', {               id: 'form-complete',                width: 200,                buttons: [{                    message: 'Close',                    defaultButton: true,                    handler: function {                        $('#form-complete').closeModal;                    }                }]            }); }        else { categorize(page,catName); }       pages = pages.slice(1,pages.length); txt.value = pages.join('\n'); }   function categorize(pageToCat,cat) { var actionVal = $('#select-mc').val; if (actionVal == 1) { //add category new mw.Api.get({               format: 'json',                action: 'query',                titles: pageToCat,                prop: 'categories'            }) .done(function(d) {               var pages = d.query.pages;                    for (var page in pages) {                    var mPage = pages[page],                        knownCats = [];                    if (mPage.categories) {                        for (var i = 0; i < mPage.categories.length; i++) {                            knownCats.push(mPage.categories[i].title);                        }                    }                }                cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1);                if (knownCats.indexOf(cat) === -1 || knownCats === 'undefined') {                    var sPrefix="";                    var sSuffix = "";                    if ($('input[name=mass-categorization-noinclude]').prop('checked')){                    //    sPrefix =" \n";                    //    sSuffix = "<\/noinclude>";                        sPrefix ="\n--"; sSuffix = ""; }                   var config = { format: 'json', action: 'edit', title: pageToCat, summary: 'Adding categories', nocreate: '', appendtext: sPrefix + '['+'['+cat+']]'+ sSuffix, bot: true, token: mw.user.tokens.get('editToken') };                   if (mw.config.get("wgUserGroups").join(' ').indexOf('bot') == -1) delete config.bot; $.ajax({                       url: mw.util.wikiScript('api'),                        data: config,                        dataType: 'json',                        type: 'POST',                        success: function(d) {                            if (!d.error) {                                console.log('Category successfully added to '+pageToCat+'!');                            }                             else {                                console.log('Failed to add category to '+pageToCat+': '+ d.error.code);                                $('#text-error-output').append('Failed to add category to '+pageToCat+': '+ d.error.code +' ');                            }                        },                        error: function {                            console.log('Failed to add category to '+pageToCat+'!');                            $('#text-error-output').append('Failed to add category to '+pageToCat+'! ');                       }                    });                }                else { console.log(pageToCat+ ' already has the category '+cat.substring(9)+' or an error was encountered. '+pageToCat+' has been skipped.'); $('#text-error-output').append(pageToCat+ ' already has the category '+cat.substring(9)+' or an error was encountered. '+pageToCat+' has been skipped. '); }           })            .fail(function { console.log('Category check failed for '+pageToCat+'! It has been skipped.'); $('#text-error-output').append('Category check failed for '+pageToCat+'! It has been skipped. '); });       }        if (actionVal == 2) {            //remove category            //get page contents            new mw.Api.get({ action: 'query', prop: 'revisions', rvprop: 'content', titles: pageToCat })           .done(function(d) { if (!d.error) { for (var i in d.query.pages) { if (d.query.pages[i].revisions) { var content = d.query.pages[i].revisions[0]["*"]; }                       else { $('#text-error-output').append('Page '+pageToCat+' does not exist! '); return; }                   }                             //remove old category var regex = new RegExp ("\\[\\[Category:"+cat+"\\]\\]","gi"); var sRegEx = "\\[\\[Category:"+cat+"\\|?.*?\\]\\]"; if ($('input[name=mass-categorization-removal]:checked').val == 2){ regex = new RegExp (sRegEx,"gi"); }                   if ($('input[name=mass-categorization-noinclude]').prop('checked')){ regex = new RegExp ("\\<noinclude\\>\\s*"+sRegEx+"\\s*\\<\/noinclude\\>","gi"); }                   var changedContent = content.replace(regex,''); cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1); //don't submit if new and old contents are equal (no category found) if (changedContent.valueOf == content.valueOf) { $('#text-error-output').append('Category not found on '+pageToCat+'! '); return; }                   //submit new page var config = { format: 'json', action: 'edit', watchlist: 'nochange', title: pageToCat, summary: 'Removing category ['+'['+cat+'|'+cat.substring(9)+']] ', nocreate: '', text: changedContent, bot: true, token: mw.user.tokens.get('editToken') };                   if (mw.config.get("wgUserGroups").join(' ').indexOf('bot') == -1) delete config.bot; $.ajax({                       url: mw.util.wikiScript('api'),                        data: config,                        dataType: 'json',                        type: 'POST',                        success: function(d) {                            if (!d.error) {                                console.log('Category successfully removed from '+pageToCat+'!');                            }                             else {                                console.log('Failed to remove category from '+pageToCat+': '+ d.error.code);                                $('#text-error-output').append('Failed to remove category from '+pageToCat+': '+ d.error.code +' ');                            }                        },                        error: function {                            console.log('Failed to remove category from '+pageToCat+'!'); $('#text-error-output').append('Failed to remove category from '+pageToCat+'! '); }                   });                }                else {                    console.log('Failed to get contents of page: '+ d.error.code);                    $('#text-error-output').append('Failed to get contents of '+pageToCat+': '+ d.error.code +' ');                }            }) .fail(function {               console.log('Failed to get contents of '+pageToCat+'!');                $('#text-error-output').append('Failed to get contents of '+pageToCat+'! ');           });        }        /* currently broken if (actionVal == 3) { //replace category var newCat = prompt('Please enter the replacement category name (no category prefix):'); if (!newCat) { alert('No name entered!'); document.getElementById('start-button').removeAttribute("disabled"); return; }     //get page contents new mw.Api.get({     action: 'query',      prop: 'revisions',      rvprop: 'content',      titles: pageToCat      }) .done(function(d) {	if (!d.error) {         for (var i in d.query.pages) {            if (d.query.pages[i].revisions) {	       var content = d.query.pages[i].revisions[0]["*"];            }            else {	      $('#text-error-output').append('Page '+pageToCat+' does not exist! ');	     return;            }          }         	  //replace old category          var regex = new RegExp ("\\[\\[Category:"+cat+"\\]\\]","gi");          if ($('input[name=mass-categorization-removal]:checked').val == 2)            regex = new RegExp ("\\[\\[Category:"+cat+"\\|?.*?\\]\\]","gi");          newCat = 'Category:'+ newCat.charAt(0).toUpperCase + newCat.substring(1);	  var changedContent = content.replace(regex,+newCat+);	  cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1);	  //don't submit if new and old contents are equal (no category found)	  if (changedContent.valueOf == content.valueOf) {	    $('#text-error-output').append('Category not found on '+pageToCat+'! ');	   return;	  }	  //submit new page          var config = {            format: 'json',            action: 'edit',            watchlist: 'nochange',            title: pageToCat,            summary: 'Replacing category ['+'['+cat+'|'+cat.substring(9)+']] with ['+'['+newCat+'|'+newCat.substring(9)+']]',            nocreate: '',	    text: changedContent,	    bot: true,            token: mw.user.tokens.get('editToken')          };          if (mw.config.get("wgUserGroups").indexOf('bot') == -1)            delete config.bot;          $.ajax({ url: mw.util.wikiScript('api'), data: config, dataType: 'json', type: 'POST', success: function(d) { if (!d.error) { console.log('Category successfully replaced on '+pageToCat+'!'); } 	       else { console.log('Failed to remove category from '+pageToCat+': '+ d.error.code); $('#text-error-output').append('Failed to replace category on '+pageToCat+': '+ d.error.code +' '); }             },              error: function { console.log('Failed to remove category from '+pageToCat+'!'); $('#text-error-output').append('Failed to replace category on '+pageToCat+'! '); }         });	}	else {	  console.log('Failed to get contents of page: '+ d.error.code);	  $('#text-error-output').append('Failed to get contents of '+pageToCat+': '+ d.error.code +' ');        }     }) .fail(function {      console.log('Failed to get contents of '+pageToCat+'!');       $('#text-error-output').append('Failed to get contents of '+pageToCat+'! ');    });    }   */        setTimeout(init,delay); } }) (this.jQuery, this.mediaWiki);// /*    if ($('#t-mc').length)        return;    // Replace \    var FormMC = '\    <form method="" name="" class="WikiaForm "> \       \           Mode: \               <select id="select-mc"> \                 Add \                 Remove \               \           \           Category: \               <input type="text" id="category-name" value="" /> \           Matching: \               \               <label for="normal-removal"><input type="radio" id="normal-removal" name="mass-categorization-removal" value="1" checked="checked"/>General (does not account for piped categories) \	       \               <label for="broad-removal"><input type="radio" id="broad-removal" name="mass-categorization-removal"/ value="2">Broad (also match possible further characters of the specified category e.g. Foo and Foo123, but takes care of pipes) \           \ \              <label for="no-include"><input type="checkbox" id="no-include" name="mass-categorization-noinclude"/ value="1">Do not include in transclusion (for templates) \ \          \           Put the name of each page you want to categorize on a separate line. \              <textarea style="height: 20em; width: 80%;" id="text-categorization"/> \ \      <div id="text-error-output" style="height:10em; width: 80%; margin: 5px auto 0px auto; color: #000; background-color: #ffbfbf; height: 150px; border: 1px solid black; font-weight: bold; overflow: scroll">Any errors encountered will appear below  \ ',   delay = window.massCategorizationDelay || 500; //Support for Monobook if (mw.config.get('skin') === 'monobook') { mw.util.addPortletLink('p-tb', '#', 'Mass Categorization', 't-mc'); } else { $('#my-tools-menu').prepend(' Mass Categorization</a></li>'); }   document.getElementById('t-mc').addEventListener('click', function  {        $.showCustomModal('Mass Categorization', FormMC, { id: 'form-categorization', width: 500, buttons: [{ message: 'Cancel', handler: function { $('#form-categorization').closeModal; }           }, {                message: 'Add category contents', defaultButton: true, handler: function { addCategoryContents; }           }, {                id: 'start-button', message: 'Initiate', defaultButton: true, handler: function { init; }           }]        });    });    function addCategoryContents { var category = prompt('Please enter the category name (no category prefix):').replace('_',' '); new mw.Api.get({           action: 'query',            list: 'categorymembers',            cmtitle: "Category:"+category,            cmlimit: 5000        }) .done(function(d) {           if (!d.error) {                var data = d.query;                if (data.categorymembers) {                    for (var i in data.categorymembers) {                        $('#text-categorization').append(data.categorymembers[i].title+'\n');                    }                }                else {                    $('#text-error-output').append(category + ' does not exist!\n');                }            }            else {                $('#text-error-output').append('Failed to get contents of '+ category +' : '+ d.error.code +' ');            }        }) .fail(function {           $('#text-error-output').append('Failed to get contents of '+ category +'! ');       });    }     function init { var catName = document.getElementById('category-name').value, txt = document.getElementById('text-categorization'), pages = txt.value.split('\n'), page = pages[0]; if (!catName) { alert('Please enter the category name!'); return; }       document.getElementById('start-button').setAttribute('disabled','disabled'); if (!page) { document.getElementById('start-button').removeAttribute("disabled"); $.showCustomModal('Finished!', 'Nothing left to do, or next line is blank.', {               id: 'form-complete',                width: 200,                buttons: [{                    message: 'Close',                    defaultButton: true,                    handler: function {                        $('#form-complete').closeModal;                    }                }]            }); }        else { categorize(page,catName); }       pages = pages.slice(1,pages.length); txt.value = pages.join('\n'); }   function categorize(pageToCat,cat) { var actionVal = $('#select-mc').val; if (actionVal == 1) { //add category new mw.Api.get({               format: 'json',                action: 'query',                titles: pageToCat,                prop: 'categories'            }) .done(function(d) {               var pages = d.query.pages;                    for (var page in pages) {                    var mPage = pages[page],                        knownCats = [];                    if (mPage.categories) {                        for (var i = 0; i < mPage.categories.length; i++) {                            knownCats.push(mPage.categories[i].title);                        }                    }                }                cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1);                if (knownCats.indexOf(cat) === -1 || knownCats === 'undefined') {                    var sPrefix="";                    var sSuffix = "";                    if ($('input[name=mass-categorization-noinclude]').prop('checked')){                    //    sPrefix =" \n";                    //    sSuffix = "<\/noinclude>";                        sPrefix ="\n--"; sSuffix = ""; }                   var config = { format: 'json', action: 'edit', title: pageToCat, summary: 'Adding category', nocreate: '', appendtext: sPrefix + '['+'['+cat+']]'+ sSuffix, bot: true, token: mw.user.tokens.get('editToken') };                   if (mw.config.get("wgUserGroups").join(' ').indexOf('bot') == -1) delete config.bot; $.ajax({                       url: mw.util.wikiScript('api'),                        data: config,                        dataType: 'json',                        type: 'POST',                        success: function(d) {                            if (!d.error) {                                console.log('Category successfully added to '+pageToCat+'!');                            }                             else {                                console.log('Failed to add category to '+pageToCat+': '+ d.error.code);                                $('#text-error-output').append('Failed to add category to '+pageToCat+': '+ d.error.code +' ');                            }                        },                        error: function {                            console.log('Failed to add category to '+pageToCat+'!');                            $('#text-error-output').append('Failed to add category to '+pageToCat+'! ');                       }                    });                }                else { console.log(pageToCat+ ' already has the category '+cat.substring(9)+' or an error was encountered. '+pageToCat+' has been skipped.'); $('#text-error-output').append(pageToCat+ ' already has the category '+cat.substring(9)+' or an error was encountered. '+pageToCat+' has been skipped. '); }           })            .fail(function { console.log('Category check failed for '+pageToCat+'! It has been skipped.'); $('#text-error-output').append('Category check failed for '+pageToCat+'! It has been skipped. '); });       }        if (actionVal == 2) {            //remove category            //get page contents            new mw.Api.get({ action: 'query', prop: 'revisions', rvprop: 'content', titles: pageToCat })           .done(function(d) { if (!d.error) { for (var i in d.query.pages) { if (d.query.pages[i].revisions) { var content = d.query.pages[i].revisions[0]["*"]; }                       else { $('#text-error-output').append('Page '+pageToCat+' does not exist! '); return; }                   }                             //remove old category var regex = new RegExp ("\\[\\[Category:"+cat+"\\]\\]","gi"); var sRegEx = "\\[\\[Category:"+cat+"\\|?.*?\\]\\]"; if ($('input[name=mass-categorization-removal]:checked').val == 2){ regex = new RegExp (sRegEx,"gi"); }                   if ($('input[name=mass-categorization-noinclude]').prop('checked')){ regex = new RegExp ("\\<noinclude\\>\\s*"+sRegEx+"\\s*\\<\/noinclude\\>","gi"); }                   var changedContent = content.replace(regex,''); cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1); //don't submit if new and old contents are equal (no category found) if (changedContent.valueOf == content.valueOf) { $('#text-error-output').append('Category not found on '+pageToCat+'! '); return; }                   //submit new page var config = { format: 'json', action: 'edit', watchlist: 'nochange', title: pageToCat, summary: 'Removing category ['+'['+cat+'|'+cat.substring(9)+']] ', nocreate: '', text: changedContent, bot: true, token: mw.user.tokens.get('editToken') };                   if (mw.config.get("wgUserGroups").join(' ').indexOf('bot') == -1) delete config.bot; $.ajax({                       url: mw.util.wikiScript('api'),                        data: config,                        dataType: 'json',                        type: 'POST',                        success: function(d) {                            if (!d.error) {                                console.log('Category successfully removed from '+pageToCat+'!');                            }                             else {                                console.log('Failed to remove category from '+pageToCat+': '+ d.error.code);                                $('#text-error-output').append('Failed to remove category from '+pageToCat+': '+ d.error.code +' ');                            }                        },                        error: function {                            console.log('Failed to remove category from '+pageToCat+'!'); $('#text-error-output').append('Failed to remove category from '+pageToCat+'! '); }                   });                }                else {                    console.log('Failed to get contents of page: '+ d.error.code);                    $('#text-error-output').append('Failed to get contents of '+pageToCat+': '+ d.error.code +' ');                }            }) .fail(function {               console.log('Failed to get contents of '+pageToCat+'!');                $('#text-error-output').append('Failed to get contents of '+pageToCat+'! ');           });        }        /* currently broken if (actionVal == 3) { //replace category var newCat = prompt('Please enter the replacement category name (no category prefix):'); if (!newCat) { alert('No name entered!'); document.getElementById('start-button').removeAttribute("disabled"); return; }     //get page contents new mw.Api.get({     action: 'query',      prop: 'revisions',      rvprop: 'content',      titles: pageToCat      }) .done(function(d) {	if (!d.error) {         for (var i in d.query.pages) {            if (d.query.pages[i].revisions) {	       var content = d.query.pages[i].revisions[0]["*"];            }            else {	      $('#text-error-output').append('Page '+pageToCat+' does not exist! ');	     return;            }          }         	  //replace old category          var regex = new RegExp ("\\[\\[Category:"+cat+"\\]\\]","gi");          if ($('input[name=mass-categorization-removal]:checked').val == 2)            regex = new RegExp ("\\[\\[Category:"+cat+"\\|?.*?\\]\\]","gi");          newCat = 'Category:'+ newCat.charAt(0).toUpperCase + newCat.substring(1);	  var changedContent = content.replace(regex,+newCat+);	  cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1);	  //don't submit if new and old contents are equal (no category found)	  if (changedContent.valueOf == content.valueOf) {	    $('#text-error-output').append('Category not found on '+pageToCat+'! ');	   return;	  }	  //submit new page          var config = {            format: 'json',            action: 'edit',            watchlist: 'nochange',            title: pageToCat,            summary: 'Replacing category ['+'['+cat+'|'+cat.substring(9)+']] with ['+'['+newCat+'|'+newCat.substring(9)+']]',            nocreate: '',	    text: changedContent,	    bot: true,            token: mw.user.tokens.get('editToken')          };          if (mw.config.get("wgUserGroups").indexOf('bot') == -1)            delete config.bot;          $.ajax({ url: mw.util.wikiScript('api'), data: config, dataType: 'json', type: 'POST', success: function(d) { if (!d.error) { console.log('Category successfully replaced on '+pageToCat+'!'); } 	       else { console.log('Failed to remove category from '+pageToCat+': '+ d.error.code); $('#text-error-output').append('Failed to replace category on '+pageToCat+': '+ d.error.code +' '); }             },              error: function { console.log('Failed to remove category from '+pageToCat+'!'); $('#text-error-output').append('Failed to replace category on '+pageToCat+'! '); }         });	}	else {	  console.log('Failed to get contents of page: '+ d.error.code);	  $('#text-error-output').append('Failed to get contents of '+pageToCat+': '+ d.error.code +' ');        }     }) .fail(function {      console.log('Failed to get contents of '+pageToCat+'!');       $('#text-error-output').append('Failed to get contents of '+pageToCat+'! ');    });    }   */        setTimeout(init,delay); } }) (this.jQuery, this.mediaWiki); /* * @name:              Rollback * @description:        Perform rollbacks without needing to be in the usergroup * @author:             Ozank Cx <dev.fandom.com/wiki/User:Ozank_Cx> *                      Cleanup/+i18n by Count of Howard <dev.fandom.com/wiki/User:Count_of_Howard> */
 * Mass Categorization
 * @description (De)Categorize listed multiple pages.
 * @author Ozuzanna
 * @TODO fix replace
 * Added option for (Dessamator)
 * (function($, mw) {
 * Mass Categorization
 * @description (De)Categorize listed multiple pages.
 * @author Ozuzanna
 * @TODO fix replace
 * Added option for (Dessamator)
 * (function($, mw) {

(function {   if ($('.mw-rollback-link').length || $('.mw-custom-rollback-link').length || window.RollbackWikiDisable) {        return;    }

var config = mw.config.get([       'wgAction',        'wgPageName',        'wgContentLanguage',        'wgCanonicalSpecialPageName'    ]), i18n = { 'en': { title: '"Rollback" reverts edit(s) to this page of the last contributor in one click', failGeneral: 'Unable to rollback', failRevisions: 'Failed to get revisions', failContent: 'Failed to get page content', failEditor: 'No different editor found', failPublish: 'Failed to publish edit', success: 'Rollback successful', rollback: 'rollback', summary1: 'Reverted edits by', summary2: 'to last version by', script: 'script', talk: 'talk', block: 'block' },       'be': { title: 'Адкат дазваляе прыбраць змены, занесеныя апошнім рэдактарам, у адзін клік', failGeneral: 'Не ўдалося адкаціць', failRevisions: 'Не ўдалося зрабіць змены', failContent: 'Не ўдалося атрымаць змесціва старонкі', failEditor: 'Рэдактар не знойдзены', failPublish: 'Не ўдалося апублікаваць змены', success: 'Адкат паспяхова завершаны', rollback: 'адкат', summary1: 'Адкочаныя змены:', summary2: 'да апошняй версіі ад', script: 'скрыпт', talk: 'сцяна', block: 'заблакаваць' },       'de': { title: 'Macht alle letzten Änderungen der Seite, die vom gleichen Benutzer vorgenommen worden sind, durch einen einzigen Klick rückgängig.', failGeneral: 'Zurücksetzen ist nicht möglich', failRevisions: 'Versionsgeschichte konnte nicht geladen werden', failContent: 'Seiteninhalt konnte nicht geladen werden', failEditor: 'Es wurde kein anderer Bearbeiter gefunden', failPublish: 'Bearbeitung konnte nicht veröffentlicht werden', success: 'Erfolgreich zurückgesetzt', rollback: 'Zurücksetzen', summary1: 'Zurücksetzen der Änderungen durch', summary2: 'zu der letzten Version von', script: 'Skript', talk: 'Diskussion', block: 'Sperren' },       'es': { title: '«Revertir» revierte todas las ediciones del último usuario con un solo clic', failGeneral: 'No se ha podido revertir', failRevisions: 'Error al obtener revisiones', failContent: 'Error al obtener contenido de la página', failEditor: 'No se han encontrado editores diferentes', failPublish: 'Error al publicar la edición', success: 'Revertido correctamente', rollback: 'revertir', summary1: 'Revertidos los cambios de ', summary2: 'a la última edición de', script: 'script', talk: 'disc.', block: 'bloquear' },       'fr': { title: 'Rollback révoque la/le(s) modification(s) du dernier contributeur de cette page en un clic', failGeneral: 'Impossible de révoquer', failRevisions: 'Échec de l\'obtention des révisions', failContent: 'Échec de l\'obtention du contenu de la page', failEditor: 'Aucun éditeur différent n\'a été trouvé', failPublish: 'Échec de la publication de la modification', success: 'Révocation(s) réussie(s) !', rollback: 'révocation', summary1: 'Révocation des modifications de', summary2: 'à la dernière version de', script: 'script', talk: 'discussion', block: 'bloquer' },       'it': { title: '"Rollback" annulla le modifiche a questa pagina dell\'ultimo contributore con un solo clic', failGeneral: 'Impossibile eseguire il rollback', failRevisions: 'Impossibile ottenere le modifiche', failContent: 'Impossibile ottenere il contenuto della pagina', failEditor: 'Nessun editor diverso trovato', failPublish: 'Impossibile pubblicare la modifica', success: 'Rollback eseguito correttamente', rollback: 'rollback', summary1: 'Annullate le modifiche di', summary2: ', riportata alla versione precedente di', script: 'script', talk: 'discussione', block: 'blocca' },       'ko': { title: '롤백은 한 클릭안에 편집들을 전 사용자의 개정으로 되돌립니다', failGeneral: '롤백을 할수가 없습니다', failRevisions: '수정을 찾을수가 없었습니다', failContent: '패이지 내용을 찾을수가 없었습니다', failEditor: '다른 편집자를 찾을수가 없었습니다', failPublish: '편집을 올릴수가 없었습니다', success: '롤백 성공', rollback: '롤백', summary1: '사용자의 편집들이 되돌려졌습니다:', summary2: '이 사용자의 개정으로:', script: '스크립트', talk: '톡', block: '블록' },       'pl': { title: 'Rollback pozwala cofać edycje do wersji poprzedniego autora jednym kliknięciem', failGeneral: 'Nie udało się zrewertować edycji', failRevisions: 'Nie udało się pobrać wersji', failContent: 'Nie udało się pobrać zawartości strony', failEditor: 'Strona ma tylko jednego edytora', failPublish: 'Nie udało się opublikować edycji', success: 'Rewert udany', rollback: 'rewert', summary1: 'Wycofano ostatnie edycje użytkownika', summary2: 'do poprzedniej wersji autorstwa', script: 'skrypt', talk: 'dyskusja', block: 'blokada' },       'ru': { title: 'Откат позволяет убрать изменения, внесённые последним редактором, в один клик', failGeneral: 'Не удалось откатить', failRevisions: 'Не удалось сделать изменения', failContent: 'Не удалось получить содержимое страницы', failEditor: 'Редактор не найден', failPublish: 'Не удалось опубликовать изменения', success: 'Откат успешно завершён', rollback: 'откатить', summary1: 'Откаченные изменения:', summary2: 'к последней версии от', script: 'скрипт', talk: 'стена', block: 'заблокировать' },       'tr': { title: 'Geri alma işlemi, son katılımcının bu sayfasını tek bir tıklamayla değiştirir', failGeneral: 'Geri alınamıyor', failRevisions: 'Düzeltmeler alınamadı', failContent: 'Sayfa içeriği alınamadı', failEditor: 'Farklı bir editör bulunamadı', failPublish: 'Düzenleme yayınlanamadı', success: 'Geri alma başarılı', rollback: 'rollback', summary1: 'Yapılan düzenlemeler', summary2: 'son versiyona göre', script: 'komut', talk: 'tartışma', block: 'engelle' },       'uk': { title: 'Відкат дозволяє прибрати зміни, внесені останнім редактором, в один клік', failGeneral: 'Не вдалося відкотити', failRevisions: 'Не вдалося зробити зміни', failContent: 'Не вдалося отримати вміст сторінки', failEditor: 'Редактор не знайдено', failPublish: 'Не вдалося опублікувати зміни', success: 'Відкат успішно завершено', rollback: 'відкинути', summary1: 'Відкочені зміни:', summary2: 'до останньої версії від', script: 'скрипт', talk: 'обговорення', block: 'заблокувати' },       'zh': { title: '回退能一键恢复本页面最后一位编辑者的贡献', failGeneral: '无法回退', failRevisions: '无法获取修订版本', failContent: '无法获取页面内容', failEditor: '无法找到另一位编辑者', failPublish: '发布编辑失败', success: '回退成功', rollback: '回退', summary1: '已恢复由', summary2: '的编辑至最后一个修订版本由', script: '脚本', talk: '讨论', block: '封禁' },       'zh-hant': { title: '回退能一鍵恢復本頁面最後一位編輯者的貢獻', failGeneral: '無法回退', failRevisions: '無法讀取修訂版本', failContent: '無法讀取頁面內容', failEditor: '無法找到另一位編輯者', failPublish: '發布編輯失敗', success: '回退成功', rollback: '回退', summary1: '已恢復由', summary2: '的編輯至最後一個修訂版本由', script: '腳本', talk: '討論', block: '封禁' }   },    lang = i18n[config.wgContentLanguage] || i18n[config.wgContentLanguage.split('-')[0]] || i18n.en;

function init { var rollbackLinkParams = { style: 'cursor: pointer', title: lang.title };

if (           config.wgAction === 'history' &&            $('#pagehistory li').length > 1        ) { rollbackLinkParams['data-id'] = config.wgPageName; $('#pagehistory li:first .mw-history-undo a').before(               $(' ', { class: 'mw-custom-rollback-link' }).html( buildElement('a', lang.rollback, rollbackLinkParams) + ' | ' )           );        } else if (            config.wgCanonicalSpecialPageName === 'Contributions'        ) { rollbackLinkParams['data-id'] = $('#mw-content-text ul').find('a:first').attr('title'); $('#mw-content-text ul').find('li').each(               function {                    if ($(this).find('.mw-uctop').length) {                        $(this).append( $(' ', {                               class: 'mw-custom-rollback-link'                            }).html(                                '[' + buildElement('a', lang.rollback, rollbackLinkParams) + ']'                            ) );                   }                }            );        } else if (            $('#differences-nextlink').length === 0 &&            ( $.getUrlVar('diff') || $.getUrlVar('oldid') )       ) {            rollbackLinkParams['data-id'] = config.wgPageName; $('.mw-usertoollinks:last').after(               '    ' +                '[' + buildElement('a', lang.rollback, rollbackLinkParams) + '] '            ); }

$('.mw-custom-rollback-link a').click(           function {                getRevisionIdAndContent($(this).attr('data-id'), handleData);                $(this).parent.remove;            }        ); }

function buildElement(tag, html, attrs) { if (typeof(html) !== 'string') { attrs = html; html = null; }

var h = '<' + tag; for (var attr in attrs) { if (attrs[attr] === false) { continue; }

h += ' ' + attr + '="' + mw.html.escape(attrs[attr]) + '"'; }       return h += html ? ">" + mw.html.escape(html) + "</" + tag + ">" : "/>"; }

function getRevisionIdAndContent(title, callback) { new mw.Api.get({           action: 'query',            prop: 'revisions',            titles: title,            rvprop: 'user|ids',            rvlimit: 500,            cb: new Date.getTime        }).done(            function(d) {                if (!d.error) {                    callback(title, d);                } else {                    new BannerNotification( lang.failGeneral + ' (' + lang.failRevisions + '): ' + d.error.code, 'error' ).show;               }            }        ).fail(            function {                new BannerNotification( lang.failGeneral + ' (' + lang.failRevisions + ')', 'error' ).show;           }        ); }

function handleData(title, data) { var revisions;

for (var i in data.query.pages) { revisions = data.query.pages[i].revisions; }

var currentUser = revisions[0].user, lastUser, revId;

for (var i in revisions) { if (revisions[i].user != currentUser) { lastUser = revisions[i].user; revId = revisions[i].revid; break; }       }

if (lastUser) { new mw.Api.get({               action: 'query',                prop: 'revisions',                rvprop: 'content',                revids: revId,                cb: new Date.getTime            }).done(                function(d) {                    if (!d.error) {                        var content = "";                        for (var i in d.query.pages) {                            if (d.query.pages[i].revisions) {                                content = d.query.pages[i].revisions[0]["*"];                            }                        }                        performRollback(title, content, currentUser, lastUser);                    } else {                        new BannerNotification( lang.failGeneral + ' (' + lang.failContent + '): ' + d.error.code,'error' ).show;                   }                }            ).fail(                function {                    new BannerNotification( lang.failGeneral + ' (' + lang.failContent + ')','error' ).show;               }            ); } else { new BannerNotification(               lang.failGeneral + ' (' + lang.failEditor + ')','error'            ).show; }   }

function performRollback(page, text, user, user2) { var summary = lang.summary1 + ' ' + user + ' (' + lang.talk +               ' | ' + lang.block + ') ' + lang.summary2 + user2 +'';

if (summary.length > 150) { summary = lang.summary1 + ' ' + user + ' (' + lang.talk +               ' | ' + lang.block + ') ' + lang.summary2 + user2 +''; }

new mw.Api.post({           action: 'edit',            title: page,            text: text,            summary: summary,            token: mw.user.tokens.values.editToken        }).done(            function(d) {                if (!d.error) {                    new BannerNotification( lang.success + '!', 'confirm' ).show;               } else {                    new BannerNotification( lang.failGeneral + ' (' + lang.failPublish + '): ' + d.error.code,'error' ).show;               }            }        ).fail(            function {                new BannerNotification( lang.failGeneral + ' (' + lang.failPublish + ')', 'error' ).show;           }        ); }

init; }); // 11:03, November 17, 2014 (UTC) //