Jump to content

User:Bornhj/monobook.js

From Wikipedia, the free encyclopedia
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.
/* <pre><nowiki>
|| My monobook.js
|| Based loosly upon [[User:Essjay]]'s monobook
|| Creates its own "WP" psuedo-namespace to avoid conflicts
|| Props to everyone whose code is in here somewhere
*/

// Declare our namespace - everyone loves namespaces
var WP = {
	// Function: addOnload
	// Add an onload function
	addOnload: function(eventLoad) {
		if (window.addEventListener) window.addEventListener("load", eventLoad, false);
		else if (window.attachEvent) window.attachEvent("onload", eventLoad);
	},
	
	// Function: addlilink
	// Preps a monobook tab link
	addlilink: function(tabs, url, name, id){
	    var na = document.createElement('a');
	    na.href = url;
	    na.appendChild(document.createTextNode(name));
	    var li = document.createElement('li');
	    li.id = id;
	    li.appendChild(na);
	    tabs.appendChild(li);
	    return li;
	},
	
	// Function: showtime
	// Displays UTC Time
	showtime: function() {
	    var timerID;
	    var now = new Date();
	    var timeValue = now.toUTCString().replace(/GMT/, "UTC");
	    document.getElementById('utcdate').firstChild.innerHTML = timeValue;
	    timerID = setTimeout('WP.showtime()', 100);
	},
	
	// Function: addTab
	// Wrapper for addlilink() to add to the monobook top tabs bar
	addTab: function(url, name, id, title, key){ 
	    var tabs = document.getElementById('p-cactions').getElementsByTagName('ul')[0];
	    WP.addlilink(tabs, url, name, id, title, key);
	},
	
	// Function: inc
	// Includes a javascript file
	inc : function(file) {
	  var lt = String.fromCharCode(60);
	  var gt = String.fromCharCode(62);
	  document.writeln(lt+'script type="text/javascript" src="/w/index.php?title='+file+'&amp;action=raw&amp;ctype=text/javascript&amp;dontcountme=s"'+gt+lt+'/script'+gt);
	},
	
	// Function: stopRedlinksEditing
	// Removes &action=edit from redlinks 
	stopRedlinksEditing: function(){ 
	    var len=document.links.length;
	    for(var i=0; i<len; ++i) {
	        var l=document.links[i];
	        if (l.className=='new') {
	            l.href=l.href.replace('&action=edit', '');
	        }
	    }
	},
	
	// Function: addForceSummary
	// Adds the onclick event to force an edit summary
	addForceSummary: function() {
	    if(!/&action=edit/.test(window.location.href) && !/&action=submit/.test(window.location.href)) return;
	    if(/&section=new/.test(window.location.href)) return;
	    if(!document.forms.editform) return;
	    document.forms.editform.wpSave.onclick = WP.forceSummary;
	},
	
	// Function: forceSummary
	// Checks the summary and prompts if needed
	forceSummary: function() {
	    if(!document.forms.editform.wpSummary.value.replace(/^(?:\/\\*.*\\*\/)? *(.*) *$/,'$1'))
	    {
	        var r = prompt('Are you sure you want to submit without adding a summary?\nTo add a summary, type it in the box below:',document.forms.editform.wpSummary.value);
	        if(r == null) { return false; }
	        document.forms.editform.wpSummary.value = r;
	    }
	    return true;
	},
	
	// Function: warningTemplate
	// Inserts a specified test template
	warningTemplate: function(template, needsPage, alternate, prePage) {
		if ( !prePage ) {
			if ( needsPage ) {
				var page = prompt("Vandalism to which article?");
				if ( page == null || page == "" ) {
					var edit = "{{subst:" + alternate + "}} ~~" +  "~~";
					var summary = alternate;
				}
				else {
					var edit = "{{subst:" + template + "|" + page + "}} ~~" + "~~";
					var summary = template + " - [[" + page + "]]";
				}
			}
			else {
				var edit = "{{subst:" + template + "}} ~~" + "~~";
				var summary = template;
			}
		}
		else {
			var edit = "{{subst:" + template + "|" + unescape(prePage).replace(/_/g, ' ') + "}} ~~" + "~~";
			var summary = template + " - [[" + unescape(prePage).replace(/_/g, ' ') + "]] (using [[User:Bornhj/gm.js|GML]])";
		}
	  var f = document.editform, t = f.wpTextbox1;
	  if (t.value.length > 0)
	    t.value += '\n';
	  t.value += edit;
	  f.wpSummary.value = summary;
	  f.wpMinoredit.checked = "";
	},
	
	// Function: init
	// Initiates all the other JS
	initJS: function() {
		// Grab our tabs
		var thething = document.getElementById("column-one");
		var tabs = thething.getElementsByTagName('div')[0].getElementsByTagName('ul')[0];
		// Grab our username
		var userName = document.getElementById('pt-userpage').getElementsByTagName('a')[0].innerHTML;
	
		// Add tabs for editing user talk pages
		if ( wgNamespaceNumber == 3 && document.getElementById('wpTextbox1') ) {
			var queryParams = WP.getQueryParams(document.location.href);
			if ( queryParams['fakeaction'] == 'rbwarn' ) {
				// GML warnings
				var page = escape(queryParams['page']);
			}
			else {
				var page = null;
			}
			WP.addTab('javascript:WP.warningTemplate("test1-n", true, "test1", ' + (!page?'null':'"'+page+'"') + ')',"t1", 'ca-tmpl-t1');
			WP.addTab('javascript:WP.warningTemplate("test1a-n", true, "test1a", ' + (!page?'null':'"'+page+'"') + ')',"t1a", 'ca-tmpl-t1a');
			WP.addTab('javascript:WP.warningTemplate("test2-n", true, "test2", ' + (!page?'null':'"'+page+'"') + ')',"t2", 'ca-tmpl-t2');
			WP.addTab('javascript:WP.warningTemplate("test2a-n", true, "test2a", ' + (!page?'null':'"'+page+'"') + ')',"t2a", 'ca-tmpl-t2a');
			WP.addTab('javascript:WP.warningTemplate("test3-n", true, "test3", ' + (!page?'null':'"'+page+'"') + ')',"t3", 'ca-tmpl-t3');
			WP.addTab('javascript:WP.warningTemplate("test3a-n", true, "test3a", ' + (!page?'null':'"'+page+'"') + ')',"t3a", 'ca-tmpl-t3a');
			WP.addTab('javascript:WP.warningTemplate("test4-n", true, "test4", ' + (!page?'null':'"'+page+'"') + ')',"t4", 'ca-tmpl-t4');
			WP.addTab('javascript:WP.warningTemplate("bv-n", true, "bv", ' + (!page?'null':'"'+page+'"') + ')',"bv", 'ca-tmpl-bv');
			WP.addTab('javascript:WP.warningTemplate("spam1", true, "null", ' + (!page?'null':'"'+page+'"') + ')',"spam", 'ca-tmpl-spam');
			WP.addTab('javascript:WP.warningTemplate(prompt("Which template?"), true, "null", ' + (!page?'null':'"'+page+'"') + ')',"cus", 'ca-tmpl-cus');
		}
		
		// Add tabs for a User page FIXME: wgNamespace 2/3
		if ( document.title.indexOf("User") == 0 ) {
			// Work out their username
			if ( document.getElementById('ca-viewsource') ) {
				var editlk = document.getElementById('ca-viewsource').getElementsByTagName('a')[0].href;
			}
			else {
				var editlk = document.getElementById('ca-edit').getElementsByTagName('a')[0].href;
			}
			editlk = editlk.substring(editlk.indexOf('title=') + 6, editlk.lastIndexOf('&action=edit'));
			editlk = editlk.substring(editlk.indexOf(':') + 1);
			var slloc = editlk.indexOf('/');
			if(slloc > 0) editlk = editlk.substring(0, slloc);
			
			// Add "listusers" tab
			WP.addTab('/w/index.php?title=Special:Listusers&group=&username=' + editlk, 'list', '');
			
			// Add "contributions" tab
			WP.addTab('/wiki/Special:Contributions/' + editlk, 'contribs', '');
			
			// Add "userspace" tab
			WP.addTab('/w/index.php?title=Special:Prefixindex&namespace=2&from=' + editlk, 'userspace', '');
			
			// Add "edit count" tabs
			WP.addTab('http://en.wikipedia.org/wiki/User:Interiot/Tool2/code.js?username=' + editlk, 'count (js)', '');
			WP.addTab('http://tools.wikimedia.de/~essjay/edit_count/Count.php?username=' + editlk + '&submit=Count', 'count (ts)', '');
			// Add "whois" tab
			WP.addTab('http://tools.wikimedia.de/~essjay/nqt.php?queryType=arin&target=' + editlk, 'whois');
			
			// Add "blocklog" tab
			WP.addTab('/wiki/Special:Log/block?page=User:' + editlk, 'blocklog', 'ca-blocklog');
			
			// Rename the user tab
			document.getElementById('ca-nstab-user').getElementsByTagName('a')[0].innerHTML='user';
		}
		
		// Add the purge and last diff tabs
		if ( document.getElementById('ca-history') ) { // FIXME: use wgIsArticle + wgArticleId (non-existant articles set wgIsArticle to true but have an ID of 0
			var thething = document.getElementById("column-one");
			var tabs = thething.getElementsByTagName('div')[0].getElementsByTagName('ul')[0];
			WP.addTab(document.getElementById('ca-history').getElementsByTagName('a')[0].href.replace( /action=history/, 'diff=0' ), 'last diff', 'ca-diff');
			WP.addTab(document.getElementById('ca-history').getElementsByTagName('a')[0].href.replace( /action=history/, 'action=purge'), 'purge', 'ca-purge');
		}
		
		// Rename interface parts
		if ( document.getElementById('pt-mytalk') ) {
			document.getElementById('pt-mytalk').getElementsByTagName('a')[0].innerHTML='talk';
		}
		if ( document.getElementById('pt-preferences') ) {
			document.getElementById('pt-preferences').getElementsByTagName('a')[0].innerHTML='prefs';
		}
		if ( document.getElementById('pt-watchlist') ) {
			document.getElementById('pt-watchlist').getElementsByTagName('a')[0].innerHTML='w/list';
		}
		if ( document.getElementById('pt-mycontris') ) {
			document.getElementById('pt-mycontris').getElementsByTagName('a')[0].innerHTML='c/tribs';
		}
		if ( document.getElementById('pt-logout') ) {
			document.getElementById('pt-logout').getElementsByTagName('a')[0].innerHTML='logout';
		}
		if ( document.getElementById('pt-mycontris') ) {
			document.getElementById('pt-mycontris').getElementsByTagName('a')[0].href='http://en.wikipedia.org/w/index.php?title=Special:Contributions&target=' +userName + '&offset=0&limit=500';
		}
		if ( document.getElementById('ca-talk') ) {
			document.getElementById('ca-talk').getElementsByTagName('a')[0].innerHTML='talk';
		}
		if ( document.getElementById('ca-edit') ) {
			document.getElementById('ca-edit').getElementsByTagName('a')[0].innerHTML='<span style="padding-left: 50px; padding-right: 50px;">edit</span>';
		}
		if ( document.getElementById('ca-viewsource') ) {
			document.getElementById('ca-viewsource').getElementsByTagName('a')[0].innerHTML='<strike>protected</strike>';
		}
		//Show the UTC clock
		var toplinks = document.getElementById('p-personal').getElementsByTagName('ul')[0];
		WP.addlilink(toplinks, '#', '', 'utcdate');
		WP.showtime();
	},
	
	// Function: loadJS()
	// Loads all the other JS and includes needed files
	loadJS: function() {
		if ( navigator.appVersion.indexOf("MSIE") == -1 ) {
			//addOnload(rearrangeNodes);
			//WP.addOnload(WP.statusChanger);
			WP.addOnload(WP.stopRedlinksEditing); 
			WP.addOnload(WP.initJS);
			//WP.addOnload(WP.addForceSummary);
			popupRevertSummaryPrompt=true;
			popupEditCounterTool='custom';
			popupEditCounterUrl='http://en.wikipedia.org/wiki/Special:Watchlist?ectarget=$1';
			WP.inc('User:Lupin/popupsdev.js');
			WP.inc('User:Cacycle/wikEd.js');
			//WP.inc('User:Lupin/recent2.js');
			//WP.inc('User:Lupin/editcount.js');
			//WP.inc('User:Interiot/Tool2/code.js');
			//WP.inc('User:Bornhj/gm.js');
			//WP.inc('User:Zocky/SearchBox.js');
			//WP.inc('User:Lightdarkness/aiv.js');
		}
	},
	
	// Function: rearrangeNodes()
	// Experimental, adds an empty bar to the bottom of the page
	rearrangeNodes: function() {
		var newNode = document.createElement('div');
		newNode.style.position = "fixed";
		newNode.style.bottom = "0";
		newNode.style.left = "0";
		newNode.style.width = "100%";
		newNode.style.height = "20px";
		newNode.style.backgroundColor = "white";
		newNode.style.border = "1px solid #aaa";
		newNode.style.zIndex = "1000";
		var attachTo = document.getElementById('globalWrapper');
		attachTo.appendChild(newNode);
	},
	
	// Function: addlilinklcon(tabs, url, text, image, id)
	// Adds an li link to the tabs, with an icon
	addlilinkicon: function(tabs, linkURL, linkText, linkImage, linkId) {
	    var na = document.createElement('a');
	    na.href = linkURL;
	    na.appendChild(document.createTextNode(linkText));
	    var li = document.createElement('li');
	    li.id = linkId;
	    li.style.background = "url('" + linkImage + "') top left no-repeat";
	    li.style.paddingLeft = "14px";
	    li.style.textTransform = "none";
	    li.appendChild(na);
	    tabs.appendChild(li);
	    return li;
	},
	
	// Function: createAJAX()
	// Creates an XMLHTTPRequest!
	createAJAX: function() {
		var http = false;
		if (window.XMLHttpRequest) { // gecko, webkit, opera
			http = new XMLHttpRequest();
		} else if (window.ActiveXObject) { // ie
			try {
				http = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
			try {
				http = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
			}
		}
		return http;
	},
	
	// Function: statusChanger()
	// Loads up the status changer (obviously....)
	statusChanger: function() {
		var userName = document.getElementById('pt-userpage').getElementsByTagName('a')[0].innerHTML;
		var theTabs = document.getElementById('p-personal').getElementsByTagName('ul')[0];
		WP.addlilinkicon(theTabs, "javascript:WP.changeStatus('online', this)", "on", "http://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Symbol_support_vote.svg/12px-Symbol_support_vote.svg.png", "p-status-online");
		WP.addlilinkicon(theTabs, "javascript:WP.changeStatus('busy', this)", "busy", "http://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Symbol_delete_vote.svg/12px-Symbol_delete_vote.svg.png", "p-status-busy");
		WP.addlilinkicon(theTabs, "javascript:WP.changeStatus('offline', this)", "off", "http://upload.wikimedia.org/wikipedia/commons/thumb/7/7f/Symbol_oppose_vote.svg/12px-Symbol_oppose_vote.svg.png", "p-status-offline");
	},
	
	// Function: parseXML(XMLString)
	// Parses me some XML
	parseXML: function(XMLString) {
		if (document.implementation.createDocument) {
			var XMLParser = new DOMParser();
			return XMLParser.parseFromString(XMLString, "text/xml");
		}
		else if (window.ActiveXObject) {
			var XMLParser = new ActiveXObject("Microsoft.XMLDOM");
			XMLParser.async = "false";
			ret = XMLParser.loadXML(XMLString);      
			if (!ret)
				return null;
			return XMLParser.documentElement;
		}
		return null;
	},
		
	// Function: changeStatus(newStatus)
	// Does some AJAX voodoo to change status
	changeStatus: function(newStatus, newStatusLink) {
		var httpr = WP.createAJAX();
		httpr.open('GET', 'http://en.wikipedia.org/w/index.php?title=User:Bornhj/Status&action=edit', true);
		httpr.send(null);
		httpr.onreadystatechange = function() {
			if ( httpr.readyState == 4 ) {
				var POSTData = '';
				// Make an XML parser
				// Stolen from godmode-lite
				var editPage = WP.parseXML(httpr.responseText);
				var formElems = editPage.getElementById('editform').getElementsByTagName('input');
				for ( i=0; i<formElems.length; i++ ) {
					if ( formElems[i].name == 'wpSummary' ) {
						formElems[i].value = "Updating status: " + newStatus;
					}
					else if ( formElems[i].name == 'wpMinoredit' ) {
						formElems[i].value = '1';
					}
					else if ( formElems[i].name == 'wpWatchthis' ) {
						formElems[i].value = "on";
					}
					else if ( formElems[i].name == 'wpPreview' ) {
						continue;
					}
					else if ( formElems[i].name == 'wpDiff' ) {
						continue;
					}
					POSTData += escape(formElems[i].name) + '=' + escape(formElems[i].value) + '&';
				}
				POSTData += 'wpTextbox1=' + escape('{{' + 'User:Bornhj/StatusBar|' + newStatus + '|~~' + '~~' + '~}}');
				// POST it back!
				var httpr2 = WP.createAJAX();
				httpr2.open('POST', 'http://en.wikipedia.org/w/index.php?title=User:Bornhj/Status&action=submit', true);
				httpr2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				httpr2.send(POSTData);
				httpr2.onreadystatechange = function() {
					if ( httpr2.readyState == 4 ) {
						var responsePage = WP.parseXML(httpr2.responseText);
						if ( !responsePage.getElementById('editform') ) {
							// Hackish, I know, but it's an easy way to see whether it succeeded :)
							// FIXME: use wgIsArticle?
							alert('Status updated successfully.');
						}
					}
				}
			}
		}
	},
	
	// Function: getQueryParams
	// Returns a hash map of the query params in the specified url
	getQueryParams: function(theUrl) {
		var UrlS = theUrl.split('?')[1];
		var UrlPairs = UrlS.split('&');
		var urlParams = new Object;
		for ( pairId in UrlPairs ) {
			var thisPair = UrlPairs[pairId].split('=');
			urlParams[thisPair[0]] = thisPair[1];
		}
		return urlParams;
	}
}

// Start 'er up!
WP.loadJS();

/*
|| End of monobook.js
|| </nowiki></pre>
*/