User:DerHexer/testglobalrename.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.
/*
    Support for global renaming of user names.

    Authors: [[:m:User:DerHexer]], [[:de:Benutzer:Gorlingor]], [[:m:User:Hoo man]] August 2012
    License: Quadruple licensed GFDL, GPL, LGPL and Creative Commons Attribution 3.0 (CC-BY-3.0)

    This tool uses code from hideuser at Meta.
        [[:m:MediaWiki:MediaWiki:Gadget-hideuser.js]]
        Authors: [[:m:User:DerHexer]] and [[:m:User:Erwin]], July 2009 - August 2009
        License: Quadruple licensed GFDL, GPL, LGPL and Creative Commons Attribution 3.0 (CC-BY-3.0)

    Which in turn uses code from SBHandler at Meta.
        [[:m:MediaWiki:Gadget-SBHandler.js]]
        Author: [[:m:User:Erwin]], October 2008 - February 2009
        License: Quadruple licensed GFDL, GPL, LGPL and Creative Commons Attribution 3.0 (CC-BY-3.0)
        
    Which in turn uses code from DelReqHandler at Commons.
        [[:Commons:MediaWiki:Gadget-DelReqHandler.js]] (oldid=15093612)
        Author: [[:Commons:User:Lupo]], October 2007 - January 2008
        License: Quadruple licensed GFDL, GPL, LGPL and Creative Commons Attribution 3.0 (CC-BY-3.0)

    Tested only in Firefox.
*/
// <nowiki>

/*global mw */
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, loopfunc:true, bitwise:true, undef:true, browser:true, jquery:true, indent:4, maxerr:50, white:false */

/**** Guard against double inclusions */
 
if (typeof LHHandler === 'undefined') {

	var LHUtils = {
		// userIsInGroup (from User:Hoo_man/functions.js)
		userIsInGroup : function (group) {
			return ($.inArray(group, mw.config.get('wgUserGroups')) !== -1);
		}

	}; // End of LHUtils

	/**** Enable the whole shebang only for stewards. */
	if (LHUtils.userIsInGroup('steward')) {
		
		var LHHandler = {
			user            : '',
			newuser         : '',
			reason          : '',
			query           : '',
			params          : '',
			both            : '',
			projects        : 0,
			completed       : 0,
			error           : false,
			
			addLinks: function() {
				var f, l, p, d, t, tr1, td1, td2, input1, tr2, td3, td4, input2, div, s, ul;
				// Create fieldset
				f = document.createElement('fieldset');

				// Create legend
				l = document.createElement('legend');
				l.appendChild(document.createTextNode('Global rename'));
				f.appendChild(l);
				
				// Create information
				p = document.createElement('p');
				p.appendChild(document.createTextNode('Please enter the new user name and a valid reason before you submit your request.'));
				f.appendChild(p);

				// Add div with progress information and link to globally rename users.
				d = document.createElement('div');
				d.setAttribute('style', 'padding: 5px; margin: 5px;');

				// Create table
				t = document.createElement('table');
				tr1 = document.createElement('tr');
				tr1.setAttribute('id', 'mw-centralauth-globalrename-newuser');
				td1 = document.createElement('td');
				td1.setAttribute('class', 'mw-label');
				td1.appendChild(document.createTextNode('New user name:'));
				tr1.appendChild(td1);
				td2 = document.createElement('td');
				input1 = document.createElement('input');
				input1.setAttribute('id', 'globalrename-newuser');
				input1.setAttribute('name', 'newuser');
				td2.appendChild(input1);
				tr1.appendChild(td2);
				t.appendChild(tr1);

				tr2 = document.createElement('tr');
				tr2.setAttribute('id', 'mw-centralauth-globalrename-reason');
				td3 = document.createElement('td');
				td3.setAttribute('class', 'mw-label');
				td3.appendChild(document.createTextNode('Reason:'));
				tr2.appendChild(td3);
				td4 = document.createElement('td');
				input2 = document.createElement('input');
				input2.setAttribute('id', 'globalrename-reason');
				input2.setAttribute('name', 'reason');
				td4.appendChild(input2);
				tr2.appendChild(td4);
				t.appendChild(tr2);
				d.appendChild(t);

				// Add submit button/container for spinner.
				div = document.createElement('div');
				div.setAttribute('id', 'globalrename-submit');
				s = document.createElement('input');
				s.setAttribute('type', 'submit');
				s.setAttribute('value', 'Global rename account');
				$( s ).on('click', LHHandler.checkCircumstances);
				div.appendChild(s);
				d.appendChild(div);

				// Add container for list for logging.
				div = document.createElement('div');
				div.setAttribute('style', 'float:left;');
				ul = document.createElement('ul');
				ul.setAttribute('id', 'mw-centralauth-globalrename-status');
				div.appendChild(ul);
				d.appendChild(div);
				f.appendChild(d);
				document.getElementsByTagName('fieldset')[3].parentNode.insertBefore(f, document.getElementsByTagName('fieldset')[3].nextSibling);
			}, // End addLinks()

			checkCircumstances : function() {
				var edits, globallock, localblock;
				// Fresh start. No errors yet.
				LHHandler.error = false;

				// Get edits.
				edits = document.getElementsByTagName('ul')[0].getElementsByTagName('li')[3].innerHTML.replace(/<.*>/,'').replace(/,/,'');
				if (edits < 100000) {
				  globallock = document.getElementsByTagName('ul')[0].getElementsByTagName('li')[4].innerHTML.replace(/<.*>/,'');
                                  if (globallock.search(/no/) != -1) {
                                    localblock = document.getElementById('mw-centralauth-merged').getElementsByTagName('tbody')[0];
                                    if (localblock.innerHTML.search(/Blocked/) == -1) {
					    LHHandler.parsePage();
                                    } else {
					    LHHandler.logMsg('Account is local locked and thus should not be renamed.', true);
                                    }
				  } else {
					  LHHandler.logMsg('Account is global locked and thus should not be renamed.', true);
				  }
				} else {
					LHHandler.logMsg('Too many global edits. Cannot be renamed without damaging our servers.', true);
				}
			}, // End checkCircumstances()
					
			parsePage : function() {
				var dspinner, div, img, i;
				// Add spinner.
				dspinner = document.getElementById('globalrename-submit');
				div = document.createElement('div');
				div.setAttribute('id', 'dspinner');
				div.setAttribute('style', 'float:left; width: 30');
				img = document.createElement('img');
				img.setAttribute('id', 'globalrenamerunning');
				img.setAttribute('height', '20');
				img.setAttribute('width', '20');
				img.setAttribute('alt', 'script running');
				img.setAttribute('src', '//upload.wikimedia.org/wikipedia/commons/3/32/Loader3.gif');
				div.appendChild(img);
				dspinner.replaceChild(div, dspinner.firstChild);

				// Get variables.
				LHHandler.user = document.getElementById('target').value; 
				LHHandler.newuser = document.getElementById('globalrename-newuser').value; 
				LHHandler.reason = document.getElementById('globalrename-reason').value; 

				// Get projects.
				var trs = document.getElementById('mw-centralauth-merged').getElementsByTagName('table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr');
				LHHandler.projects = trs.length-1;
									
				// Loop over projects.
				for (i=0; i<LHHandler.projects; i++) {
					var project = trs[i].getElementsByTagName('td')[1].getElementsByTagName('a')[0].innerHTML.split('.');
					project = project[1]+'/'+project[0];
					if(project==='mediawiki/www')project='wikipedia/mediawiki';
					if(project==='wikimedia/species')project='wikipedia/species';
					if(project==='wikimedia/meta')project='wikipedia/meta';
					if(project==='wikimedia/commons')project='wikipedia/commons';
					if(project==='org/wikisource')project='wikipedia/sources';

                                        if (trs[i].getAttribute('class') && (trs[i].getAttribute('class') == 'unattached-row')) {
                                          LHHandler.logMsg('The unattached account on ' + project + ' was not renamed.');
                                          LHHandler.checkStatus();
                                        } else {
					  LHHandler.query = 'https://secure.wikimedia.org/' + project + '/wiki/Special:RenameUser?';
					  LHHandler.query += 'oldusername=' + encodeURIComponent(LHHandler.user);
					  LHHandler.query += '&newusername=' + encodeURIComponent(LHHandler.newuser);
					  LHHandler.query += '&reason=' + encodeURIComponent(LHHandler.reason);
					  LHHandler.query += '&uselang=qqx'; //this will save us from a lot of pain
					  LHHandler.getRequest(LHHandler.query, LHHandler.renameUser, project);
                                        }
				}

			}, // End parsePage()

			// Titleblacklist test?
			
			renameUser : function (request, project) {
				var token = request.responseText;
				if(token) token = token.match(/<input(.*?)name="token/);
				if(token) token = token[0].match(/value="(.*?)"/);
				if(token) token = token[1];
				if(token) {
					LHHandler.postRequest(LHHandler.query, LHHandler.checkStatus, LHHandler.params + "&token="+encodeURIComponent(token)+"&movepages=1&confirmaction=1&submit=Submit", project);
				} else {
					LHHandler.logMsg('Token could not be found on ' + project + '.', true);
				}
			}, //End renameUser()
			
			checkStatus : function() {
				var img, alt, src;
				// Checking status means that the process for a project has
				// ended.
				LHHandler.completed += 1;
				
				// Set image accordingly.
				if (LHHandler.completed === LHHandler.projects) {
					img = document.createElement('img');
					img.setAttribute('id', 'globalrenamerunning');
					img.setAttribute('height', '20');
					img.setAttribute('width', '20');
					if (LHHandler.error) {
						alt = 'Script stopped with errors';
						src = '//upload.wikimedia.org/wikipedia/commons/thumb/a/a2/X_mark.svg/525px-X_mark.svg.png';
					} else {
						alt = 'Script stopped';
						src = '//upload.wikimedia.org/wikipedia/commons/thumb/f/fb/Yes_check.svg/600px-Yes_check.svg.png';
					}
					img.setAttribute('src', src);
					img.setAttribute('alt', alt);
					document.getElementById('dspinner').replaceChild(img, document.getElementById('globalrenamerunning'));
				}      
			}, //End checkStatus()
			
			logMsg : function (msg, error) {
				var li;
				li = document.createElement('li');
				if (error) {
					LHHandler.error = true;
					li.setAttribute('style', 'color:red; font-weight:bold;');
				}
				li.appendChild(document.createTextNode(msg));
				document.getElementById('mw-centralauth-globalrename-status').appendChild(li);
			}, //End logMsg()
			
			getRequest : function(url, callback, args) {
				var request = new XMLHttpRequest() ;
				if(request === null) {
					return null;
				}    
				request.open('GET', url, false);
				request.onreadystatechange = function () {
					if(request.readyState===4) {
						callback(request, args);
					}
				};
				request.setRequestHeader('Pragma', 'cache=yes');
				request.setRequestHeader('Cache-Control', 'no-transform');
				request.send(null);
			},

			postRequest : function(url, callback, params, args) {
				var request = new XMLHttpRequest();
				if(request === null) {
					return null;
				}
				request.open('POST', url, false);
				request.onreadystatechange = function () {
					if(request.readyState===4 && (request.status===200 || request.status===302)) {
						LHHandler.logMsg("Account renamed on " + args+ ".", false);
						callback(request);
					} else {
						LHHandler.logMsg('Account could not be renamed on ' + args + '.', true);
					}
				};

				request.setRequestHeader('Content-type','application/x-www-form-urlencoded');
				request.setRequestHeader('Content-length', params.length);
				request.setRequestHeader("Pragma", "cache=yes");
				request.setRequestHeader("Cache-Control", "no-transform");
				request.send(params);
			}

		}; // End of LHHandler
		
		/**
		 * Only for [[Special:CentralAuth]] via a secure connection.
		 * Secure connection is needed for all projects to be at the
		 * same domain, such that we can make XMLRequests to all
		 * projects.
		 */
		if(mw.config.get('wgServer').indexOf('secure.wikimedia') !== -1 && mw.config.get('wgCanonicalSpecialPageName') === 'CentralAuth') {
			$(document).ready(LHHandler.addLinks);
		}

	} // End of steward check
 
} // End of idempotency check
// </nowiki>
// [[Category:Gadgets|LHHandler.js]]