User:Thundercraft5/common.js

/** User:Thundercraft5/common.js * Licensed Under CC-BY-SA-3.0. * * =====Contents===== * *Personal Adjustments *	*Upper icons adjustment *	*Top Menu *	* * * Major Scripts *	*blockListLookup *	*rangeBlockLinks *	*blockListTools

/* global mw, test, mediaWiki, ace */ /* jshint esversion: 6, forin: true, immed: true, indent: 4, latedef: false, newcap: true, noarg: true, undef: true, undef: true, unused: true, browser: true, jquery: true, onevar: true, eqeqeq: true, multistr: true, maxerr: 999999

//#==================================================# //# PERSONAL ADJUSTMENTS //#==================================================# window.dontWantRoleSpecificJS = true;

window.test = new Proxy({	test: "$", }, {	deleteProperty: function(o, k) {		throw new TypeError(o, k);	}, }); try { delete test.test; } catch (e) { console.warn(e); }

var inter = setInterval(function {   var userGroups = mw.config.get('wgUserGroups');    var canBlock = /sysop|util|staff|helper|global-discussions-moderator|wiki-manager|soap/.test(userGroups.join('\n'));    if ($('[class^="ReplyCreate_reply-create"]').length) {        clearInterval(inter);

function changeCommentLinks { // jshint ignore:line $('span[class^="EntityHeader_header-details"] > div[class^="wds-avatar EntityHeader_avatar"] > a').each(function {               var user = $(this).attr('href').replace(/\/wiki\/(User:|Special:Contributions\/)/gi, ''),                    $link = $(this).parent.parent.children('a:last-of-type:not(.mw-user-anon-link)'),                    $this = $(this);

$link .attr('href', '/wiki/Special:Contributions/' + user) .html(user);

$this.attr('href', '/wiki/Special:Contributions/' + user);

$link.after(                   ' (', $('', {                       href: "/wiki/Message_wall:" + user,                        html: "wall",                        title: "Message_wall:" + user,                        class: "mw-user-anon-link",                    }), canBlock ? ' &bull; ' : "", canBlock ? $('', {                       href: "/wiki/Special:Block/" + user,                        html: "block",                        title: "Special:Block/" + user,                        class: "mw-user-anon-link",                    }) : "", ')'               );            });        }

changeCommentLinks;

$('[class^="ReplyList_view-all-replies"]').click(function {           setTimeout(changeCommentLinks, 25);        }); } }, 25);

document.addEventListener('keydown', function(e) {   var key = e.key.toLowerCase;    if (key === "l" && e.ctrlKey) {        e.preventDefault;        document.querySelector('.oo-ui-iconElement-icon.oo-ui-icon-gotoLine').click;    } else if (key === "s" && e.ctrlKey) {        e.preventDefault;        document.querySelector('.oo-ui-iconElement-icon.oo-ui-icon-pilcrow').click;    } });

// Lua Syntax highlighting function [disabled] if (true) { return; }   var libs = { "package": true, "table": true, "string": true, "io": true, "file": true, "math": true, "utf8": true, "coroutine": true, "debug": true, "os": true, "util": true, "number": true, "mw": true, };    var keywords = { "time": true, "cos": true, "sin": true, "huge": true, "wrap": true, "len": true, "lower": true, "config": true, "open": true, "close": true, "input": true, "require": true, "format": true, "min": true, "max": true, "cosh": true, "sinh": true, "tan": true, "tanh": true, "gsub": true, "gmatch": true, "upper": true, "concat": true, "unpack": true, "tonumber": true, "type": true, "sub": true, "create": true, "date": true, "error": true, "output": true, "rep": true, "pairs": true, "ipairs": true, "pow": true, "maxn": true, "match": true, "remove": true, "sort": true, "log": true, "seeall": true, "byte": true, "char": true, "find": true, "reverse": true, "preload": true, "loaded": true, "init": true, "clock": true, "rad": true, "random": true, "pi": true, "mod": true, "modf": true, "log10": true, "ldexp": true, "exp": true, "expr": true, "dofile": true, "print": true, "running": true, "status": true, "yield": true, "cpath": true, "loadlib": true, "path": true, "searchers": true, "searchpath": true, "dump": true, "packsize": true, "codes": true, "offset": true, "charpattern": true, "mininteger": true, "ult": true, "randomseed": true, "flush": true, "lines": true, "popen": true, "read": true, "seek": true, "write": true, "setvbuf": true, "difftime": true, "execute": true, "exit": true, "getenv": true, "rename": true, "getinfo": true, "getlocal": true, "isyieldable": true, "fmod": true, "deg": true, "ceil": true, "floor": true, "abs": true, "acos": true, "asin": true, "atan": true, "atan2": true, "traceback": true, "stack": true, "pcall": true, "xpcall": true, "call": true, "select": true, "getmetatable": true, "next": true, "assert": true, "join": true, "name": true, "__index": true, "__newindex": true, "__call": true, "__mode": true, "__add": true, "__sub": true, "__mul": true, "__div": true, "__mod": true, "__pow": true, "__unm": true, "__concat": true, "__eq": true, "__lt": true, "__le": true, "__pairs": true, "__ipairs": true, "__metatable": true, "__tostring": true, "metatable": true, "rawset": true, "rawget": true, "set": true, "get": true, "new": true, "class": true, "load": true, "loaders": true, "object": true, "style": true, "title": true, "tag": true, };    function copySet(o) { var newArr = []; Object.keys(o).forEach(function(key) {            newArr.push(key);         }); return newArr; }    var libsArr = copySet(libs) , keywordsArr = copySet(keywords); $('.p').each(function {        var $this = $(this),             $text = $this.html;         if ($text.match(/([\(\)\{\}\[\]]+)/g)) {             $this.html($text.replace(/([\(\)\{\}\[\]]+)/, ' $1 '));         }     }); $('.n').each(function {        var $this = $(this),             $text = $this.html;         if ($text.match(new RegExp('^(' + keywordsArr.join('|') + ")$", 'gi'))) {             $this.removeClass('n').addClass('nf');         } else if ($text.match(new RegExp('^(' + libsArr.join('|') + ")$", 'gi'))) {             $this.removeClass('n').addClass('lb');         } else if (($this.next.html || "").match(/( ([\(\{]+[\}\)]*)<\/span>|^\")/)) {             $this.removeClass('n').addClass('f');         } else if ($this.next.html === ":") {             $this.addClass('nc').removeClass('n');         }     }); });
 * (function {

var pagePathname = mw.config.get('wgArticlePath').replace('$1', ''), sitename = mw.config.get('wgSiteName'), // jshint ignore:line userGroups = mw.config.get('wgUserGroups'), // jshint ignore:line namespace = mw.config.get("wgNamespaceNumber"), // jshint ignore:line pagename = mw.config.get('wgPageName'), // jshint ignore:line wikiUrl = mw.config.get('wgServer').replace(/https?:\/\//g, ''), // jshint ignore:line server = mw.config.get('wgServer'); // jshint ignore:line

var inter = setInterval(function {	if (namespace !== 828) {		clearInterval(inter);		return;	}	if ($('.ace_content').length && namespace === 828) {		clearInterval(inter);	} else {		return;	}	var histList = [''], 		histPos = 0, 		question, input, output, $spinner, 		sessionContent = null, 		sessionKey = null, 		pending = false, 		clearNextRequest = false,		debugConsole,		session;	function refocus { // jshint ignore:line		debugConsole.blur;		debugConsole.focus;	}	function initConsole { // jshint ignore:line		input = document.getElementById('mw-scribunto-input');		output = document.getElementById('mw-scribunto-output');		$spinner = $.createSpinner({ size: 'small', type: 'block', id: "consoleSpinner", });		println(mw.msg('scribunto-console-intro'), 'mw-scribunto-message');		debugConsole = ace.edit('debugConsole');		ace.console = {};		ace.console.editor = debugConsole;		session = debugConsole.session;		debugConsole.resize;		debugConsole.getSession.setMode('ace/mode/lua');		session.on('change', function { var size = debugConsole.session.getScreenLength * debugConsole.renderer.lineHeight + debugConsole.renderer.scrollBar.getWidth; $('#debugConsole').css('height', size); debugConsole.resize; });		debugConsole.setOptions({ enableSnippets: true, enableLiveAutocompletion: true, enableBasicAutocompletion: true, });		// Toggle enableLiveAutocompletion (Ctrl-S)		debugConsole.commands.addCommand({ name: 'toggleAutocomplete', bindKey: {win: 'Ctrl-S'}, exec: function(editor) { var on = editor.$enableLiveAutocompletion === true; editor.setOptions({					enableLiveAutocompletion: !editor.$enableLiveAutocompletion,				}); if (on) editor.completer.detach; }		});		// Clear Console (Ctrl-Alt-C)		debugConsole.commands.addCommand({ name: 'clearConsole', bindKey: {win: 'Ctrl-Alt-C'}, exec: function { clearOutput; }		});		// Clear Console State (Ctrl-Shift-C)		debugConsole.commands.addCommand({ name: 'clearConsoleState', bindKey: {win: 'Ctrl-Shift-C'}, exec: function { onClearClick; }		});		// Replace Spaces (Ctrl-Shift-S)		debugConsole.commands.addCommand({ name: 'replaceSpaces', bindKey: {win: 'Ctrl-Shift-S'}, exec: function(editor) { var pos = editor.getCursorPosition; editor.find('   '); editor.replaceAll('\t'); editor.moveCursorToPosition(pos); }		});

session.on('focus', inputFocus); // Submit (Ctrl-Enter) debugConsole.commands.addCommand({		   name: 'consoleSubmit',		    bindKey: {win: 'Ctrl-Enter'},		    exec: function {		        go;		    }		}); // Go To previous history entry (UpArrow) debugConsole.commands.addCommand({			name: 'navigateUp',			bindKey: { win: 'Up' },			exec: function(editor) {				if (caretInFirstLine) {					hist('up');				} else {					// If cursor is not in first posistion, dont suppress default behavior					editor.navigateUp;				}			},		}); // Go To next history entry (DownArrow) debugConsole.commands.addCommand({			name: 'navigateDown',			bindKey: { win: 'Down' },			exec: function(editor) {				if (caretInLastLine) {					hist('down');				} else {					// If cursor is not in last posistion, dont suppress default behavior					editor.navigateDown;				}			},		}); }	function inputFocus { // jshint ignore:line if (sessionContent === null) { return; }		if (clearNextRequest) { return; }		if (getContent !== sessionContent) { printClearBar('scribunto-console-cleared'); clearNextRequest = true; }	}	function caretInFirstLine { // jshint ignore:line return debugConsole.getCursorPosition.row === 0; }	function caretInLastLine { // jshint ignore:line return debugConsole.getCursorPosition.row+1 === debugConsole.session.getLength; }	function println(s, type) { // jshint ignore:line var newdiv; if ((s = String(s))) { newdiv = document.createElement('div'); newdiv.appendChild(document.createTextNode(s)); newdiv.className = type; output.appendChild(newdiv); return newdiv; }	}	function printClearBar(msg) { // jshint ignore:line $(' ').attr('class', 'mw-scribunto-clear').text(mw.msg(msg)).appendTo(output); }	function hist(direction) {// jshint ignore:line var L = histList.length; var session = debugConsole.session; if (L === 1) { return; }		if (direction === 'up') { if (histPos === L - 1) { histList[histPos] = session.getValue; }			if (histPos > 0) { histPos--; setTimeout(function {					session.setValue('');					session.setValue(histList[histPos]);				}, 0); }		} else { if (histPos < L - 1) { histPos++; session.setValue(histList[histPos]); } else if (histPos === L - 1) { if (session.getValue) { histList[histPos] = session.getValue; ++histPos; session.setValue(''); }			}		}	}	function printQuestion(q) { // jshint ignore:line println(q.match(/^=/) ? q.replace(/^=/, '') : q, 'mw-scribunto-input' + (q.match(/^=/) ? ' exp' : '')); }	function printError(er) { // jshint ignore:line var lineNumberString; if (er.name) { lineNumberString = (er.lineNumber !== undefined) ? (' on line ' + er.lineNumber + ': ') : ': '; println(er.name + lineNumberString + er.message, 'mw-scribunto-error'); } else { println(er, 'mw-scribunto-error'); }	}	function setPending { // jshint ignore:line pending = true; debugConsole.setOptions({		   readOnly: true,		}); $spinner.insertBefore($('#debugConsole').parent); }	function clearPending { // jshint ignore:line $spinner.remove; pending = false; debugConsole.setOptions({		   readOnly: false,		}); }	function go { // jshint ignore:line var params, api, content, sentContent; if (pending) { return; }		question = debugConsole.session.getValue; if (question === '') { return; }		histList[histList.length - 1] = question; histList[histList.length] = ''; histPos = histList.length - 1; debugConsole.session.setValue(''); setTimeout(function {			debugConsole.session.setValue('');		}, 0); printQuestion(question); params = { action: 'scribunto-console', title: mw.config.get('wgPageName'), question: question };		content = getContent; sentContent = false; if (!sessionKey || sessionContent !== content) { params.clear = true; params.content = content; sentContent = true; }		if (sessionKey) { params.session = sessionKey; }		if (clearNextRequest) { params.clear = true; clearNextRequest = false; }		api = new mw.Api; setPending; api.post(params).done(function(result) {			if (result.sessionIsNew ===  && !sentContent) {				printClearBar('scribunto-console-cleared-session-lost');				sessionContent = null;				clearPending;				debugConsole.setValue(params.question);				go;				return;			}			sessionKey = result.session;			sessionContent = content;			if (result.type === 'error') {				$(' ')					.addClass('mw-scribunto-error')					.html(result.html)					.appendTo(output);			} else {				if (result.print !== ) {					println(result.print, 'mw-scribunto-print');				}				if (result.return !== '') {					println(result.return, 'mw-scribunto-normalOutput');				}			}			clearPending;			setTimeout(refocus, 0);		}).fail(function(code, result) {			if (result.error && result.error.info) {				printError(result.error.info);			} else if (result.exception) {				printError('Error sending API request: ' + result.exception);			} else { mw.log(result); printError('Error sending API request: ' + code); }			clearPending; setTimeout(refocus, 0); });	}	function getContent { // jshint ignore:line		var $textarea = $('#wpTextbox1'),		   context = $textarea.data('wikiEditor-context');		if (context === undefined || context.codeEditor === undefined) {			return $textarea.val;		} else {			return $textarea.textSelection('getContents');		}	}	function onClearClick {// jshint ignore:line		$('#mw-scribunto-output').empty;		clearNextRequest = true;		refocus;	}	function clearOutput {// jshint ignore:line		$('#mw-scribunto-output').empty;		refocus;	}	function initEditPage { // jshint ignore:line		$('#mw-scribunto-console').first.remove;		var $wpTextbox1, 			$console = $('#mw-scribunto-console');		mw.messages.set('scribunto-console-clear-output', 'Clear Console Output');		mw.messages.set('scribunto-console-clear', 'Clear Console State');		mw.messages.set('scribunto-console-submit', 'Submit');		if (!$console.length) {			$wpTextbox1 = $('#wpTextbox1'); $console = $(' ').attr({				id: 'mw-scribunto-console'			}); console.log(!$('.editOptions').length); $('.editOptions').before($console); }		$(' ')			.attr('class', 'mw-scribunto-console-fieldset') .append($(' ')				.text(mw.msg('scribunto-console-title'))			) .append($(' ')) .append($(' ').append( $(' ', {					id: "debugConsole",					css: {				       'width': 'calc(-webkit-fill-available+100px)',				        'font-size': '14px',				        'line-height': '18px',				        'min-height': '100px',				        'max-height': '400px',					}				}) ))			.append($(' ').append( $(' ')					.attr({						type: 'button',						value: 'Clear Console Output'					}) .on('click', clearOutput), $(' ')					.attr({						type: 'button',						value: mw.msg('scribunto-console-clear')					}) .on('click', onClearClick), $(' ')					.attr({						type: 'button',						value: mw.msg('scribunto-console-submit')					}) .on('click', function(e) {						e.preventDefault;						go;					}) ))			.wrap(' ') .appendTo($console); initConsole; }	$(function {		var action = mw.config.get('wgAction');		if (action === 'edit' || action === 'submit' || action === 'editredlink') {			initEditPage;		}	}); });

/* Upper icons adjustment */ $('a[href="' + pagePathname + 'Special:CreatePage"]').remove; $('a[title="Wiki Activity"]').after(	$('', { class: "wds-button wds-is-secondary", href: "/wiki/Special:AbuseLog", title: "Abuse Log", html: " " }) ); $('a[href="' + pagePathname + 'Special:WikiActivity"]') .attr('href', pagePathname + 'Special:RecentChanges') .attr('title', 'Recent Changes'); $('a[href="' + pagePathname + 'Special:AdminDashboard"]') .first .after(		$('', { class: "wds-button wds-is-secondary", href: pagePathname + 'Special:AbuseFilter', title: "Abuse Filter Management", html: "    ", })		);

/* Top Menu */ var topListSelector = 'div.wds-community-header__wiki-buttons > div.wds-dropdown ul.wds-list.wds-is-linked'; $(topListSelector) .empty .attr('title', 'More Tools and Links') .append(		$('', { html: $('', {				href: pagePathname + "Special:BlockLookup",				html: "Block Lookup",				title: 'Special:BlockLookup',			}), }),		$('', { html: $('', {				href: pagePathname + "Special:BlockList",				html: "Blocked Users",				title: 'Special:BlockList',			}), }),		$('', { html: $('', {				href: pagePathname + "Special:AllMessages",				html: "All System Messages",				title: 'Special:AllMessages',			}), }),		$('', { html: $('<a>', {				href: pagePathname + "Special:AllPages",				html: "All pages",				title: 'Special:AllPages',			}) }),		$('<li>', { html: $('<a>', {				href: pagePathname + "Special:Watchlist",				html: "Watch list",				title: 'Special:Watchlist',			}) }),		$('<li>', { html: $('<a>', {				href: pagePathname + "Special:ListUsers",				html: "Users List",				title: 'Special:ListUsers',			}) }),		$('<li>', { html: $('<a>', {				href: pagePathname + "Special:ListGroupRights",				html: "User Group Rights",				title: 'Special:ListGroupRights',			}) })	);

/* rangeBlockLinks */ var pagename = mw.config.get("wgTitle"), namespace = mw.config.get("wgNamespaceNumber"), username = mw.config.get("wgTitle").split('/')[1], usergroups = mw.config.get('wgUserGroups');
 * (function($, mw, window) {

if (		namespace !== -1		|| !pagename.match(/(?:\d{1,3}\.){3}\d{1,3}/)		|| !/sysop|soap|staff|helper|global-discussions-moderator|wiki-manager/gmi.test(usergroups.join)		|| window.rangeBlockLinksInit	) { console.log('RangeBlockLinks: Import conditions not met, skipping import.'); return; }	window.rangeBlockLinksInit = true; function makeRangeBlockLink(range) { return([				"<a href=\"/wiki/Special:Block/",				username,				'/',				range,				"\" title=\"Block the /",				range,				" CIDR range this IP address originates from\"",				" id=\"rangelinks-range-block-CIDR-" + range + "\"",				">/",				range,				"</a>",			].join('')); }	$("#contentSub > a[href=\"/wiki/Special:Block/" + username + "\"]") .after(			" <small id=\"rangeblock-links\">(" + [					makeRangeBlockLink(24), makeRangeBlockLink(22), makeRangeBlockLink(20), makeRangeBlockLink(18), makeRangeBlockLink(16), ].join(' • ') + ") "		);

console.log('RangeBlockLinks: Successfully added range block links!'); })(jQuery, mediaWiki, window);

/* blockListTools */ function _main { var pagePathname = mw.config.get('wgArticlePath').replace('$1', ''), $ipToolsSel = $('td.TablePager_col_ipb_target span.mw-usertoollinks'), namespace = mw.config.get("wgNamespaceNumber"), pagename = mw.config.get("wgTitle");
 * (function {

function logMsg(data) { return console.log('BlockListTools:', typeof(data) === 'object' ? data.join(' ') : data); }

if (namespace !== -1 && pagename !== 'BlockList') { logMsg('Namespace/page is not supported, skipping importing script.'); return; }

window.blockListToolsInit = true;

/* IP tools */ $ipToolsSel.each(function {           /* Variables within iterator */            var $elem = $(this).children('a'),                href = $elem.prop('href'),                ip = href.match(/(\d{1,3}\.){3}\d{1,3}/g),                classes = $elem.prop('class'), // jshint ignore:line                user = href.split(':')[2]; // jshint ignore:line

if (ip) { $elem.first.after(                   " &bull; ",                    /* Proxy Check/General Info */                    $('<a>', { href: "//www.ipqualityscore.com/free-ip-lookup-proxy-vpn-test/lookup/" + ip, title: "Proxy check for " + ip, html: "PC", class: $elem.prop('class'), }),                   " &bull; ",                    /* Spam Blacklist check */                    $('<a>', { href: "//cleantalk.org/blacklists/" + ip, title: "Spam Blacklist check for " + ip, html: "BC", class: $elem.prop('class'), }),                   " &bull; ",                    $('<a>', { href: "https://cleantalk.org/whois/" + ip, title: "WHOIS for " + ip, html: "WHOIS", class: $elem.prop('class'), })               );            }        });        logMsg('Sucessfully appended IP tool links!');

/* Variables */ var blOpsArray = [], blActionsSel = 'span.mw-blocklist-actions', cbSel = 'a[title^="Special:Block/"]', // jshint ignore:line uSel = 'a[title^="Special:Unblock/"]'; // jshint ignore:line

/* Get Block List Unblock/Block Links and store them */ $(blActionsSel).each(function(i, elem) {           elem.remove;            blOpsArray.push(elem);        });

/* Append Stored elements */ $('td.TablePager_col_ipb_timestamp').each(function(i, elem) {           elem.append(blOpsArray[i]);        });

/* Adjustments */ $(blActionsSel).before(' '); /* Iterate over new elements */ $('span.mw-blocklist-actions > a').each(function(i) {           var $this = $(this),            	user;            /* Save User variable for future modifications */            user = $this.prop('title').match(/Special\:((?:Un)?block)\/(.+)/i);            user = user ? user[2] : null;            /* Format Titles */            $this.prop('title', $this.prop('title').replace(/Special\:((?:Un)?block)\/(.+)/i, function(match, $1, $2) {               if ($1.toLowerCase === 'block') {                    return 'Change block settings for ' + $2;               } else {                    return 'Unblock ' + $2;               }            }));

/* Shorten Link Text */ if ($this.html.toLowerCase === 'change block') { $this.html('CB'); } else { $this.html('U'); }

if (i % 2 === 1) { /* Extra Tool Links */ $this.after(' | ', $('<a>', { href: pagePathname + 'Special:AbuseLog?wpSearchUser=' + user, html: "AL", title: "Abuse logs for " + user }));           }        });        logMsg('Sucessfully Modified block list action links!');    }	window.ajaxCallAgain = window.ajaxCallAgain || [];	window.ajaxCallAgain.push(_main);	_main; })(jQuery, mediaWiki, window);