Jump to content

User:Dead.rabbit/change.js

From Wikipedia, the free encyclopedia
This is the current revision of this page, as edited by Xaosflux (talk | contribs) at 13:03, 1 February 2019 (Xaosflux moved page User:Md.altaf.rahman/change.js to User:Dead.rabbit/change.js without leaving a redirect: User:Md.altaf.rahman was renamed to User:Dead.rabbit (phab:T212082 appears to have blocked the initial move)). The present address (URL) is a permanent link to this version.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
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.
var conf = window.mw ? mw.config.values : window;	
	var maxfix = 25;
	
	function make (arg, literal) {
		if (!arg) return null;
		return literal ? document.createTextNode (arg) : document.createElement (arg);
	}
	
	function currentTimestamp () {
		var now = new Date();
		var ts  = "" + now.getUTCFullYear();
		function two (s) { return s.substr (s.length - 2); }
		ts = ts
			+ two ('0' + (now.getUTCMonth() + 1))
			+ two ('0' + now.getUTCDate())
			+ two ('00' + now.getUTCHours())
			+ two ('00' + now.getUTCMinutes())
			+ two ('00' + now.getUTCSeconds());
		return ts;
	}
	
	var getJSON = (function () {
		function getRequest () {
			var request = null;
			try {
				request = new window.XMLHttpRequest();
			} catch (anything) {
				if (window.ActiveXObject) {
					try {
						request = new window.ActiveXObject('Microsoft.XMLHTTP');
					} catch (any) {
					}
				} // end if IE
			} // end try-catch
			return request;
		}
		
		function armorUri (uri) {
			// Avoid protocol-relative URIs, IE7 has a bug with them in Ajax calls
			if (uri.length >= 2 && uri.substring(0, 2) == '//') return document.location.protocol + uri;
			return uri;
		}
		
		return function (settings) {
			var req = getRequest();
			if (!req && settings && settings.error) settings.error (req);
			if (!req || !settings || !settings.uri) return req;
			var uri = armorUri (settings.uri);
			var args = settings.data || null;
			var method;
			if (args && uri.length + args.length + 1 > 2000) {
				// We lose caching, but at least we can make the request
				method = 'POST';
				req.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded');
			} else {
				method = 'GET';
				if (args) uri += '?' + args;
				args = null;
			}
			req.open (method, uri, true);
			req.onreadystatechange = function () {
				if (req.readyState != 4) return;
				if (req.status != 200 || !req.responseText || !(/^\s*[\{\[]/.test(req.responseText))) {
					if (settings.error) settings.error (req);
				} else {
					if (settings.success) settings.success (eval ('(' + req.responseText + ')'));
				}
			};
			req.setRequestHeader ('Pragma', 'cache=yes');
			req.setRequestHeader ('Cache-Control', 'no-transform');
			req.send (args);
			return req;
		};
	})();
	/*
	function needsInfobox(wikitext, title) {

		var lwiki = wikitext.toLowerCase();
		var s = lwiki.indexOf("infobox");
		if (s == -1) { // no infobox
			var e = lwiki.indexOf(".jpg");
			if ( e != -1 ) {
				s = wikitext.lastIndexOf(":", e);
				if ( s != -1 && e-s <= 50) { // found an image
					var img = wikitext.substring(s+1, e+4);
					s = wikitext.lastIndexOf("[[", s+1);
					e = wikitext.indexOf("\n", s);
					
					return [s, e, img];
				}
			}
		} 	
		return null;
	}*/
	
	function addinfoboxtext(wikitext, title){
		var start = wikitext.indexOf("\'\'\'");
		if (start != -1) {
			wikitext = wikitext.substring(0, start) + "{{infobox person"+
			"\n|name="+title+
			"\n|image="+
			"\n|caption="+
			"\n|birth_date="+
			"\n|birth_place="+
			"\n|nationality="+
			"\n|alma_mater="+
			"\n|death_date="+
			"\n|death_place="+
			"\n|occupation="+
			"\n}}\n" + wikitext.substring(start);
		}
		return wikitext; 
	}
	
	
	function removepdata(wikitext){
		var s = wikitext.toLowerCase().indexOf("{{"+"persondata");
		if (s != -1) {
			var e = wikitext.indexOf("}}", s);
			if ( e != -1) {
				return wikitext.substring(0, s) + wikitext.substring(e+2);
			}
		} 
		return wikitext;
	}
	
	function addinfobox(json) {
		if (json && json.query) {
			if (json.query.pages) {
				var page = null;
				for (var id in json.query.pages) { 
    				page = json.query.pages[id];
    				break;
				}
				if (page) {
					if (page.revisions && page.revisions.length > 0) {
						// Revisions are sorted by revision ID, hence [0] is the one we asked for, and possibly there's a [1] if we're
						// not on the latest revision (edit conflicts and such).
						var pageText = page.revisions[0]['*'];

						var mdata = addinfoboxtext(pageText, page.title);
						
						//commitForm(page.title, mdata, "Adding infobox");
						alert(page.title);
						commitForm("Halima Begum", mdata, "Adding infobox");
					}
				}
			}
		}
	}
	
	function removepersondata(json) {
		if (json && json.query) {
			if (json.query.pages) {
				var page = null;
				for (var id in json.query.pages) { 
    				page = json.query.pages[id];
    				break;
				}
				if (page) {
					if (page.revisions && page.revisions.length > 0) {
						var pageText = page.revisions[0]['*'];

						if (maxfix > 0) {
							var mdata = removepdata(pageText); 
							if (mdata != pageText) {
								save(page.title, mdata, page.edittoken,"Persondata has been deprecated by [[Wikipedia:Village pump (proposals)/Archive 122#RfC: Should Persondata template be deprecated and methodically removed from articles?|this RfC]]");
							}
						} else if(maxfix === 0) {
							alert("done with 25 pages. reloading...");
							location.reload();
							maxfix -= 1;
						}
					}
				}
			}
		}
	}

       function save(pagename, content, editToken, wsummary) {
		//alert("saving");
		$.post(
       		       wgScriptPath + '/api.php?',
       		         {
            	           action : 'edit',
            	         //format : 'json',
                            title : pagename,
                   	  summary : wsummary,
            	             text : content,
            	    basetimestamp : currentTimestamp (),
            	            token : editToken
        	    }, function( data ) {
        		// do nothing. to check error:
            	         //alert(JSON.stringify(data));
        	       }
    	       );
	}
	
	function _replacelink(wikitext, oldstring, newstring){
		return wikitext.replace(oldstring, newstring);
	}
	
	function replacelink(json) {
		if (json && json.query) {
			if (json.query.pages) {
				var page = null;
				for (var id in json.query.pages) { 
    				page = json.query.pages[id];
    				break;
				}
				if (page) {
					if (page.revisions && page.revisions.length > 0) {
						var pageText = page.revisions[0]['*'];

						if (maxfix > 0) {
							var oldstring = "[[Bangla Academy Award]]";
							var newstring = "[[Bangla Academy Literary Award]]";
							var mdata = _replacelink(pageText, oldstring, newstring); 
							if (mdata != pageText) {
								maxfix -= 1;
								var summary = oldstring + " => " + newstring;
								save(page.title, mdata, page.edittoken, summary);
								
							}
						} else if(maxfix === 0) {
							//alert("done with 25 pages. reloading...");
							//location.reload();
						}
					}
				}
			}
		}
	}
	
	function passInfoBox(wikitext) {
		var i = -1;
		if((i=wikitext.search(/infobox/i)) != -1){
			
			var s = wikitext.indexOf("{{", i);
			var e = wikitext.indexOf("}}", i);

			while ( s != -1 && e > s) {
				s = wikitext.indexOf("{{", s+2);
				e = wikitext.indexOf("}}", e+2);
			}
			
			return e;
		}
		return -1;
	}
	
	function getlinktext(str){
		
		if ((bar=str.indexOf("|")) != -1) {	
			link = str.substring(2, bar);
			text = str.substring(bar+1, str.length-2);
		} else {
			link = text = str.substring(2, str.length-2);
		}
		
		return [link, text];		
	}
	
	function removedups(wikitext){
		var s = passInfoBox(wikitext);
		var i;
		
		var seen = [];
		
		while((i=wikitext.indexOf("[[", s)) != -1) {
			e = wikitext.indexOf("]]", i);
			
			var ahref = wikitext.substring(i, e+2);
			
			var res = getlinktext(ahref);
			var link = res[0];
			var text = res[1];
			
			if(seen[link]) {
				wikitext = wikitext.substring(0, i) + text + wikitext.substring(e+2);
			} else {
				seen[link] = true;
			}
			s = e;
		}
		
		return wikitext;
	}
	
	
	function removeduplicates(json) {
		if (json && json.query) {
			if (json.query.pages) {
				var page = null;
				for (var id in json.query.pages) { 
    				page = json.query.pages[id];
    				break;
				}
				if (page) {
					if (page.revisions && page.revisions.length > 0) {
						var pageText = page.revisions[0]['*'];
						var mdata = removedups(pageText);
						if (mdata != pageText) {
							commitForm(page.title, mdata, "removed overlinking as per ''[[Wikipedia:Tutorial/Wikipedia_links#When to link|When To Link]]''");
						}
					}
				}
			}
		}
	}
	
	function findnoinfobox(json) {
		if (json && json.query) {
			if (json.query.pages) {
				var page = null;
				for (var id in json.query.pages) { 
    				page = json.query.pages[id];
    				break;
				}
				if (page) {
					if (page.revisions && page.revisions.length > 0) {
						var pageText = page.revisions[0]['*'];

						if (maxfix > 0) {
							//if(pageText.toLowerCase().indexOf("religion") != -1) {
							//if(/religion\s+=/.test(pageText)){
							//if(/columns-list/.test(pageText) && ! /colwidth/.test(pageText) ){
							if(/birth\sdate/.test(pageText) && ! /df=y/.test(pageText)){
								maxfix -= 1;
								open("http://en.wikipedia.org/w/index.php?title="+page.title+"&action=edit");
							}
						} else if(maxfix === 0) {
							location.reload();
							maxfix -= 1;
						}
					}
				}
			}
		}
	}
	
	function getPage(pagename, callback){
		//alert(conf.wgServer + conf.wgScriptPath + '/api.php');
		getJSON ({
			uri : conf.wgServer + conf.wgScriptPath + '/api.php',
			data : 'format=json&action=query&rawcontinue=&titles=' + encodeURIComponent (pagename)
				+ '&prop=info%7Crevisions%7Clanglinks&inprop=watched&intoken=edit'
				+ '&rvprop=content%7Ctimestamp%7Cids%7Cuser&lllimit=500'
				+ '&rvlimit=1&rvdir=older'
				+ '&meta=siteinfo%7Cuserinfo&uiprop=options',
			success : function (json) { callback (json); },
			error : function (req) { /*window.alert("fail" + req.status + ' ' + req.statusText);*/ }
		});
	}
	
	function getPage2(pagename, callback){
		$.post(
			wgScriptPath + '/api.php?',
			{
				format : 'json',
				action : 'query',
				rawcontinue : '',
				titles : encodeURIComponent (pagename),
				prop : "info%7Crevisions%7Clanglinks",
				inprop : "watched",
				intoken : "edit",
				rvprop : "content%7Ctimestamp%7Cids%7Cuser",
				lllimit : "500",
				rvlimit : "1",
				rvdir : "older",
				meta : "siteinfo%7Cuserinfo",
				uiprop : "options"
			},
			function( data ) {
        		callback (data);
            	//alert(JSON.stringify(data));
        	}
		);
	}
	
	function getPage3(pagename, callback){
		$.post(
			wgScriptPath + '/api.php?',
			{
				action : 'parse',
				rawcontinue : '',
				titles : encodeURIComponent (pagename),
				prop : "info%7Crevisions%7Clanglinks",
				inprop : "watched",
				intoken : "edit",
				rvprop : "content%7Ctimestamp%7Cids%7Cuser",
				lllimit : "500",
				rvlimit : "1",
				rvdir : "older",
				meta : "siteinfo%7Cuserinfo",
				uiprop : "options"
			},
			function( data ) {
        		callback (data);
            	//alert(JSON.stringify(data));
        	}
		);
	}
	
	
	function saveForm (pagename, wikitext, editToken, summary) {
		var formContainer = make ('div');
		formContainer.style.display = 'none';
		document.body.appendChild (formContainer);
		formContainer.innerHTML =
			'<form id="hotcatCommitForm" method="post" enctype="multipart/form-data" action="'
			+ conf.wgScript + '?title=' + encodeURIComponent (pagename)
			+ '&action=edit">'
			+ '<input type="hidden" name="wpTextbox1" />'
			+ '<input type="hidden" name="model" value="wikitext" />'
			+ '<input type="hidden" name="format" value="text/x-wiki" />'
			+ '<input type="hidden" name="wpSummary" value="" />'
			+ '<input type="checkbox" name="wpMinoredit" value="1" />'
			+ '<input type="checkbox" name="wpWatchthis" value="0" />'
			+ '<input type="hidden" name="wpAutoSummary" value="" />'
			+ '<input type="hidden" name="wpEdittime" />'
			+ '<input type="hidden" name="wpStarttime" />'
			+ '<input type="hidden" name="wpDiff" value="wpDiff" />'
			+ '<input type="hidden" name="wpSave" value="wpSave" />'
			+ '<input type="hidden" name="oldid" value="0" />'
			+ '<input type="submit" name="hcCommit" value="hcCommit" />'
			+ '<input type="hidden" name="wpEditToken" />'
			+ '<input type="hidden" name="wpUltimateParam" value="1" />'
			+ '</form>';
		
		var commitForm = document.getElementById ('hotcatCommitForm');
		
		commitForm.wpDiff.name = commitForm.wpDiff.value = 'wpSave';
		
		commitForm.wpAutoSummary.value = 'd41d8cd98f00b204e9800998ecf8427e'; // MD5 hash of the empty string
		commitForm.wpMinoredit.checked = true;
		commitForm.wpWatchthis.checked = false;
		commitForm.wpSummary.value = summary;
		commitForm.wpTextbox1.value = wikitext;
		commitForm.wpEdittime.value = commitForm.wpStarttime.value =  currentTimestamp ();
		commitForm.wpEditToken.value = editToken;

		commitForm.hcCommit.click();
	}
	
	function commitForm(pagename, wikitext, summary) {
		var formContainer = make ('div');
		formContainer.style.display = 'none';
		document.body.appendChild (formContainer);
		formContainer.innerHTML =
			'<form id="hotcatCommitForm" method="post" enctype="multipart/form-data" action="'
			+ conf.wgScript + '?title=' + encodeURIComponent (pagename)
			+ '&action=edit">'
			+ '<input type="hidden" name="wpTextbox1" />'
			+ '<input type="hidden" name="model" value="wikitext" />'
			+ '<input type="hidden" name="format" value="text/x-wiki" />'
			+ '<input type="hidden" name="wpSummary" value="" />'
			+ '<input type="checkbox" name="wpMinoredit" value="1" />'
			+ '<input type="checkbox" name="wpWatchthis" value="1" />'
			+ '<input type="hidden" name="wpAutoSummary" value="" />'
			+ '<input type="hidden" name="wpEdittime" />'
			+ '<input type="hidden" name="wpStarttime" />'
			+ '<input type="hidden" name="wpDiff" value="wpDiff" />'
			+ '<input type="hidden" name="oldid" value="0" />'
			+ '<input type="submit" name="hcCommit" value="hcCommit" />'
			+ '<input type="hidden" name="wpEditToken" />'
			+ '<input type="hidden" name="wpUltimateParam" value="1" />'
			+ '</form>';
		
		var commitForm = document.getElementById ('hotcatCommitForm');
		
		commitForm.wpAutoSummary.value = 'd41d8cd98f00b204e9800998ecf8427e'; // MD5 hash of the empty string
		commitForm.wpMinoredit.checked = true;
		commitForm.wpWatchthis.checked = true;
		commitForm.wpSummary.value = summary;
		commitForm.wpTextbox1.value = wikitext;
		commitForm.wpEdittime.value = commitForm.wpStarttime.value =  currentTimestamp ();

		//commitForm.wpDiff.name = commitForm.wpDiff.value = 'wpDiff';
		//commitForm.wpSave.name = commitForm.wpSave.value = 'wpDiff';
		
		commitForm.hcCommit.click();
		
	}
	
	function parseCatElements (json, feachpage) {
		if (json && json.query) {
			if (json.query.categorymembers) {
				var items = json.query.categorymembers
				
				for(var i = 0; i < items.length; i++) { 
					var title = items[i].title.replace(/ /g, "_");

					if (title.indexOf("Category") === 0) {
						getCatElements(title, parseCatElements, feachpage);	
					} else {
						getPage(title, feachpage);	
					}
				}
			}
		}
	}
	
	function getCatElements(catname, callback, callback2){
		getJSON ({
			uri : conf.wgServer + conf.wgScriptPath + '/api.php',
			data : 'format=json&action=query&list=categorymembers'
				+ '&cmtitle=' + encodeURIComponent (catname)
				+ '&cmlimit=500',
			success : function (json) { callback (json, callback2); },
			error : function (req) { /*window.alert("fail" + req.status + ' ' + req.statusText); */}
		});
	}
	
	function pageviewtext(json) {
		alert(json);
	}
	function pageview(callback){
		/*
		$.post("wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/Albert_Einstein/monthly/20050101/20170731", function(data, status){
        	alert("Data: " + data + "\nStatus: " + status);
    	});
    	*/
    	getJSON ({
			uri : "/media/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/Albert_Einstein/monthly/20050101/20170731",
			data : '',
			success : function (json) { alert("nigga"); callback (json); },
			error : function (req) { window.alert("fail" + req.status + ' ' + req.statusText); }
		});
	}
	
	

$( function($) {
	
	var pageviewlink = mw.util.addPortletLink('p-tb', '#', 'Page View', 'ca-pageview');
    $(pageviewlink).click( function(e) {
        e.preventDefault();
    	pageview(pageviewtext);
    	//alert("Aha!");
	});
	
	var addinfolink = mw.util.addPortletLink('p-tb', '#', 'Add infobox', 'ca-addinfobox');
    $(addinfolink).click( function(e) {
        e.preventDefault();
    	getPage(conf.wgPageName, addinfobox);	
	});
	
	var remduplink = mw.util.addPortletLink('p-tb', '#', 'Remove Duplicates', 'ca-remdupbox');
    $(remduplink).click( function(e) {
        e.preventDefault();
    	getPage(conf.wgPageName, removeduplicates);	
	});
	
	var findinfolink = mw.util.addPortletLink('p-tb', '#', 'Find NO infobox', 'ca-findinfobox');
    $(findinfolink).click( function(e) {
        e.preventDefault();
    	getCatElements(conf.wgPageName, parseCatElements, findnoinfobox);
	});

    var recfindPDATAlink = mw.util.addPortletLink('p-tb', '#', 'Fix Persondata', 'ca-recfindpdata');
    $(recfindPDATAlink).click( function(e) {
        e.preventDefault();
    	getCatElements(conf.wgPageName, parseCatElements, removepersondata);
    });
    
    var replink = mw.util.addPortletLink('p-tb', '#', 'Replace Link', 'ca-replink');
    $(replink).click( function(e) {
        e.preventDefault();
    	getCatElements(conf.wgPageName, parseCatElements, replacelink);
    });
    
    function findmostred(x) {
    	alert(x);
    	part = x
    	e = 0
    	s = 0
    	while(true) {
    		s = part.indexOf('<a', e)
    		if (s != -1){ 
    			alert(part.substring(s, s+20));
    		} else {
    			break;
    		}
    		e = s+1
    	}
    	/*
		 var findreds = function() {
            var href = $(this).attr('href');
            if(href !== undefined && href.indexOf('#') != 0) {
            	if (href.indexOf('redlink') != -1) {
            		alert(href);
            	}
            }
            return true;
        };
		*/
        //x.find('a').not('.infobox *, .navbox *').each(findreds);
	}
	
	
	
	var findmostredlink = mw.util.addPortletLink('p-tb', '#', 'Find most RED', 'ca-findmostred');
    $(findmostredlink).click( function(e) {
        e.preventDefault();
    	
    	getPage3("Bobita", findmostred);
	});
	
    /*
    var portletlink = mw.util.addPortletLink('p-tb', '#', 'Highlight red', 'ca-findredlinks');
    $(portletlink).click( function(e) {
        e.preventDefault();
        				
        mw.util.addCSS(".duplicate-link { border: 3px solid red; }");
        
        // detect duplicate links
        var findreds = function() {
            var href = $(this).attr('href');
            if(href !== undefined && href.indexOf('#') != 0) {
            	if (href.indexOf('redlink') != -1) {
            		$(this).addClass("duplicate-link");
            	}
            }
            return true;
        };

        var content = ".mw-content-ltr";

        mw.util.$content.find('a').not('.infobox *, .navbox *').each(findreds);
    });
    */
});