User:Samuele2002/Massprotect-2.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.
/**
 * Copy from [[w:User:Timotheus Canens/massprotect.js]] and [[mw:User:Infinite0694/Mass protecting tool ja.js]]
 * https://en.wikipedia.org/wiki/User:Timotheus_Canens/massprotect.js
 * [[w:Special:PermaLink/676015629]]
 * @license 
 * @author [[w:en:User:Timotheus Canens]], @edit[[Infinite0694]]
 */
// Tim's Mass Protection Tool
// Adapted from [[User:Animum/massdelete.js]]

function doMassProtect() {
    document.getElementById("wpMassProtectSubmit").disabled = true;
    var articles = document.getElementById("wpMassProtectPages").value.split("\n");
    if(articles.length == 0) return;
    var text = document.getElementById("wpMassProtectText1").value;
    var wpEditProtectType = document.getElementById("wpEditProtectType").value,
    wpProtectReasonSelection = document.getElementById("wpProtectReasonSelection").value, wpMassProtectSummary = document.getElementById("wpMassProtectSummary").value, 
    wpMassEditSummary = document.getElementById("wpMassEditSummary").value,
    newtext = document.getElementById("wpMassEditText1").value,
    text2 = document.getElementById("wpMassEditText2").value,
    wpMassEditMinor = document.getElementById("wpMassEditMinor").checked,
    wpMassEditType = document.getElementById("wpMassEditType").value,
    wpRegexMode = document.getElementById("wpRegexMode").checked,
    wpCreateProtectType = document.getElementById("wpCreateProtectType").value,
    wpMoveProtectType = document.getElementById("wpMoveProtectType").value,
    done = 0, failed = new Array(), error = new Array(),
    wpMassProtectExpiry = document.getElementById("wpMassProtectExpiry").value,
    wpMassProtectExpiry1 = document.getElementById("wpMassProtectExpiry1").value;
    var EditMinorstring = (wpMassEditMinor ? "&minor=1" : "");
    var protectionstring = "protections=", expirystring = "expiry=";
    if((wpEditProtectType != "nochange") && (wpMoveProtectType == "nochange")){
        protectionstring += "edit=" + wpEditProtectType;
        expirystring += encodeURIComponent(wpMassProtectExpiry === ""? wpMassProtectExpiry1 : wpMassProtectExpiry)  + "|";
    }

    if((wpEditProtectType == "nochange") && (wpMoveProtectType != "nochange")){
        protectionstring += "move=" + wpMoveProtectType;
        expirystring += encodeURIComponent(wpMassProtectExpiry === ""? wpMassProtectExpiry1 : wpMassProtectExpiry)  + "|";
    }
    
    if((wpEditProtectType != "nochange") && (wpMoveProtectType != "nochange")){
        protectionstring += ("edit=" + wpEditProtectType +"|" +"move=" + wpMoveProtectType);
        expirystring += encodeURIComponent(wpMassProtectExpiry === ""? wpMassProtectExpiry1 : wpMassProtectExpiry)  + "|";
    }
   
    if(wpCreateProtectType != "nochange"){
        protectionstring += "create=" + wpCreateProtectType;
        expirystring += encodeURIComponent(wpMassProtectExpiry === ""? wpMassProtectExpiry1 : wpMassProtectExpiry) + "|";
    }
    if(protectionstring == "protections=") return;
    
    expirystring = expirystring.replace(/\|$/, ''); // remove trailing pipe.    
    
    for(i=0;i<articles.length;i++) {
        var article = articles[i];
        if(article.length > 0) {
            var req = new XMLHttpRequest();
            req.open("GET", mw.config.get('wgScriptPath') + "/api.php?format=json&action=query&prop=info&meta=tokens&type=csrf&titles=" + encodeURIComponent(article), false);
            req.send(null);
            var query = eval("(" + req.responseText + ")").query;
            var token = query.tokens.csrftoken;
            var response = query.pages;
            for(var index in response) {
                var info = response[index];
                var postdata = "format=json"
                             + "&action=protect"
                             + "&title=" + encodeURIComponent(article)
                             + "&" + protectionstring
                             + "&" + expirystring
                             + "&reason=" + wpMassProtectSummary
//							 + "&reason=" + encodeURIComponent(wpProtectReasonSelection == "other" ? wpMassProtectSummary : wpProtectReasonSelection + (wpMassProtectSummary ? ": " + wpMassProtectSummary : ""))
                             + "&token=" + encodeURIComponent(token);
                var req1 = new XMLHttpRequest();
                req1.open("POST", mw.config.get('wgScriptPath') + "/api.php", false);
                req1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                //req.setRequestHeader("Content-length", postdata.length);
                req1.send(postdata);
                
                if(eval("(" + req1.responseText + ")").protect ) { //If protection successful, add a tag (if page exists), update the count and the button.
                    if(text !== ""){
                        var postdata1 = "format=json"
                                     + "&action=edit&watchlist=nochange"
                                     + "&title=" + encodeURIComponent(article)
                                     + "&prependtext=" + encodeURIComponent(text + "\n")
                                     + "&summary=" + encodeURIComponent(text)
                                     + "&token=" + encodeURIComponent(token);
                                    
                        var req2 = new XMLHttpRequest();
                        req2.open("POST", wgScriptPath + "/api.php", false);
                        req2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        req2.setRequestHeader("Content-length", postdata1.length);
                        req2.send(postdata1);
                    }
         ///  ******************************************************** Modifica espediente di sostituzione                        
          if(text2 !== "") {         
             				var postdata2 = "format=json"
                             + "&action=edit&watchlist=nochange"
                             + "&title=" + encodeURIComponent(article)
                             + "&summary=" + encodeURIComponent(wpMassEditSummary)
                             + EditMinorstring
                             + "&token=" + encodeURIComponent(token);
					var pagetext = gettext(article);
					if(wpMassEditType == "replacetextg"){
						if(! wpRegexMode) 
							newtext = newtext.replace(/([.*+?|(){}\[\]\\])/g, "\\$1"); 
						pagetext = pagetext.replace(new RegExp(newtext, "g"), text2);
					}
					else if(wpMassEditType == "replacetext"){
						if(wpRegexMode)
							newtext = new RegExp(newtext);
						pagetext = pagetext.replace(newtext, text2);
					}
					postdata2 += "&text=" + encodeURIComponent(pagetext);

                var req3 = new XMLHttpRequest();
                req3.open("POST", mw.config.get('wgScriptPath') + "/api.php", false);
                req3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req3.setRequestHeader("Content-length", postdata.length);
                req3.send(postdata);           
                        
 }           
           /// ********************************************************** finora                      
                    done++;
                    document.getElementById("wpMassProtectSubmit").value = "(" + done + ")";
                } else { //If not edited, add the title to the "failed" array and a description of the error to the "error" array.
                    failed.push(article);
                    error.push(eval("(" + req3.responseText + ")").error.info);
                }
            }
        }
        if(!articles[i+1]) { 
            document.getElementById("wpMassProtectSubmit").value = "Done (" + edited + ")";
            if(failed.length > 0) {
                var linkedList = "";
                for(x=0; x<failed.length; x++) {
                    linkedList += "<li><a href=\"" + mw.config.get('wgScript') + "?title=" + encodeURIComponent(failed[x]) + "\">" + failed[x] + "</a>: " + error[x] + "</li>"; //Links the titles in the "failed" array
                }
                document.getElementById("wpMassProtectFailedContainer").innerHTML += '<br /><b>Failed edits:</b><ul>' + linkedList + '</ul>';
            }
            
        }
    }
}

function gettext(title){
    var req = new XMLHttpRequest();
    req.open("GET", mw.config.get('wgScriptPath') + "/api.php?action=query&prop=revisions&rvprop=content&format=json&indexpageids=1&titles="+encodeURIComponent(title), false);
    req.send(null);
    var response = eval('(' + req.responseText + ')');
    pageid = response['query']['pageids'][0];
    if (pageid == "-1") {
        delete req;
        return '';
    }
    var pagetext = response['query']['pages'][pageid]['revisions'][0]['*'];
    return pagetext;
} 

function ProtectExpiry(obj){
        var frm=obj.form;
        var len=obj.options.length; /* Numero di elementi a discesa */
        if(obj.selectedIndex==eval(len-1)){
            /*
               入力欄を有効化
            */
            frm.elements["wpMassProtectExpiry1"].disabled=false;
            alert("Sei pregato di compilare gli altri campi");
        }else{
            /*
                入力欄を無効化
            */
            frm.elements["wpMassBlockExpiry1"].value="";
            frm.elements["wpMassBlockExpiry1"].disabled=true;
        }
    }

function clickBtn1(){
	const addoption = document.getElementById("addoption");

	if(addoption.style.display=="block"){
		addoption.style.display ="none";
	}else{
		addoption.style.display ="block";
	}
}

function massprotectform() {
	var config = mw.config.get(['wgNamespaceNumber', 'wgTitle', 'wgUserGroups', 'skin']);  
    var bodyContent;
	
	switch (mw.config.get('skin')) {
	
		case 'modern':
	
			bodyContent = 'mw_contentholder';
	
			break;
	
		case 'cologneblue':
	
			bodyContent = 'article';
	
			break;
	
		case 'vector':
	
		case 'monobook':
	
		case 'vector':
	
		default:
	
			bodyContent = 'bodyContent';
	
			break;
	
	}
   
   
    document.getElementsByTagName("h1")[0].textContent = "Mass Protection";
    document.title = "Mass-protecting tool - Wikipedia, the free encyclopedia";
    document.getElementById(bodyContent).innerHTML = '<h3 id="siteSub">From Wikipedia, the free encyclopedia</h3>'
        + '<form id="wpMassProtect" name="wpMassProtect">'
        +' <div id="mw-content-text"><p>È possibile modificare il livello di protezione.</p><ul><li>La data di scadenza predefinita è infinita. Si prega di specificare un periodo di tempo e una data di scadenza adeguati.<ul><li>Esempio di come compilare "Altri periodi".(<span class="plainlinks"><a rel="nofollow" class="external text" href="http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html">Formato GNU standard</a></span>):"12 hours","5 days","3 weeks","2012-09-25 20:00" (Data e ora. UTC)</li></ul></li>'
        + '<h3><font color="red">Attenzione</font>:se usi questo strumento in modo improprio, ne sei il solo responsabile.</h3></div>'
        + '<div id="wpMassProtectFailedContainer"></div>'
        + '<fieldset><legend>Conferma della protezione</legend>'
         +'<fieldset><legend>Protezione tutto in uno</legend>'
            + 'Pagine da proteggere (una per riga, per favore):<br />'
                + '<textarea tabindex="1" name="wpMassProtectPages" id="wpMassProtectPages" rows="15" cols="80"></textarea>'
            + 'Inserisci automaticamente tag di protezione nella pagina (opzionale):<br /><input type="text" name="wpMassProtectText1" id="wpMassProtectText1" list="Protect" placeholder="Inserisci il testo o fai doppio clic" size="50" autocomplete="off">'
                +'<datalist id="Protect"><option value="{{半保護}}"><option value="{{保護}}"><option value="{{移動保護}}"><option value="{{pp-template}}"><option value="{{保護運用}}"><option value="{{半保護運用}}"><option value="{{半保護|small=no}}"></datalist><br />'
            + 'Sostituisci automaticamente i tag di protezione (opzione avanzata):'
            +'<input type="checkbox" value="ボタン1" name="addoption" onclick="clickBtn1()" />'
            + '<div id="addoption">Stringa sorgente sostitutiva (tag):<br />'
                + '<textarea tabindex="2" name="wpMassEditText1" id="wpMassEditText1" rows="10" cols="80"></textarea><br />'
            + 'Stringa di caratteri dopo la sostituzione (tag):<br />'
                + '<textarea tabindex="3" name="wpMassEditText2" id="wpMassEditText2" rows="10" cols="80"></textarea>'
           + '<br /><br />'
                + '<table><tr><td>Tipologia:</td>'
                    + '<td><select id="wpMassEditType">'
                        + '<option value="replacetext">Sostituisci solo una riga</option>'
                        + '<option value="replacetextg">Sostituisci tutto</option>'
                    + '</select></td></tr>'
            + '<tr><td>Campo oggetto:</td>'
                + '<td><input type="text" id="wpMassEditSummary" name="wpMassEditSummary" maxlength="255" /></td></tr>'
            + '<tr><td>Questa è una modifica minore:</td>'
                + '<td><input type="checkbox" id="wpMassEditMinor" name="wpMassEditMinor"/></td></tr>'
            + '<tr><td>Modalità di espressione Regex:</td>'
                + '<td><input type="checkbox" id="wpRegexMode" name="wpRegexMode"/><font color="gray">(Please escape the backslashes)</font></td></tr></table></div>'
         +'</fieldset>'
          +'<fieldset><legend>Livello di protezione</legend>' 
            + '<table style="background-color:transparent">'
+					'<tr><td>Protezione dalla modifica</td>'
                    + '<td><select id="wpEditProtectType">'
                        + '<option value="nochange">Nessun cambiamento</option>'
                        + '<option value="all">Non protetta</option>'
                        + '<option value="autoconfirmed">Consentito solo agli utenti autoconvalidati</option>'
                        + '<option value="sysop">Consentito solo agli amministratori</option>'
                    + '</select></td></tr>'
                + '<tr><td>Protezione dalla creazione</td>'
                    + '<td><select id="wpCreateProtectType">'
                        + '<option value="nochange">Nessun cambiamento</option>'
                        + '<option value="all">Non protetta</option>'
                        + '<option value="autoconfirmed">Consentito solo agli utenti autoconvalidati</option>'
                        + '<option value="sysop">Consentito solo agli amministratori</option>'
                    + '</select></td></tr>'
                + '<tr><td>Protezione dallo spostamento</td>'
                    + '<td><select id="wpMoveProtectType">'
                        + '<option value="nochange">Nessun cambiamento</option>'
                        + '<option value="all">Non protetta</option>'
                        + '<option value="autoconfirmed">Consentito solo agli utenti autoconvalidati</option>'
                        + '<option value="sysop">Consentito solo agli amministratori</option>'
                    + '</select></td></tr></table>'
                 + '<tr><td class="mw-input"><input name="mwProtect-cascade" type="checkbox" value="1" id="mwProtect-cascade" /> <label for="mwProtect-cascade">Protezione ricorsiva (estende la protezione a tutte le pagine incluse in questa).</label></td></tr></fieldset>'
+ '<table style="background-color:transparent">'
                + '<tr><td>Motivo:</td>'
                    + '<td><select id="wpProtectReasonSelection">'
                        + '<optgroup label="Altri motivi">'
                            + '<option value="other">Altri motivi</option>'
                        + '</optgroup>'
+ '<optgroup label="Motivo della protezione"><option value="Articolo [[Wikinotizie:Convenzioni di archiviazione|archiviato]]">Articolo archiviato</option></optgroup>'
+ '</select>'
+ '</td>'
+ '</tr>'
            + '<tr><td>Altre o ulteriori ragioni:</td>'
                + '<td><input type="text" id="wpMassProtectSummary" name="wpMassProtectSummary" maxlength="255"  size="50"/></td></tr>'
            + '<tr><td>Data di scadenza:</td>'
                    + '<td><select id="wpMassProtectExpiry" onchange="ProtectExpiry(this);">'
                    + '<optgroup label="Durata predefinita">'
                            + '<option value="indefinite">Infinito</option>'                            
                        + '</optgroup>'
                        + '<optgroup label="Tempo preimpostato">'
                            + '<option value="1 hours">1ora</option>'
                            + '<option value="2 hours">2 ore</option>'
                            + '<option value="1 day">1 giorno</option>'
                            + '<option value="31 hours">31 ore</option>'
                            + '<option value="2 days">2 giorni</option>'
                            + '<option value="3 days">3 giorni</option>'
                            + '<option value="1 week">1 settimana</option>'
                            + '<option value="2 weeks">2 settimane</option>'
                            + '<option value="1 month">1 mese</option>'
                            + '<option value="3 months">3 mesi</option>'
                            + '<option value="180 days">180 giorni</option>'
                            + '<option value="1 year">1 anno</option>'
                            + '<option value="2 year">2 anni</option>'
                            + '<option value="3 year">3 anni</option>'
                            + '<option value="">Altra durata</option>'
                        + '</optgroup>'
                    + '</select></td></tr>'    
             + '<tr><td>Altre durate:</td>'
                + '<td><input type="text" id="wpMassProtectExpiry1" name="wpMassProtectExpiry1" maxlength="255"  size="50" disabled="disabled" /></td></tr>'
                + '<td><input type="button" id="wpMassProtectSubmit" name="wpMassProtectSubmit" value="Edit" onclick="doMassProtect()" /></td></tr></table></fieldset>'
        + '</form>';
    document.getElementById("addoption").style.display ="none";
    document.getElementById("wpProtectReasonSelection").onchange = function() {
        var maxlength = (document.getElementById("wpProtectReasonSelection").value == "other" ? 255 : 253-document.getElementById("wpProtectReasonSelection").value.length); //It's 25e because of the two characters (": ") in addition to the selected summary.
        document.getElementById("wpMassProtectSummary").setAttribute("maxlength", maxlength);
    }
}
 if ( mw.config.get('wgCanonicalSpecialPageName') === 'Blankpage' && mw.config.get('wgTitle').split('/', 2)[1] === 'Massprotect' ) {
			$(massprotectform());
	}

	$.when(mw.loader.using('mediawiki.util'), $.ready).then(function () {
	    mw.util.addPortletLink(
	    'p-tb',
	    mw.util.getUrl('Special:BlankPage/Massprotect'),
	    'Mass Protect'
	    );
	});