Jump to content

User:Yunshui/vector.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Yunshui (talk | contribs) at 23:00, 4 February 2013 (fingers crossed...). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
importScript('User:Timotheus Canens/afchelper4.js'); // Yet another AfC helper script v4.

importScript('User:AzaToth/twinkle.js');

importScript('MediaWiki:Gadget-HotCat.js');

importScript('User:Ale_jrb/Scripts/igloo.js'); // [[User:Ale_jrb/Scripts/igloo]]

importScript('User:Symplectic_Map/spell.js');

importScript('User:Mr.Z-man/closeAFD.js');

importScript("User:PleaseStand/segregate-refs.js");

importScript('User:Dipankan001/external link.js')

importScript('User:Symplectic_Map/spell.js');

	if ( histlimit === undefined ) var histlimit = 40;
	if ( typeof histwidth === 'undefined' ) var histwidth = 200;
 
	diffRequestLocked = "f";
 
	function userHistMain() {
		var me = this;
 
		this.displayBox = function ( user ) {
			// if user is set, this name will automatically be displayed on load
			if ( user == null ) { user = ''; } else {
				user = user.replace ( /(_|%20)/gi, ' ' );
				user = user.replace ( /(%3A)/gi, ':' );
			}
 
			var box = document.createElement( 'input' );
			box.setAttribute ( 'id', 'userhist-isolate' );
			box.setAttribute ( 'type', 'text' );
			box.setAttribute ( 'value', user );
			box.setAttribute ( 'style', 'width: ' + histwidth + 'px' );
 
			var button = document.createElement( 'input' );
			button.setAttribute ( 'type', 'button' );
			button.setAttribute ( 'value', 'Isolate history' );
			button.setAttribute ( 'style', 'margin-left: 4px;' );
 
			if ( button.addEventListener ) { 
				button.addEventListener( 'click', function () { userHist.getUserHist(document.getElementById('userhist-isolate').value); }, false ); 
			} 
			else 
			{ 
				button.attachEvent( 'onclick', function () { userHist.getUserHist(document.getElementById('userhist-isolate').value); } ); 
			}
 
 
			var span = document.createElement ( 'span' );
			span.setAttribute ( 'style','margin-left: 20px;' );
			span.appendChild ( box );
			span.appendChild ( button );
 
			document.getElementById( 'mw-history-search' ).appendChild ( span );
		}
 
		this.getUserHist = function ( user ) {
			var api = '/w/api.php';
			if ( typeof user == 'undefined' ) return false;
			if ( ! user ) return false;
 
			user = user.replace(/ /g, '_');
			user = user.replace(/User(:|%3A)/gi, '');
 
			// remove useless interface
			var histPar = document.getElementById ( 'mw-history-compare' );
			histPar.innerHTML = '<span style="padding: 4px;">isolating edits by <strong>' + user + '</strong> - please wait...</span>';
 
			var apiLink = '?action=query&format=xml&prop=revisions&titles='+wgPageName+'&rvprop=ids|timestamp|flags|comment|user|size&rvlimit=500&rvuser='+user+'';
 
			this.req 				= new wa_ajaxcall ();
			this.req.requestUrl		= api + apiLink;
			this.req.get			( function() {
										userHist.data = userHist.req.response;
										userHist.showUserHist ();
										return true;
									} );
		}
 
		this.showUserHist = function () {
			var data = this.data;
 
			if ( data.getElementsByTagName( 'rev' ).length <= 0 ) {
				this.showError('That user has never edited this page.');
				return false;
			}
 
			// get output
			var output = [];
			for ( var i = 0; i < data.getElementsByTagName( 'rev' ).length; i ++ ) {
				var dataset = data.getElementsByTagName( 'rev' )[i];
 
				output[i] = [];
				output[i][0] = dataset.getAttribute ( 'revid' ); // oldid
				output[i][1] = dataset.getAttribute ( 'user' ); // user
				output[i][2] = dataset.getAttribute ( 'timestamp' ); // timestamp
				output[i][3] = dataset.getAttribute ( 'comment' ); // comment
				output[i][4] = dataset.getAttribute ( 'size' ); // size
				output[i][5] = dataset.getAttribute ( 'minor' ); // minor
			}
 
			// build our own interface
			var newInt = document.createElement("ul");
			newInt.id = "pagehistory";
			var url = '/w/index.php?title='+wgPageName;
			for (var i = 0; i < output.length; i ++) {
 
				var timestamp = me.convertTimestamp(output[i][2]);
				var comment = me.parseComment(output[i][3]);
				if ( output[i][5] != null ) { var m = '<span class="minor">m</span> '; } else { var m = ''; }
 
				newEntry = document.createElement("li");
				newEntry.className='""';
				newEntry.id = "rev" + output[i][0];
				newEntry.innerHTML = '(<a href="'+url+'&oldid='+output[i][0]+'&diff=cur">cur</a> | <a href="'+url+'&oldid='+output[i][0]+'&diff=prev">prev</a>) <span style="padding-left: 5px;"><a href="'+url+'&oldid='+output[i][0]+'">'+timestamp+'</a></span> <span class="history-user"><a href="/wiki/User:'+output[i][1]+'">'+output[i][1]+'</a></span> '+m+'<span class="history-size">('+output[i][4]+' bytes)</span> '+comment+' ';
 
				var inlineDiffButton = document.createElement("input");
				inlineDiffButton.type = "button";
				inlineDiffButton.id = output[i][0];
				inlineDiffButton.value = "Inspect edit";
				$(inlineDiffButton).click(function(){ userHist.inspectDiff(this);});
				newEntry.appendChild(inlineDiffButton);
				newInt.appendChild(newEntry);
			}
 
			var histPar = document.getElementById( 'mw-history-compare' );
			histPar.innerHTML = "";
			histPar.appendChild(newInt);
                        mw.loader.load('mediawiki.action.history.diff')
		}
 
		this.inspectDiff = function( button)
		{
			if(diffRequestLocked === "t")
			{
				alert("An old request is still being processed, please wait...");
				return;
			}
			else
			{
				diffRequestLocked = "t";
 
				$.getJSON("/w/api.php?action=query&prop=revisions&format=json&rvprop=timestamp&rvlimit=1&rvstartid="+button.id+"&rvendid="+button.id+"&rvtoken=rollback&rvdiffto=prev&titles="+wgPageName, function(response, status){
 
				var diffString = response.query.pages[wgArticleId].revisions[0].diff["*"];
 
                                if(diffString == null)
                                {
                                     alert("Request failed!");
                                     diffRequestLocked = "f";
                                     return;
                                }
 
				var newTable = document.createElement("table");
                                newTable.className = "diff";
 
                                var colGroup = document.createElement("colgroup");
                                var diffCol = document.createElement("col");
                                diffCol.className = "diff-marker";
                                colGroup.appendChild(diffCol);
                                diffCol = document.createElement("col");
                                diffCol.className = "diff-content";
                                colGroup.appendChild(diffCol);
                                diffCol = document.createElement("col");
                                diffCol.className = "diff-marker";
                                colGroup.appendChild(diffCol);
                                diffCol = document.createElement("col");
                                diffCol.className = "diff-content";
                                colGroup.appendChild(diffCol);
                                newTable.appendChild(colGroup);
 
				$(newTable).append(diffString);
				$(newTable).insertAfter("#"+ button.id);
 
                                $(button).attr("disabled", "disabled");
                                //$(button).click(function(){return false;});
 
				diffRequestLocked = "f";
                                });
 
			}
		}
 
		this.showError = function( errorMessage ) {
			var container = document.getElementById( 'mw-history-compare' );
			container.innerHTML = '<span style="padding: 4px; color: #885555; font-weight: bold;">userhist error: ' + errorMessage + '</span>';
 
			return true;
		}
 
		this.convertTimestamp = function (timestamp) {
			var regTest = /([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z/g;
			regTest.lastIndex = 0;
			time = regTest.exec(timestamp);
			if (time == null) return 'failed to parse timestamp';
 
			var d = new Date();
			var hourOffset = (d.getTimezoneOffset() / 60) * -1;
			var h = parseInt( time[4], 10 ) + hourOffset;
			if  (h < 10 ) h = '0' + h;
 
			var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
			var month = parseInt(time[2], 10);
 
			var newStamp = h + ':' + time[5] + ', ' + time[3] + ' ' + months[month-1] + ' ' + time[1]; 
 
			return newStamp;
		}
 
		this.parseComment = function (comment) {
			if (comment == null) return '';
 
			comment = comment.replace('/*', '<span class="autocomment">?');
			comment = comment.replace('*/', '</span>');
 
			comment = comment.replace(/\[\[(.+?)(#.+?)?(?:\|(.+?))\]\]/g, "<a href=\"/wiki/$1$2\" title=\"$3\">$3</a>");
			comment = comment.replace(/\[\[(.+?)(#.+?)?\]\]/g, "<a href=\"/wiki/$1$2\" title=\"$1\">$1</a>");
 
			comment = '(<span class="comment">' + comment + '</span>)';
 
			return comment;
		}
 
		this.manageSize = function () {
			var regTest = /class="history-size">\(([,0-9]+?) +?bytes\)<\/span>/ig, regMatch;
			var col = { 'add': '#006400', 'remove': '#8b0000' }, results = [], i = 0;
 
			while ( regMatch = regTest.exec ( document.getElementById ( 'pagehistory' ).innerHTML ) ) {
				results [ i ++ ] = parseInt ( regMatch [1].replace ( ',', '' ), 10 );
 
				if ( i > histlimit ) break;
			}
 
			for ( var i = 0, l = results.length; i < ( l - 1 ); i ++ ) {
				var addition = results [i] - results [i + 1];
				if ( addition === 0 ) { var rep = '<span style="color: #555555; ">0</span>'; } else
				if ( addition < 0 ) { var rep = '<span style="color: ' + col ['remove'] + '; font-weight: bold;">' + addition + '</span>'; } else { var rep = '<span style="color: ' + col ['add'] + '; font-weight: bold;">+' + addition + '</span>'; }
 
				document.getElementById ( 'pagehistory' ).innerHTML = document.getElementById ( 'pagehistory' ).innerHTML.replace ( /class="history-size">\(([,0-9]+?) +?bytes\)<\/span>/i, "class=\"historysize\">(" + rep + ", $1 bytes)</span>" );
			}
		}
 
		this.init = function () {
			if ( wgAction == 'history' ) {
				if ( ( window.location.href.indexOf ( '&isolate=' ) > -1 ) && ( window.location.href.indexOf ( '&offset=' ) == -1 ) && ( window.location.href.indexOf ( '&limit=' ) == -1 ) ) {
					var user = window.location.href.substr ( window.location.href.indexOf( '&isolate=' ) + 9 );
					me.getUserHist ( user );
				} else {
					//me.manageSize (); - FIXME: prevents the history diff selectors from working correctly
					var user = '';
				}
 
				me.displayBox ( user );
			}
 
			else if ( ( wgAction == 'view' ) && ( wgPageName == 'Special:Contributions' ) ) {
				var regContent = document.getElementById ( 'contentSub' ).innerHTML;
				var regTest = /for .*?(?:title="(.+?)">|([\.0-9]+?) \()/i;
				var regMatch = regTest.exec ( regContent );
				if ( regMatch[1] === undefined ) {
					var user = regMatch[2];
				} else {
					var user = regMatch[1];
				}
 
				var bodyContent = document.getElementById ( 'bodyContent' );
				regTest.lastIndex = 0;
				regTest = /(title="([^<]+?)">hist<\/a>)\)/ig;
				bodyContent.innerHTML = bodyContent.innerHTML.replace ( regTest, "$1 | <a href=\"/w/index.php?title=$2&action=history&isolate=" + user + "\">all</a>\)" );
			}
		}
	}
 
	importScript ( 'User:Ale_jrb/Scripts/waLib.js' );
	var userHist = new userHistMain ();
	hookEvent ( 'load', userHist.init );

// Add [[WP:Reflinks]] launcher in the toolbox on left
addOnloadHook(function () {
 addPortletLink(
  "p-tb",     // toolbox portlet
  "http://toolserver.org/~dispenser/cgi-bin/webreflinks.py/" + wgPageName
   + "?client=script&citeweb=on&overwrite=&limit=20&lang=" + wgContentLanguage,
  "Reflinks"  // link label
)});

/* Ajax batch delete thingy, version [0.1.1b]
Originally from: http://en.wikipedia.org/wiki/User:Splarka/ajaxbatchdelete.js
 
Notes:
* It is a bit verbose, after debugging perhaps some output should be removed.
* It waits 1 second after every delete before starting the next.
* Can be aborted by simply deleting the contents of the textarea, or leaving the page.
* Stops when it hits a blank line.
* Nonfatal errors (skip to next line):
** Bad character or malformed line
** Bad token
** Unexpected response
* Pauses in execution can be added with a blank line.
 
To do:
* Cache the token if two the same?
** Please note the delete token is not guaranteed to be static, but currently it always is.
*/
 
addOnloadHook(function() {
  addPortletLink('p-tb','/wiki/Special:BlankPage?blankspecial=ajaxbd','Batch Delete');
});
 
if(wgCanonicalSpecialPageName && wgCanonicalSpecialPageName.toLowerCase() == 'blankpage' && queryString('blankspecial') == 'ajaxbd') {
  document.title = 'Ajax Batch Deletion';
  addOnloadHook(abdForm);
}
 
function abdForm() {
  addPortletLink('p-tb','/wiki/Special:Log/delete?user=' + encodeURIComponent(wgUserName),'My delete log');
 
  //subvert this Special: page to our own needs.
  var con = document.getElementById('content') || document.getElementById('mw_content');
  var bcon = document.getElementById('bodyContent') || document.getElementById('mw_contentholder');
  var fh = getElementsByClassName(con,'h1','firstHeading')[0];
  while(fh.firstChild) fh.removeChild(fh.firstChild)
  fh.appendChild(document.createTextNode('Ajax Batch Deletion'));
  for(var i=0;i<bcon.childNodes.length;i++) {
    bcur = bcon.childNodes[i];
    if(bcur.id != 'siteSub' && bcur.id != 'contentSub' && bcur.className != 'visualClear') {
      while(bcur.firstChild) bcur.removeChild(bcur.firstChild)
      if(bcur.nodeType == 3) bcur.nodeValue = '';
    }
  }
 
  //generate content
  var form = document.createElement('form');
   form.appendChild(document.createTextNode('List of pages to delete:'));
   form.appendChild(document.createElement('p'));
   form.setAttribute('action','javascript:void(0);');
   var txt = document.createElement('textarea');
    txt.style.height = '20em';
    txt.style.width = '50%';
    txt.setAttribute('id','abd-textarea');
   form.appendChild(txt);
   form.appendChild(document.createElement('p'));
   var lab1 = document.createElement('label');
    lab1.setAttribute('for','abd-reason')
    lab1.appendChild(document.createTextNode('Deletion reason: '));
   form.appendChild(lab1);
   var inp1 = document.createElement('input');
    inp1.style.width = '20em';
    inp1.setAttribute('type','text');
    inp1.setAttribute('id','abd-reason');
   form.appendChild(inp1);
   form.appendChild(document.createElement('p'));
   var sub1 = document.createElement('input');
    sub1.setAttribute('type','button');
    sub1.setAttribute('id','abd-startbutton');
    sub1.setAttribute('value','start');
    sub1.setAttribute('onclick','abdStart()');
   form.appendChild(sub1);
  bcon.appendChild(form);
  var pre = document.createElement('pre');
   pre.setAttribute('id','abd-output');
  bcon.appendChild(pre);
}
 
function abdStart() {
  document.getElementById('abd-startbutton').setAttribute('disabled','disabled');
  var out = document.getElementById('abd-output');
  var txt = document.getElementById('abd-textarea');
  var deletes = txt.value.split('\n');
  var page = deletes[0];
  if(page == '') {
    out.appendChild(document.createTextNode('* Done! Nothing left to do, or next line is blank.\n'));
    document.getElementById('abd-startbutton').removeAttribute('disabled');
  } else {
    var badchars = /(\#|\<|\>|\[|\]|\{|\}|\|)/;
    if(badchars.test(page)) {
      out.appendChild(document.createTextNode('! Illegal characters detected, skipping:' + page + '\n'));
      setTimeout('abdStart()',1000);
    } else {
      out.appendChild(document.createTextNode('> Attempting to delete [[' + page + ']]\n'));
      abdGetToken(page);
    }
  }
  deletes = deletes.slice(1,deletes.length);
  txt.value = deletes.join('\n');
}
 
function abdGetToken(page) {
  var out = document.getElementById('abd-output');
  out.appendChild(document.createTextNode(' > Fetching delete token for [[' + page + ']]\n'));
  var url = wgScriptPath + '/api.php?action=query&prop=info&indexpageids=1&intoken=delete&format=json&titles=' + encodeURIComponent(page);
  var req = sajax_init_object();
  req.open('GET', url, true);
  req.onreadystatechange = function() {
    if(req.readyState == 4 && req.status == 200) {
      eval("abdDelete(" + req.responseText + ",'" + req.responseText.replace(/\'/g,"`") + "','" + page + "')");
    }
  }
  req.send(null);
}
 
function abdDelete(obj,txt,page) {
  var out = document.getElementById('abd-output');
  if(obj['error']) {
    out.appendChild(document.createTextNode(' ! Api error: ' + obj['error']['code'] + ' - ' + obj['error']['info'] + '\n'));
    return;
  }
  if(!obj['query'] || !obj['query']['pageids'] || !obj['query']['pages'][obj['query']['pageids'][0]] || !obj['query']['pages'][obj['query']['pageids'][0]]['deletetoken']) {
    out.appendChild(document.createTextNode('  ? Unexpected response: ' + txt + '\n'));
    return;
  }
  var token = obj['query']['pages'][obj['query']['pageids'][0]]['deletetoken'];
  out.appendChild(document.createTextNode('  > Token found, attempting delete\n'));
  var reason = document.getElementById('abd-reason').value;
 
  var params = 'action=delete&format=json&token=' + encodeURIComponent(token) + '&title=' + encodeURIComponent(page) + '&reason=' + encodeURIComponent(reason);
  var url = wgScriptPath + '/api.php';
 
  var req = sajax_init_object();
  req.open('POST', url, true);
  req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  req.setRequestHeader('Content-length', params.length);
  req.setRequestHeader('Connection', 'close');
  req.onreadystatechange = function() {
    if(req.readyState == 4 && req.status == 200) {
      eval("abdDeleteAftermath(" + req.responseText + ",'" + req.responseText.replace(/\'/g,"`") + "')");
    }
  }
  req.send(params);
}
 
function abdDeleteAftermath(obj,txt) {
  var out = document.getElementById('abd-output');
  if(obj['error']) {
    out.appendChild(document.createTextNode('   ! Api error: ' + obj['error']['code'] + ' - ' + obj['error']['info'] + '\n'));
  } else if(obj['delete'] && obj['delete']['title']) {
    out.appendChild(document.createTextNode('   > Page [[' + obj['delete']['title'] + ']] deleted\n'));
  } else {
    out.appendChild(document.createTextNode('   ? Unexpected response: ' + txt + '\n'));
    return;
  }
  setTimeout('abdStart()',1000);
}
 
function queryString(p) {
  var re = RegExp('[&?]' + p + '=([^&]*)');
  var matches;
  if (matches = re.exec(document.location)) {
    try { 
      return decodeURI(matches[1]);
    } catch (e) {
    }
  }
  return null;
}

//Mass rollback function
//Written by John254
//Adapted from User:Mr.Z-man/rollbackSummary.js
//Instructions: Selecting the "rollback all" tab when viewing a user's contributions history
//will open all rollback links displayed there. (Use with caution)
 
function rollbackEverythingButton() {
  var hasRollback = getElementsByClassName(document, "span", "mw-rollback-link");
  if (hasRollback[0] && (document.title.indexOf("User contributions") != -1) ) {
    addPortletLink('p-cactions', 'javascript:rollbackEverything()', "rollback all", "ca-rollbackeverything", "rollback all edits displayed here");
  }
}
addOnloadHook(rollbackEverythingButton);
function rollbackEverything() {
    for (var i in document.links) {
      if (document.links[i].href.indexOf('action=rollback') != -1) {
        window.open(document.links[i].href);
      }
    }
}

importScript("User:Drilnoth/delresized.js");

//Mass rollback function
//Written by John254
//Adapted from User:Mr.Z-man/rollbackSummary.js
//Instructions: Selecting the "rollback all" tab when viewing a user's contributions history
//will open all rollback links displayed there. (Use with caution)
 
function rollbackEverythingButton() {
  var hasRollback = getElementsByClassName(document, "span", "mw-rollback-link");
  if (hasRollback[0] && (document.title.indexOf("User contributions") != -1) ) {
    addPortletLink('p-cactions', 'javascript:rollbackEverything()', "rollback all", "ca-rollbackeverything", "rollback all edits displayed here");
  }
}
addOnloadHook(rollbackEverythingButton);
function rollbackEverything() {
    for (var i in document.links) {
      if (document.links[i].href.indexOf('action=rollback') != -1) {
        window.open(document.links[i].href);
      }
    }
}

importScript('User:Dr_pda/prosesize.js'); //[[User:Dr_pda/prosesize.js]]