User:Samuele2002/Massprotect.js

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.
/* Tim's Mass Protection Tool
 * Copy from [[w:User:Timotheus Canens/massprotect.js]]
 * https://en.wikipedia.org/wiki/User:Timotheus_Canens/massprotect.js
 * @license 
 * @author [[w:en:User:Timotheus Canens]], @edit
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.   
    
     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", wgScriptPath + "/api.php?format=json&action=query&prop=info&intoken=protect&titles=" + encodeURIComponent(article), false);
            req.send(null);
            var response = eval("(" + req.responseText + ")").query.pages;
            for(var index in response) {
                var info = response[index];
                var token = info.protecttoken;
                var postdata = "format=json"
                             + "&action=protect"
                             + "&title=" + encodeURIComponent(article)
                             + "&" + protectionstring
                             + "&" + expirystring
							 + "&reason=" + encodeURIComponent(wpProtectReasonSelection == "other" ? wpMassProtectSummary : wpProtectReasonSelection + (wpMassProtectSummary ? ": " + wpMassProtectSummary : ""))
                             + "&token=" + encodeURIComponent(token);
                var req = new XMLHttpRequest();
                req.open("POST", wgScriptPath + "/api.php", false);
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req.setRequestHeader("Content-length", postdata.length);
                req.send(postdata);
                
                if(eval("(" + req.responseText + ")").protect ) { //If protection successful, add a tag (if page exists), update the count and the button.
                    if(text !== ""){
                        var postdata = "format=json"
                                     + "&action=edit&watchlist=nochange"
                                     + "&title=" + encodeURIComponent(article)
                                     + "&prependtext=" + encodeURIComponent(text + "\n")
                                     + "&summary=" + encodeURIComponent(text)
                                     + "&token=" + encodeURIComponent(token);
                                    
                        var req = new XMLHttpRequest();
                        req.open("POST", wgScriptPath + "/api.php", false);
                        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        req.setRequestHeader("Content-length", postdata.length);
                        req.send(postdata);
                    }
         ///  ******************************************************** 編集の置換ギミック                         
          
          // [[m:User:Indic-TechCom/Script/findAndreplace.js]]

$( document ).ready( function (){

	function init() {
		// Remove the default content
		$('#mw-content-text > p').remove();
    	$('#firstHeading').text('Find and Replace');
		
		// Create widget
		var listofPages = new OO.ui.MultilineTextInputWidget( {
            	placeholder: 'List of Pages',
            	autosize: true, 
            	rows: 10 
        	} ), 
	        findInput = new OO.ui.TextInputWidget( { 
	            placeholder: 'Trova'
	        } ),
	        replaceInput = new OO.ui.TextInputWidget( { 
	            placeholder: 'Sostituisci'
	        } ),
	        reasonInput = new OO.ui.TextInputWidget( { 
	            placeholder: 'Motivo'
	        } ),
			replaceStart = new OO.ui.ButtonWidget( { 
			    label: 'Inizia sostituzioni', 
			    icon: 'alert',
			    flags: [ 'progressive' ]
			} ),
		/*	cancelBtn = new OO.ui.ButtonWidget( {
			    label: 'Annulla',
			    flags: [ 'primary', 'destructive' ],
			    href: 'https:' + mw.config.get( 'wgServer' )
			} ),*/
			label1 = $('<p>').text('List of Pages:').css('font-weight','bold' ),
			label2 = $('<p>').text('Find:').css('font-weight','bold' ),
			label3 = $('<p>').text('Replace:').css('font-weight','bold' ),
			label4 = $('<p>').text('Reason:').css('font-weight','bold' ),
			divMainBox = $('<div />').css( {
				'box-shadow': '0 .5rem 1rem rgba(0, 0, 0, .15)',
				'border': '1px solid',
				'padding': '1rem',
				'margin-bottom': '3rem',
				'border-radius': '.5rem'
			}),
			divLog = $("<div />").hide(),
			orderedList = $("<ol />");
			
		divMainBox.append( 
            label1, listofPages.$element, 
            label2, findInput.$element,
            label3, replaceInput.$element,
            label4, reasonInput.$element,
            '<br/>',
            replaceStart.$element,
            cancelBtn.$element
		);
    	
		$( '#mw-content-text' ).append( divMainBox, '<br/>', divLog );

		// Replace button click event
		replaceStart.on( 'click', function() {

			pagesList = listofPages.getValue().replace(/^\s*[\r\n]/gm, '').split("\n");
			find = findInput.getValue().trim(),
			replace = replaceInput.getValue().trim(),
			reason = reasonInput.getValue().trim() + " (By [[meta:Indic-TechCom/Tools|FindAndReplace]])";
			
			// Check whether the all fields are enough to run the function
			if( pagesList[0].trim() !== "" && find !== "" && replace !== "" ) {
				divLog.empty();
				$("<h1>").wrapInner( "<span class='mw-headline'>Edit Log</span>").appendTo( divLog );
				orderedList.appendTo( divLog );
				divLog.show();
			} else {
				missingAlertMsg( "any source page" );
				return;
			}
			
			if ( find === "" ) {
				missingAlertMsg( "\'find\' string" );
				return;
			} else if ( replace === "" ) {
				missingAlertMsg( "replace string" );
				return;
			}

			pagesList.forEach( function(page){
				page = page.trim();

				var getContentParam = {
					"action": "query",
					"format": "json",
					"prop": "revisions",
					"titles": page,
					"rvprop": "content",
					"rvslots": "main",
					"rvlimit": "1"
				};
			
				api = new mw.Api();
				api.get( getContentParam, { async: false } ).done( function ( data ) {
					try {
						Text1 = data.query.pages[Object.keys(data.query.pages)[0]].revisions[0].slots.main['*'];
					} catch(e){
						Text1 = -1;
					}
	
					if( Text1 !== -1 ){
						Text2 = safeReplace( Text1, find, replace );
						if ( Text2 === Text1){
							orderedList.append( "<li><b>" + page + "</b> Nessuna modifica necessaria.</li>" );
						} else{
							// Edit the page
							var editParams = {
								action: 'edit',
								title: page,
								text: Text2,
								summary: reason,
								format: 'json'
							};

							api.postWithToken( 'csrf', editParams, { async: false } ).done( function ( res ) {
								if( res.edit.result === "Success"){
									orderedList.append( "<li>Modifiche apportate alla pagina <b>" + page + "</b></li>" );
								} else{
									orderedList.append( "<li>Qualcosa è andato storto nella pagina <b>" + page + "</b></li>" );
								}
							} );
						}
					} else {
						orderedList.append( "<li><b>" + page + "</b> non trovata.</li>" );
					}
				});
			});
    	});
	}

	function missingAlertMsg ( str ) {
		return alert( "Did not find " + str + " :(" );
		
	}

/*	function safeReplace( input, find, replaceText ) {
	    var flags = 'g';
	    
	    find = find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
	
	    var exclude = '(<!--[\\s\\S]*?-->|<(nowiki|math|source|syntaxhighlight|pre|gallery|timeline)[^>]*?>[\\s\\S]*?<\\/\\2>)';
	    var re = new RegExp(exclude + '|(' + find + ')', flags.replace(/i|$/, 'i'));
	    return input.replace(re, function(match, g1, g2, g3) {
			if (g3 !== undefined) {
				return match.replace(new RegExp(find, flags), replaceText);
			} else {
				return match;
			}
		});
	} */
          
          
       /*   
          if(text2 !== "") {         
             				var postdata = "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);
					}
					postdata += "&text=" + encodeURIComponent(pagetext);

                var req = new XMLHttpRequest();
                req.open("POST", wgScriptPath + "/api.php", false);
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req.setRequestHeader("Content-length", postdata.length);
                req.send(postdata);           
                        
 }           
           /// ********************************************************** ここまで                      
                    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("(" + req.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=\"" + 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", 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; /* プルダウンの項目数 */
        if(obj.selectedIndex==eval(len-1)){
            /*
               入力欄を有効化
            */
            frm.elements["wpMassProtectExpiry1"].disabled=false;
            alert("その他欄に入力してください");
        }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 bodyContent = (skin == "cologneblue" ? "article" : "bodyContent");
    document.getElementsByTagName("h1")[0].textContent = "Tim's mass protection tool";
    document.title = "Tim's mass-editing tool - Wikipedia, the free encyclopedia";
    document.getElementById(bodyContent).innerHTML = '<h3 id="siteSub">From Wikipedia, the free encyclopedia</h3><br /><br />'
        + '<form id="wpMassProtect" name="wpMassProtect">'
        + '<b>If you abuse this tool, it\'s <i>your</i> fault, not mine.</b>'
        + '<div id="wpMassProtectFailedContainer"></div>'
        + '<br /><br />'
            + 'Pagine da proteggere (una per riga, per favore)<br />'
                + '<textarea tabindex="1" name="wpMassProtectPages" id="wpMassProtectPages" rows="10" cols="80"></textarea>'
            + 'Tag di protezione da aggiungere alla pagina protetta (opzionale):<br />'
                + '<textarea tabindex="2" name="wpMassProtectText1" id="wpMassProtectText1" rows="10" cols="80"></textarea>'
            + '<br /><br /><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">Semi</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">Semi</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">Semi</option>'
                        + '<option value="sysop">Consentito solo agli amministratori</option>'
                    + '</select></td></tr>'
            + '<tr><td>Reason:</td>'
                + '<td><input type="text" id="wpMassProtectSummary" name="wpMassProtectSummary" maxlength="255" /></td></tr>'
            + '<tr><td>Expiry:</td>'
                + '<td><input type="text" id="wpMassProtectExpiry" name="wpMassProtectExpiry" maxlength="255" /></td></tr>'
                + '<tr><td><input type="button" id="wpMassProtectSubmit" name="wpMassProtectSubmit" value="Edit" onclick="doMassProtect()" /></td></tr></table>'
        + '<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>';
        

                          
        
}

if(wgNamespaceNumber == -1 && (wgPageName == "Special:Massprotect" || wgPageName == "Special:Massprotect") && /autoconfirmed/.test(wgUserGroups)) $(massprotectform());