User:Animum/moveRV-severe.js

Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
//Imported from enwiki

importScript('User:Animum/urlparameters.js');
importScript('User:Animum/formatresponse.js');
 
function zeroPad(str) {
    return ("0" + str).slice(-2);
}
 
var isSysop = /sysop/.test(wgUserGroups);
 
function revertmoves() { //An _EXTENSIVELY_ modified version of Voice of All's move-reversion script.
    document.getElementById("contentSub").innerHTML += "<br /><b>Working... (this may take a while)</b>";
    var l = document.getElementById('bodyContent').getElementsByTagName('li');
    var NEXT_INDEX = 0;
    var completedMoves = 0;
    var completedDeletions = 0;
    for (var i=NEXT_INDEX;i<l.length;i++) {
            var li_a = l[i].getElementsByTagName('a');
            for(k=0;k<li_a.length;k++) { //Here to look good.
                    var article  = li_a[(isSysop ? 4 : 3)].href.split("title=")[1].split("&")[0];
                    var article2 = li_a[(isSysop ? 5 : 4)].href.replace(/.*?(\/wiki\/|\/index\.php\?title\=)/g, "").split("&")[0];
 
                    var req = sajax_init_object();
                    req.open("GET", wgScriptPath + "/api.php?format=json&action=query&prop=revisions&titles=" + article + "&rvprop=comment&limit=1", false);
                    req.send(null);
                    var pageInfo = formatResponse(eval("(" + req.responseText + ")"));
                    if(pageInfo.revisions != undefined) {
                      if(pageInfo.revisions[0].comment) {
                        if(pageInfo.revisions[0].comment.indexOf("moved [[" + article2.replace(/_/g, " ") + "]] to [[" + article.replace(/_/g, " ") + "]]") != -1) {
                            var shouldAbort = true; //Has already been reverted.
                        } else {
                            shouldAbort = false;
                        }
                      } else {
                        shouldAbort = false; //No comment means no move has been made.
                      }
                    } else {
                        shouldAbort = false; //If page doesn't exist, we don't want to move it.
                    }
                        var req = sajax_init_object();
                        req.open("GET", wgScriptPath + "/api.php?format=json&action=query&prop=revisions&titles=" + article2 + "&rvprop=comment&limit=1", false);
                        req.send(null);
                            var pageInfo = formatResponse(eval("(" + req.responseText + ")"));
                            if(pageInfo.revisions == undefined) {
                                 shouldAbort = true; //Page to move doesn't exist.
                            }
                        var req = sajax_init_object();
                        req.open("GET", wgScriptPath + "/api.php?format=json&action=query&prop=info&intoken=move|delete&titles=" + article2, false);
                        req.send(null);
                            var summary = "Script-assisted page-move revert.";
                            var info = formatResponse(eval("(" + req.responseText + ")"));
                            var edittoken = info.movetoken;
                            var deletetoken = info.deletetoken;
              	            var postdata = "wpOldTitle=" + article2
                                         + "&wpNewTitle=" + article
                                         + "&wpReason=" + encodeURIComponent(summary)
                                         + "&wpMovetalk=0"
                                         + "&wpEditToken=" + encodeURIComponent(edittoken)
                                         + "&wpMove=Move+page"
                                         + "&wpConfirm=1";
                        var req = sajax_init_object();
                        req.open("POST", wgScriptPath + "/index.php?title=Special:MovePage&action=submit", false);
                        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        req.setRequestHeader("Content-length", postdata.length);     
                        if(shouldAbort == false) { //If nobody else has already reverted, we do                   
                            req.send(postdata);
 
                            var dt = new Date();
                            var timestamp = dt.getUTCFullYear() + zeroPad(dt.getUTCMonth() + 1) + zeroPad(dt.getUTCDate()) + zeroPad(dt.getUTCHours()) + zeroPad(dt.getUTCMinutes()) + zeroPad(dt.getUTCSeconds());
 
                            var div = document.createElement("div");
                            div.id = "completedMoveCount";
                            document.getElementById("contentSub").appendChild(div);
 
                            var req = sajax_init_object();
                            req.open("GET", wgScriptPath + "/api.php?format=json&action=query&list=logevents&letype=move&leuser=" + wgUserName + "&letitle=" + unescape(article2) + "&lelimit=1&ledir=newer&lestart=" + timestamp, false);
                            req.send(null);
                            if(eval("(" + req.responseText + ")").query.logevents) {
                                if(eval("(" + req.responseText + ")").query.logevents[0].user == wgUserName && eval("(" + req.responseText + ")").query.logevents[0].comment.indexOf(summary) != -1) {
 
                                    if(isSysop) {
                                        var delsummary = "Cleanup of redirects created from page-move vandalism.";
                                        var postdata = "wpReason=" + encodeURIComponent(delsummary)
                                                     + "&wpEditToken=" + encodeURIComponent(deletetoken);
                                        var req = sajax_init_object();
                                        req.open("POST", wgScript + "?title=" + article2 + "&action=delete", false);
                                        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                                        req.setRequestHeader("Content-length", postdata.length);
                                        req.send(postdata);
                                    }
                                    completedMoves = completedMoves+1;
                                    document.getElementById("completedMoveCount").innerHTML = "<b>" + completedMoves + (completedMoves == 1 ? " move " + (isSysop ? "and deletion has" : "has") : " moves " + (isSysop ? "and deletions have" : "have")) + " been completed.</b>";
                                }
                            }
                        }
                NEXT_INDEX = NEXT_INDEX+1;
                break;
            }
    }
    document.getElementById("contentSub").innerHTML += "<br /><b>Cleanup finished.</b>"; //Done.
    return;
}
 
function isProtected(page) {
  var req = sajax_init_object();
  req.open("GET", wgScriptPath + "/api.php?action=query&prop=info&inprop=protection&intoken=protect&titles=" + page + "&format=json", false);
  req.send(null);
  var info = formatResponse(eval("(" + req.responseText + ")"));
  if(info.protection[0]) {
   var protection = info.protection;
   if((protection[0].type == "edit" && protection[0].level == "sysop" && protection[1].type == "move" && protection[1].level == "sysop") || (protection[0].type == "create" && protection[0].level == "sysop")) { //We don't want to protect *only* if the page is fully edit- or create-protected.
    return true;
   } else {
    return false;
   }
  } else {
    return false;
 }
}
 
function userHasProtected(page) {
    var req = sajax_init_object();
    req.open("GET", wgScriptPath + "/api.php?action=query&list=blocks&bkusers=" + page + "&format=json&bkprop=by", false);
    req.send(null);
    var info = eval("(" + req.responseText + ")");
    return (escape(info.query.blocks[0].by) == wgUserName ? true : false);
}
 
 
function protect(page) {
  if(isProtected(page)) {
   document.getElementById("contentSub").innerHTML += "<br /><b>Error:  Page is already fully protected. Defaulting to page-move reversion...</b>";
   revertmoves();
   return;
  }
  var req = sajax_init_object();
  req.open("GET", wgScriptPath + "/api.php?format=json&action=query&prop=info&intoken=protect&titles=" + encodeURIComponent(page), false);
  req.send(null);
  var info = formatResponse(eval("(" + req.responseText + ")"));
  var edittoken = info.protecttoken;
   var postdata = "mwProtect-level-edit=sysop"
               + "&mwProtect-level-move=sysop"
               + "&mwProtect-reason=" + encodeURIComponent("Preventative measure against vandalism")
               + "&mwProtect-level-create=sysop"
               + "&mwProtect-expiry=" + encodeURIComponent("1 month")
               + "&wpEditToken=" + encodeURIComponent(edittoken);
  var req = sajax_init_object();
  req.open("POST", wgScriptPath + "/index.php?title=" + encodeURIComponent(page) + "&action=protect", false);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  req.setRequestHeader("Content-length", postdata.length);
  req.send(postdata);
   if(userHasProtected(page)) {
    document.getElementById("contentSub").innerHTML += "<br /><b><a href=\"/wiki/" + encodeURIComponent(page) + "\">" + page + "</a> has been protected.</b>";
    revertmoves();
   } 
  return;
}
 
function isBlocked(name) {
  var req = sajax_init_object();
  req.open("GET", wgScriptPath + "/api.php?action=query&list=blocks&bkusers=" + name + "&format=json", false);
  req.send(null);
  var info = eval("(" + req.responseText + ")");
  return (info.query.blocks[0] ? true : false); 
}
 
function blockip(name) {
  // Safeguards against errors
  if(isBlocked(name)) {
    document.getElementById("contentSub").innerHTML += "<br /><br /><b>Error:  " + name + " is already blocked. Defaulting to protection...</b>";
    protect("User talk:" + name);
    return;
  }
  if(name == "undefined") {
     document.getElementById("contentSub").innerHTML += "<br /><br /><b>Error:  No valid username was given; please block manually.";
     return;
  }
  //If none of these safeguards have been triggered, continue.
  var req = sajax_init_object();
  req.open("GET", wgScriptPath + "/index.php?title=Special:BlockIP/" + name, false);
  req.send(null);
   document.getElementById("contentSub").innerHTML += "<br /><br />";   
  var duration = prompt("Duration (leave blank to be indefinite):") || "indefinite";
  var edittoken = req.responseText.split('<input name="wpEditToken" type="hidden" value="')[1].split('" />')[0];
  var postdata = "wpBlockAddress=" + encodeURIComponent(name)
               + "&wpBlockOther=" + duration
               + "&wpBlockReason=" + encodeURIComponent("Page-move vandalism")
               + "&wpBlockReasonList=other"
               + "&wpEmailBan=0"
               + "&wpCreateAccount=1"
               + "&wpEnableAutoblock=1"
               + "&wpEditToken=" + encodeURIComponent(edittoken)
               + "&wpBlock=block";
  var req = sajax_init_object();
  req.open("POST", wgScriptPath + "/index.php?title=Special:BlockIP&action=submit", false);
  req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');  
  req.setRequestHeader('Content-length', postdata.length);
  req.send(postdata);
   if(isBlocked(name)) { //Make sure we really are done.
    document.getElementById("contentSub").innerHTML += "<b>" + name + " has been blocked.</b>";
    protect("User talk:" + name);
   }
}
 
function beginRectification() {
    var doContinue = confirm("This script will block " + unescape(UrlParameters["user"].replace(/[+_]/g, " ")) + ", protect his/her talk page, revert ALL of his/her moves, and delete the redirects created therefrom.\n\nClick \"OK\" to continue, or \"Cancel\" to abort.");
    if(doContinue) {
        blockip(unescape(UrlParameters["user"]).replace(/[+_]/g, " "));
    } else {
        alert("Aborted.");
    }
} 
 
$(function() {
    if(wgNamespaceNumber == -1 && wgCanonicalSpecialPageName == "Log" && (UrlParameters["type"] == "move" || location.href.substring(location.href.indexOf("title=") + 6).split("/")[1] == "move" || location.href.substring(location.href.indexOf("/wiki/") + 6).split("?")[0].split("/")[1] == "move") && (UrlParameters["user"] || location.href.substring(location.href.indexOf("user=") + 5))) {
        mw.util.addPortletLink("p-cactions", "javascript:beginRectification()", "pagemove", "ca-pagemove");
    }
});