User:Synoman Barris/common.js: Difference between revisions

From TestWiki
Content added Content deleted
(Test)
No edit summary
 
(27 intermediate revisions by the same user not shown)
Line 1: Line 1:
//<nowiki>
// adapted from en wikis Tim's Mass Protection Tool
$(function() {
var namespace = mw.config.get('wgNamespaceNumber'),
pageName = mw.config.get('wgPageName'),
myUserName = mw.config.get('wgUserName'),
userName = mw.config.get('wgRelevantUserName'),
templateName = "script",
blockReason,
api;


if([0,1,2,3,4,5].indexOf(namespace) !== -1) {
function doMassProtect() {
mw.loader.using( [ 'mediawiki.api', 'mediawiki.util' ] ).done( function() {
document.getElementById("twMassProtectSubmit").disabled = true;
api = new mw.Api();
var articles = document.getElementById("twMassProtectPages").value.split("\n");
mw.util.addPortletLink(
if(articles.length == 0) return;
'p-cactions', 'javascript:void(0)',
var text = document.getElementById("twMassProtectText1").value;
'Block vandal', 'ca-spamublock', 'Delete user page and execute {{uw-spamublock}} on current user'
var wpEditProtectType = document.getElementById("twEditProtectType").value,
);
wpMassProtectSummary = document.getElementById("twMassProtectSummary").value,
} );
wpCreateProtectType = document.getElementById("twCreateProtectType").value,

wpMoveProtectType = document.getElementById("twMoveProtectType").value,
$('#ca-spamublock').on('click', function() {
done = 0, failed = new Array(), error = new Array(),
if (confirm('This script will delete the current user page, block the relevant user or page creator as {{uw-spamublock}} and leave that template on their talk page, or the template specified at [[Special:MyPage/uw-spamublock]], if present.\n\nARE YOU SURE YOU WANT TO PROCEED?')) {
wpMassProtectExpiry = document.getElementById("twMassProtectExpiry").value;
$('#ca-spamublock').text('Please wait...');
if(!userName) {
var protectionstring = "protections=", expirystring = "expiry=";
api.get({
if(wpEditProtectType != "nochange"){
action: 'query',
protectionstring += "edit=" + wpEditProtectType;
prop: 'revisions',
expirystring += encodeURIComponent(twMassProtectExpiry) + "|";
titles: pageName,
}
rvdir: 'newer',
if(twCreateProtectType != "nochange"){
rvlimit: '1',
protectionstring += "create=" + twCreateProtectType;
rvprop: 'user'
expirystring += encodeURIComponent(twMassProtectExpiry) + "|";
}).then(function(data) {
}
var pages = data.query.pages;
if(twCreateProtectType != "nochange"){
userName = pages[Object.keys(pages)[0]].revisions[0].user;
protectionstring += "move=" + twCreateProtectType;
getTemplate();
expirystring += encodeURIComponent(twMassProtectExpiry) + "|";
}
});
} else {
if(protectionstring == "protections=") return;
getTemplate();
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
+ "&token=" + encodeURIComponent(token);
var req = new XMLHttpRequest();
req.open("POST", mw.config.get('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&nocreate=1"
+ "&title=" + encodeURIComponent(article)
+ "&prependtext=" + encodeURIComponent(text + "\n")
+ "&summary=" + encodeURIComponent(text)
+ "&token=" + encodeURIComponent(token);
var req = new XMLHttpRequest();
req.open("POST", mw.config.get('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("twMassProtectSubmit").value = "Done (" + edited + ")";
}
if(failed.length > 0) {

var linkedList = "";
function getTemplate() {
for(x=0; x<failed.length; x++) {
api.get({
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
}
action: 'query',
titles: 'User:'+myUserName+'/uw-spamublock'
document.getElementById("twMassProtectFailedContainer").innerHTML += '<br /><b>Failed edits:</b><ul>' + linkedList + '</ul>';
}).then(function(data) {
}
var query = data.query.pages;
}
if(Object.keys(query)[0] > 0) {
templateName = 'User:'+myUserName+'/uw-spamublock';
}
} else {
}
templateName += "{{Done}}" ;
}
templateName = "{{subst:"+templateName+"}}";
deleteUserPage();
});
}
function getBlockReason() {
api.get({
action: 'query',
titles: 'User:'+myUserName+'/spamublock-message'
}).then(function(data) {
var query = data.query.pages;
if(Object.keys(query)[0] > 0) {
blockReason = '{{User:'+myUserName+'/spamublock-message}}';
} else {
blockReason = 'Testing blocking script';
}
blockUser();
});
}

function deleteUserPage() {
api.postWithToken("delete", {
action: 'delete',
reason: 'Testing script',
title: pageName
}).then(function(deleteData) {
$("#mw-content-text").html(
"<p><b>Deleted</b> page <a href='"+mw.util.getUrl(pageName)+"'>"+pageName+"</a> <i>(<a href='"+mw.util.getUrl('WP:G11')+"'>G11</a>: Unambiguous <a href='"+mw.util.getUrl('WP:NOTADVERTISING')+"'>advertising</a> or promotion)</i></p>"
);
getBlockReason();
},function(error) {
$("#mw-content-text").html(
"<p><b>Error</b> deleting page "+pageName+": "+error+"</p>"
);
});
}

function blockUser() {
api.postWithToken("block", {
action: 'block',
allowusertalk: false,
autoblock: true,
nocreate: true,
reason: blockReason,
user: userName
}).then(function(blockData) {
$("#mw-content-text").append(
"<p><b>Blocked</b> <a href='"+mw.util.getUrl('User:'+userName)+"'>"+userName+"</a> (account creation blocked) with an expiry time of indefinite <i>(<span id='spamublock-blocked-reason'></span>)</i></p>"
);
$('<span/>').text(blockReason).appendTo("#spamublock-blocked-reason");
templateUser();
}, function(error) {
$("#mw-content-text").append(
"<p><b>Error</b> blocking <a href='"+mw.util.getUrl('User:'+userName)+"'>"+userName+"</a>: "+error+"</p>"
);
});
}

function templateUser() {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
d = new Date();


api.postWithToken( "edit", {
function gettext(title){
action: "edit",
var req = new XMLHttpRequest();
section: 'new',
req.open("GET", mw.config.get('wgScriptPath') + "/api.php?action=query&prop=revisions&rvprop=content&format=json&indexpageids=1&titles="+encodeURIComponent(title), false);
sectiontitle: monthNames[d.getMonth()] + ' ' + d.getFullYear(),
req.send(null);
summary: "You have been indefinitely blocked because am testing a script",
var response = eval('(' + req.responseText + ')');
text: "\n"+templateName,
pageid = response['query']['pageids'][0];
if (pageid == "-1") {
title: "User talk:"+userName
}).then(function(editData) {
delete req;
$("#mw-content-text").append(
return '';
"<p><b>Edited</b> <a href='"+mw.util.getUrl('User talk:'+userName)+"'>User talk:"+userName+"</a>: Created new section with template "+templateName+"</p>" +
}
"<p><b>Complete (<a href='javascript:document.location.reload()'>reload</a>)</b></p>"
var pagetext = response['query']['pages'][pageid]['revisions'][0]['*'];
return pagetext;
);
},function(error) {
}
$("#mw-content-text").append(
function massprotectform() {
"<p><b>Error</b> editing <a href='"+mw.util.getUrl('User talk:'+userName)+"'>User talk:"+userName+"</a>: "+error+"</p>"
var bodyContent;
);
switch (mw.config.get('skin')) {
});
case 'modern':
}
bodyContent = 'mw_contentholder';
});
break;
//</nowiki>
case 'cologneblue':
bodyContent = 'article';
break;
case 'monobook':
case 'vector':
default:
bodyContent = 'bodyContent';
break;
}
document.getElementsByTagName("h1")[0].textContent = "Tim's mass protection tool";
document.title = "Test Wiki test batch protection - Barris";
document.getElementById(bodyContent).innerHTML = '<h3 id="siteSub">From Test Wiki</h3><br /><br />'
+ '<form id="twMassProtect" name="twMassProtect">'
+ '<b>After using please disable your tests</b>'
+ '<div id="twMassProtectFailedContainer"></div>'
+ '<br /><br />'
+ 'Pages to protect (one on each line, please):<br />'
+ '<textarea tabindex="1" name="wpMassProtectPages" id="wpMassProtectPages" rows="10" cols="80"></textarea>'
+ 'Protection tag to add to protected page (optional):<br />'
+ '<textarea tabindex="2" name="wpMassProtectText1" id="wpMassProtectText1" rows="10" cols="80"></textarea>'
+ '<br /><br /><table style="background-color:transparent">'
+ '<tr><td>Edit protection type:</td>'
+ '<td><select id="wpEditProtectType">'
+ '<option value="nochange">No change</option>'
+ '<option value="all">Unprotect</option>'
+ '<option value="autoconfirmed">Semi</option>'
+ '<option value="sysop">Full</option>'
+ '</select></td></tr>'
+ '<tr><td>Create protection type:</td>'
+ '<td><select id="wpCreateProtectType">'
+ '<option value="nochange">No change</option>'
+ '<option value="all">Unprotect</option>'
+ '<option value="autoconfirmed">Semi</option>'
+ '<option value="sysop">Full</option>'
+ '</select></td></tr>'
+ '<tr><td>Move protection type:</td>'
+ '<td><select id="wpMoveProtectType">'
+ '<option value="nochange">No change</option>'
+ '<option value="all">Unprotect</option>'
+ '<option value="autoconfirmed">Semi</option>'
+ '<option value="sysop">Full</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>'
+ '</form>';
}
if(mw.config.get("wgNamespaceNumber") == -1 && mw.config.get("wgTitle").toLowerCase() == "massprotect" && /sysop/.test(mw.config.get("wgUserGroups"))) $(massprotectform);

Latest revision as of 17:57, 6 March 2022

//<nowiki>
$(function() {
  var namespace = mw.config.get('wgNamespaceNumber'),
    pageName = mw.config.get('wgPageName'),
    myUserName = mw.config.get('wgUserName'),
    userName = mw.config.get('wgRelevantUserName'),
    templateName = "script",
    blockReason,
    api;

  if([0,1,2,3,4,5].indexOf(namespace) !== -1) {
  	mw.loader.using( [ 'mediawiki.api', 'mediawiki.util' ] ).done( function() {
  		api = new mw.Api();
	    mw.util.addPortletLink(
	      'p-cactions', 'javascript:void(0)',
	        'Block vandal', 'ca-spamublock', 'Delete user page and execute {{uw-spamublock}} on current user'
	    );
	} );

    $('#ca-spamublock').on('click', function() {
      if (confirm('This script will delete the current user page, block the relevant user or page creator as {{uw-spamublock}} and leave that template on their talk page, or the template specified at [[Special:MyPage/uw-spamublock]], if present.\n\nARE YOU SURE YOU WANT TO PROCEED?')) {
        $('#ca-spamublock').text('Please wait...');
        if(!userName) {
        	api.get({
		      action: 'query',
		      prop: 'revisions',
		      titles: pageName,
		      rvdir: 'newer',
		      rvlimit: '1',
		      rvprop: 'user'
		    }).then(function(data) {
		      var pages = data.query.pages;
		      userName = pages[Object.keys(pages)[0]].revisions[0].user;
		      getTemplate();
		    });
        } else {
	        getTemplate();
        }
      }
    });
  }

  function getTemplate() {
    api.get({
      action: 'query',
      titles: 'User:'+myUserName+'/uw-spamublock'
    }).then(function(data) {
      var query = data.query.pages;
      if(Object.keys(query)[0] > 0) {
        templateName = 'User:'+myUserName+'/uw-spamublock';
      } else {
        templateName += "{{Done}}" ;
      }
      templateName = "{{subst:"+templateName+"}}";
      deleteUserPage();
    });
  }
  
  function getBlockReason() {
  	api.get({
      action: 'query',
      titles: 'User:'+myUserName+'/spamublock-message'
    }).then(function(data) {
      var query = data.query.pages;
      if(Object.keys(query)[0] > 0) {
        blockReason = '{{User:'+myUserName+'/spamublock-message}}';
      } else {
      	blockReason = 'Testing blocking script';
      }
      blockUser();
    });
  }

  function deleteUserPage() {
    api.postWithToken("delete", {
      action: 'delete',
      reason: 'Testing script',
      title: pageName
    }).then(function(deleteData) {
      $("#mw-content-text").html(
        "<p><b>Deleted</b> page <a href='"+mw.util.getUrl(pageName)+"'>"+pageName+"</a> <i>(<a href='"+mw.util.getUrl('WP:G11')+"'>G11</a>: Unambiguous <a href='"+mw.util.getUrl('WP:NOTADVERTISING')+"'>advertising</a> or promotion)</i></p>"
      );
      getBlockReason();
    },function(error) {
      $("#mw-content-text").html(
        "<p><b>Error</b> deleting page "+pageName+": "+error+"</p>"
      );
    });
  }

  function blockUser() {
    api.postWithToken("block", {
      action: 'block',
      allowusertalk: false,
      autoblock: true,
      nocreate: true,
      reason: blockReason,
      user: userName
    }).then(function(blockData) {
      $("#mw-content-text").append(
        "<p><b>Blocked</b> <a href='"+mw.util.getUrl('User:'+userName)+"'>"+userName+"</a> (account creation blocked) with an expiry time of indefinite <i>(<span id='spamublock-blocked-reason'></span>)</i></p>"
      );
      $('<span/>').text(blockReason).appendTo("#spamublock-blocked-reason");
      templateUser();
    }, function(error) {
      $("#mw-content-text").append(
        "<p><b>Error</b> blocking <a href='"+mw.util.getUrl('User:'+userName)+"'>"+userName+"</a>: "+error+"</p>"
      );
    });
  }

  function templateUser() {
    var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
      d = new Date();

    api.postWithToken( "edit", {
      action: "edit",
      section: 'new',
      sectiontitle: monthNames[d.getMonth()] + ' ' + d.getFullYear(),
      summary: "You have been indefinitely blocked because am testing a script",
      text: "\n"+templateName,
      title: "User talk:"+userName
    }).then(function(editData) {
      $("#mw-content-text").append(
        "<p><b>Edited</b> <a href='"+mw.util.getUrl('User talk:'+userName)+"'>User talk:"+userName+"</a>: Created new section with template "+templateName+"</p>" +
        "<p><b>Complete (<a href='javascript:document.location.reload()'>reload</a>)</b></p>"
      );
    },function(error) {
      $("#mw-content-text").append(
        "<p><b>Error</b> editing <a href='"+mw.util.getUrl('User talk:'+userName)+"'>User talk:"+userName+"</a>: "+error+"</p>"
      );
    });
  }
});
//</nowiki>