Jump to content

User:WikiMacaroons/utvt.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.
/*
REMEMBER: When putting on enwiki, make it so:
-all test.wiki, etc is changed to en.wiki
-it checks if you have rollback right
-Change prefpage to "User:"+orun+"/UTVT Preferences.js";
*/
orun = mw.user.getName( );
//orun = orun.replace(/ /g, '_');
var slotstr = "";
prefpage = "User:"+orun+"/UTVT Preferences.js";
new mw.Api().get( {
     action: "query",
     titles: [ prefpage ],
 } ).then( function( ret ) {
     $.each( ret.query.pages, function() {
         if ( this.missing !== "" ) {
         } else {
            doSettings(prefpage);
        }
    } );
}, function( error ) {
	
} );
var rightslist = [];
var params = {
		action: 'query',
		meta: 'userinfo',
		uiprop: 'rights',
		format: 'json'
	},
	api = new mw.Api();

api.get( params ).done( function ( data ) {
	window.rb = 0;
	for(var elem in data.query.userinfo.rights){
		console.log(data.query.userinfo.rights[elem]);
		rightslist.push(data.query.userinfo.rights[elem]);
	}
	if(rightslist.includes("sysop")){
		window.issysop = 1;
	}
	else if(rightslist.includes("")){
		window.rb = 1;
	}
	else{
		window.issysop = 0;
	}
	/*
	if(rb == "no"){
		alert("Sorry, this script relies on you having rollback rights.");
	}
	*/
} );
/*function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}
console.log(JSON.parse(httpGet("https://ores.wikimedia.org/v3/scores/enwiki/977407410/damaging")));
*/

if(window.location.href == "https://en.wikipedia.org/wiki/User:WikiMacaroons/Untitled_Vandalism_Tracker/Tracker"){
	window.evenorodd = 1;
	document.querySelector('html').innerHTML = `
	<title>Untitled Vandalism Tracker</title>
	<script src="https://unpkg.com/keyboard@0.0.1/Keyboard.js"></script>
	<body> 
	<script src="../eventsource-polyfill.js"></script>
	<style>
	html *
	{
		font-family: Arial !important;
	}
	.div1 {
	  width: 780px;
	  height: 100px;
	  border: 2px solid gold;
	  background-color: gold;
	}
	.div2 {
	  width: 784px;
	  height: 100px;
	  border: 2px #ffdd80;
	  background-color: #ffdd80;
	}
	.div3 {
	  width: 350px;
	  height: 100px;
	  border: 2px #F0F0F0;
	  background-color: #FFFFFF;
	}
	.button {
	  border: none;
	  color: white;
	  text-align: center;
	  text-decoration: none;
	  display: inline;
	  font-size: 16px;
	  transition-duration: 0.4s;
	  cursor: pointer;
	}
	.revb {
	  border: none;
	  color: white;
	  text-align: center;
	  text-decoration: none;
	  display: inline;
	  font-size: 16px;
	  transition-duration: 0.4s;
	  cursor: pointer;
	  width: 100px;
	  height: 40px;
	}
	.adactions {
	  border: none;
	  color: white;
	  text-align: center;
	  text-decoration: none;
	  display: inline;
	  font-size: 16px;
	  transition-duration: 0.4s;
	  cursor: pointer;
	  width: 300px;
	  height: 40px;
	}
	.button3 {
	  background-color: #ebf0f5; 
	  color: black; 
	  border: 2px solid #ebf0f5;
	}
	
	.button3:hover {
	  background-color: #fa6e4b;
	  color: white;
	  border: 2px solid #fa6e4b;
	}
	.buttonvandalism {
	  background-color: #ffcbc7; 
	  color: black; 
	  border: 2px solid #ffcbc7;	
	}
	.buttonvandalism:hover {
	  background-color: #d40f00; 
	  color: black; 
	  border: 2px solid #d40f00;	
	}
	.buttontest {
	  background-color: #fccc9f; 
	  color: black; 
	  border: 2px solid #fccc9f;	
	}
	.buttontest:hover {
	  background-color: #d16806; 
	  color: black; 
	  border: 2px solid #d16806;	
	}
	.buttonunsource {
	  background-color: #ffe37d; 
	  color: black; 
	  border: 2px solid #ffe37d;	
	}
	.buttonunsource:hover {
	  background-color: #e3b200;
	  color: black; 
	  border: 2px solid #e3b200;	
	}
	.buttonpromo {
	  background-color: #d5ff8c; 
	  color: black; 
	  border: 2px solid #d5ff8c;	
	}
	.buttonpromo:hover {
	  background-color: #77a823; 
	  color: black; 
	  border: 2px solid #77a823;	
	}
	.buttonremove {
	  background-color: #d2f1fa;
	  color: black; 
	  border: 2px solid #d2f1fa;	
	}
	.buttonremove:hover {
	  background-color: #4da5bd;
	  color: black; 
	  border: 2px solid #4da5bd;
	}
	.buttonblp {
	  background-color: #e7baf5;
	  color: black; 
	  border: 2px solid #e7baf5;
	}
	.buttonblp:hover {
	  background-color: #a054b8;
	  color: black; 
	  border: 2px solid #a054b8;
	}
	.buttonnpov {
	  background-color: #fcacc9;
	  color: black; 
	  border: 2px solid #fcacc9;
	}
	.buttonnpov:hover {
	  background-color: #eb3172;
	  color: black; 
	  border: 2px solid #eb3172;
	}
	p.revidcss {
		color: grey;
		text-indent: 20px;
		font-size: 13px;
	}
	p.pagetitlecss {
		text-indent: 20px;
	}
	.right {
	    float: right;
	    margin-right: 5%;
	}
	p.add{
		color: green;
		font-size: 13px;
	}
	p.subtract{
		color: red;
		font-size: 13px;
	}
	p.reverthead{
		float: right;
	    margin-right: 5%;
	}
	p.warnhead{
		float: right;
	    margin-right: 5%;
	}
	.diff td div {
    	word-wrap: break-word;
	}
	.diff-editfont-monospace .diff-addedline, .diff-editfont-monospace .diff-deletedline, .diff-editfont-monospace .diff-context {
	    font-family: monospace,monospace;
	}
	.diff-contentalign-left td {
	    direction: ltr;
	    unicode-bidi: embed;
	}
	.diff-addedline, .diff-deletedline, .diff-context {
	    font-size: 13px;
	    line-height: 1.6;
	    vertical-align: top;
	    white-space: pre-wrap;
	    border-style: solid;
	    border-width: 1px 1px 1px 4px;
	    border-radius: 0.33em;
	}
	.diff-currentversion-title, .diff {
	    direction: ltr;
	    unicode-bidi: embed;
	}
	.diff {
	    border: 0;
	    border-spacing: 4px;
	    margin: 0;
	    width: 100%;
	    table-layout: fixed;
	}
	
	.inner {
	  margin-right: 900px
	}
	.table tbody tr.table-indent{
    padding-left: 900px;
	}
	/* The Modal (background) */
	.modal {
	  display: none; /* Hidden by default */
	  position: fixed; /* Stay in place */
	  z-index: 1; /* Sit on top */
	  left: 0;
	  top: 0;
	  width: 100%; /* Full width */
	  height: 100%; /* Full height */
	  overflow: auto; /* Enable scroll if needed */
	  background-color: rgb(0,0,0); /* Fallback color */
	  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
	}
	
	/* Modal Content/Box */
	.modal-content {
	  background-color: #fefefe;
	  margin: 15% auto; /* 15% from the top and centered */
	  padding: 20px;
	  border: 1px solid #888;
	  width: 80%; /* Could be more or less, depending on screen size */
	}
	
	/* The Close Button */
	.blockClose {
	  color: #aaa;
	  float: right;
	  font-size: 28px;
	  font-weight: bold;
	}
	
	.blockClose:hover,
	.blockClose:focus {
	  color: black;
	  text-decoration: none;
	  cursor: pointer;
	}
	.protectClose {
	  color: #aaa;
	  float: right;
	  font-size: 28px;
	  font-weight: bold;
	}
	
	.protectClose:hover,
	.protectClose:focus {
	  color: black;
	  text-decoration: none;
	  cursor: pointer;
	}
	.setClose {
	  color: #aaa;
	  float: right;
	  font-size: 28px;
	  font-weight: bold;
	}
	
	.setClose:hover,
	.setClose:focus {
	  color: black;
	  text-decoration: none;
	  cursor: pointer;
	}
	.slidecontainer {
	  width: 100%; /* Width of the outside container */
	}
	
	/* The slider itself */
	.slider {
	  -webkit-appearance: none;  /* Override default CSS styles */
	  appearance: none;
	  width: 100%; /* Full-width */
	  height: 25px; /* Specified height */
	  background: #d3d3d3; /* Grey background */
	  outline: none; /* Remove outline */
	  opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
	  -webkit-transition: .2s; /* 0.2 seconds transition on hover */
	  transition: opacity .2s;
	}
	
	/* Mouse-over effects */
	.slider:hover {
	  opacity: 1; /* Fully shown on mouse-over */
	}
	
	/* The slider handle (use -webkit- (Chrome, Opera, Safari, Edge) and -moz- (Firefox) to override default look) */
	.slider::-webkit-slider-thumb {
	  -webkit-appearance: none; /* Override default look */
	  appearance: none;
	  width: 25px; /* Set a specific slider handle width */
	  height: 25px; /* Slider handle height */
	  background: #4CAF50; /* Green background */
	  cursor: pointer; /* Cursor on hover */
	}
	
	.slider::-moz-range-thumb {
	  width: 25px; /* Set a specific slider handle width */
	  height: 25px; /* Slider handle height */
	  background: #4CAF50; /* Green background */
	  cursor: pointer; /* Cursor on hover */
	}
	</style>
	<script src="//cdnjs.cloudflare.com/ajax/libs/mousetrap/1.4.6/mousetrap.min.js"></script>
	<div id="blockModal" class="modal">

	  <!-- Modal content -->
	  <div class="modal-content">
	    <span class="blockClose">&times;</span>
	    <h1 id="blockHeader">Blocking User: </h1>
	    <p id="blockSub">[ADMIN STATUS]</p>
	    <div id="nonAdBlock">
	    <label for="blockPrimary">Primary Linked Page:</label>
		<input type="text" id="blockPrimary" name="blockPrimary"><br><br>
		<label for="blockComment">Comment:</label><br><br>
		<textarea id="blockComment" name="blockComment" rows="4" cols="50">
		</textarea><br><br>
		<button class="revb buttonremove" id="blockSubmit" onclick="submitBlock((document.getElementById('blockPrimary').value), (document.getElementById('blockComment').value))">Submit</button>
		</div>
	  </div>
	
	</div>
	<div id="protectModal" class="modal">

	  <!-- Modal content -->
	  <div class="modal-content">
	  <span class="protectClose">&times;</span>
	  <h1 id="protHeader">Protecting Page: </h1>
	  <p id="protSub">[ADMIN STATUS]</p>
	<label for="protDur">Duration:</label>
	<select id="protDur" name="protDur">
	  <option value="Temporary">Temporary</option>
	  <option value="Indefinite">Indefinite</option>
	</select>
	<label for="protType">Type:</label>
	<select id="protType" name="protType">
	  <option value="Semi-Protection">Semi-Protection</option>
	  <option value="Extended Confirmed Protection">Extended Confirmed Protection</option>
	  <option value="Pending Changes Protection">Pending Changes Protection</option>
	  <option value="Move Protection">Move Protection</option>
	  <option value="Full Protection">Full Protection</option>
	</select><br>
	<label for="protComment">Reason:</label><br><br>
		<textarea id="protComment" name="protComment" rows="4" cols="50">Persistent [[WP:VAND|vandalism]].</textarea><br><br>
	<button class="revb buttonunsource" id="protSubmit" onclick="submitProt(document.getElementById('protDur').value, document.getElementById('protType').value, document.getElementById('protComment').value)">Submit</button>
	</div>
	</div>
	<div id="setModal" class="modal">

	  <!-- Modal content -->
	  <div class="modal-content">
	    <span class="setClose">&times;</span>
	    <h1 id="setHeader">Settings</h1>
	    <p>Probability of Vandalism</p> <a href="https://en.wikipedia.org/wiki/User:WikiMacaroons/Untitled_Vandalism_Tracker/Guide#Probability_of_Vandalism">(?)</a>
	    <div class="slidecontainer">
			<input type="range" min="1" max="100" value="0" class="slider" id="myRange">
		</div>
		<p>Probability:</p> <p id="vandalprob"></p><br>
		<p>Namespaces:</p>
		<div id="namespaces">
		</div>
		<br>
		<button class="revb buttonnpov" id="setSubmit" onclick="submitSettings()">Submit</button>
	  </div>
	
	</div>

	<div id='diff' style='float:right' class='div3'></div>
	<p id='feed' style='font-size: 15px;'></p>
	<p id="prefs" style="color: white;"></p>

	</body>
	`;
	parseSlots(prefpage);
	setTimeout(() => {  var myobj = document.getElementById("prefs"); window.prefstr = myobj.textContent; myobj.remove(); }, 2000);
	//var EventSource = require('eventsource');
	var url = 'https://stream.wikimedia.org/v2/stream/recentchange';
	
	console.log(`Connecting to EventStreams at ${url}`);
	var eventSource = new EventSource(url);
	
	eventSource.onopen = function(event) {
	    console.log('--- Opened connection.');
	};
	
	eventSource.onerror = function(event) {
	    console.error('--- Encountered error', event);
	};
	
	eventSource.onmessage = function(event) {
	    // event.data will be a JSON string containing the message event.
	    //console.log(JSON.parse(event.data));
	    var change = JSON.parse(event.data);
	    window.windowchange = JSON.parse(event.data);
	    /*changewiki = window.windowchange.wiki;
	    changeid = window.windowchange.revision;
	    changeid = changeid.new;
	    console.log(changewiki);
	    console.log(changeid);*/
	    try{
	    	usenewrev = JSON.parse(event.data).id;
	    	usewiki = JSON.parse(event.data).wiki;
	    } catch{
	    	usewiki = "TEST";
	    }
	    //alert(usenewrev);
	    if(usewiki == "enwiki"){
	    	if(checkOres(usenewrev, "70")== true){
			    	console.log(JSON.parse(event.data));
			    	window.revnew = JSON.parse(event.data).revision.new;
			    	window.revold = JSON.parse(event.data).revision.old;
			    	window.paget = JSON.parse(event.data).title;
			    	window.user = JSON.parse(event.data).user;
			    	window.comment = JSON.parse(event.data).parsedcomment;
			    	window.schange = JSON.parse(event.data)["length"].new - JSON.parse(event.data)["length"].old;
			    	compare(revold, revnew, paget, user, comment, schange);
		    	/*catch(err){
		    		if(err.toString().indexOf("read property 'new' of undefined") != -1){
		    			console.log("new page");
		    		}
		    	}*/
	    }
	}
	
	};
	
}
function compare(oldr, newr, title, uname, summary, sizechange){
	var today = new Date();
	var time = "";
	if(today.getMinutes().toString().length == 1){
		time = today.getHours() + ":0" + today.getMinutes();
	}
	else{
		time = today.getHours() + ":" + today.getMinutes();
	}
	time += "‌ ‌ ‌ ‌ ‌";
	var params = {
	    action: "compare",
	    format: "json",
	    fromrev: oldr,
	    torev: newr
	},
	api = new mw.Api();
	
	api.get( params ).done( function ( data ) {
		if(schange.toString().indexOf("-") != -1){
		    schange = "<p class='subtract' style='margin:0;display:inline:float:right' id='viewc'><b>   ("+schange+")</b></p>";
		}
    	else{
    		if(schange.toString() == "0"){
    			schange = "<p class='revidcss' style='margin:0;display:inline:float:right' id='viewc'><b>   (+"+schange+")</b></p>";
    		}
    		else{
    			schange = "<p class='add' style='margin:0;display:inline:float:right' id='viewc'><b>   (+"+schange+")</b></p>";
    		}
		}
		docrev = `
		<div class='div`+evenorodd+`'><p class='revidcss' style="margin:0;display:inline;float:left">Revision Id: `+newr+` `+time+`</p> `+schange+`<button class="right button button3" onclick='viewDiff(`+oldr+`, `+newr+`, "`+uname+`", "`+title+`")'>View change</button>
		<p class='pagetitlecss'>`+title+`</p>
		<p class='pagetitlecss'>Change made by User:<b>`+uname+`.</b> Summary: <b>"`+summary+`"</b>.</p>
		</div>
		`;
		if(evenorodd == 1){
			evenorodd = 2;
		}
		else{
			evenorodd = 1;
		}
		//document.getElementById("feed").innerHTML = data.compare["*"]+document.getElementById("feed").innerHTML;
		document.getElementById("feed").innerHTML = docrev+document.getElementById("feed").innerHTML;
		console.log(data);
		//document.getElementById("diff").innerHTML = (data.compare["*"]);
	} );
}
function viewDiff(oldrev, newrev, author, pagename){
	window.currpn = pagename;
	var diffparams = {
	    action: "compare",
	    format: "json",
	    fromrev: oldrev,
	    torev: newrev
	},
	diffapi = new mw.Api();
	diffapi.get( diffparams ).done( function ( diffdata ) {
		document.getElementById("diff").innerHTML = `<p class='reverthead' style='padding-right: 440px; line-height: 30px'>Revert<br>
		<button class='right revb buttonvandalism' onclick='revertChange("`+author+`", "Reverted edits by [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:VANDALISM|Vandalism]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "`+pagename+`")'>Vandalism</button><br>
		<button class='right revb buttontest' onclick='revertChange("`+author+`", "Reverted edits by [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for Test Edits. ([[User:WikiMacaroons/UTVT|UTVT]])", "`+pagename+`")'>Tests</button><br>
		<button class='right revb buttonunsource' onclick='revertChange("`+author+`", "Reverted edits by [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:Verifiability|Unsourced content]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "`+pagename+`")'>Unsourced</button><br>
		<button class='right revb buttonpromo' onclick='revertChange("`+author+`", "Reverted edits by [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:PROMO|Promotional Content]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "`+pagename+`")'>Promotion</button><br>
		<button class='right revb buttonremove' onclick='revertChange("`+author+`", "Reverted edits by [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for Unexplained content removal. ([[User:WikiMacaroons/UTVT|UTVT]])", "`+pagename+`")'>Content Removal</button><br>
		<button class='right revb buttonblp' onclick='revertChange("`+author+`", "Reverted edits by [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:BLP|BLP Violation]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "`+pagename+`")'>BLP Violation</button><br>
		<button class='right revb buttonnpov' onclick='revertChange("`+author+`", "Reverted edits by [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:NPOV|Neutral POV issue]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "`+pagename+`")'>NPOV Issue</button><br>
		</p>
		<p class='warnhead' style='position: absolute; top: 30px; right: -30px;'>Warn<br>
		<button class='right revb buttonvandalism' onclick='warnUser("`+author+`", "Warned [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:VANDALISM|Vandalism]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "uw-vandalism", "`+pagename+`")'>Vandalism</button><br>
		<button class='right revb buttontest' onclick='warnUser("`+author+`", "Warned [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for Test Edits. ([[User:WikiMacaroons/UTVT|UTVT]])", "uw-test", "`+pagename+`")'>Tests</button><br>
		<button class='right revb buttonunsource' onclick='warnUser("`+author+`", "Warned [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:Verifiability|Unsourced content]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "uw-unsourced", "`+pagename+`")'>Unsourced</button><br>
		<button class='right revb buttonpromo' onclick='warnUser("`+author+`", "Warned [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:PROMO|Promotional Content]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "uw-advert", "`+pagename+`")'>Promotion</button><br>
		<button class='right revb buttonremove' onclick='warnUser("`+author+`", "Warned [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for Unexplained content removal. ([[User:WikiMacaroons/UTVT|UTVT]])", "uw-delete", "`+pagename+`")'>Content Removal</button><br>
		<button class='right revb buttonblp' onclick='warnUser("`+author+`", "Warned [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:BLP|BLP Violation]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "uw-biog", "`+pagename+`")'>BLP Violation</button><br>
		<button class='right revb buttonnpov' onclick='warnUser("`+author+`", "Warned [[Special:Contributions/`+author+`|`+author+`]] ([[User talk:`+author+`|talk]]) for [[WP:NPOV|Neutral POV issue]]. ([[User:WikiMacaroons/UTVT|UTVT]])", "uw-npov", "`+pagename+`")'>NPOV Issue</button><br>
		</p>
		<div style='overflow: scroll; width: 320px; height: 300px; position: absolute; left: 900px; top: 30px;'><table class='table tbody tr.table-indent'>`+diffdata.compare["*"]+`</table></div>
		<div style='position: absolute; right: 150px; top: 350px;'><button class='adactions buttonremove' onclick='blockUser("`+author+`", "`+issysop+`", "`+pagename+`")'>Block/Request Block of User</button></div>
		<div style='position: absolute; right: 150px; top: 390px;'><button class='adactions buttonunsource' onclick='protectPage("`+pagename+`", "`+issysop+`")'>Protect/Request protection of Page</button></div>
		<div style='position: absolute; right: 150px; top: 430px;'><button class='adactions buttonnpov' onclick='settings();'>Settings</button></div>
		
		`;
	});
}

function warnUser(authname, reason, template, currentpn){
	document.querySelector('html').style.cursor = "progress";
	var months =  ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	var dnums = new Date();
	var monthname = months[dnums.getMonth()];
	var year = dnums.getFullYear();
	var wheading = monthname+" "+year;
	var pageexists = 0;
	var warnparams = {
			action: 'query',
			prop: 'revisions',
			titles: 'User talk:'+authname,
			rvslots: '*',
			rvprop: 'content',
			formatversion: '2',
			format: 'json',
		},
		warnapi = new mw.Api();
	
		warnapi.postWithToken( 'csrf', warnparams ).done( function ( data ) {
			window.fullpagetext = data.query.pages[0].revisions[0].slots.main.content;
			if(data.query.pages[0].missing == true){
				console.log("Page does not exist");
				sendNewWarn(template, authname, reason, wheading, "1", data.query.pages[0].revisions[0].slots.main.content);
			}
			else if(data.query.pages[0].missing == undefined){
				console.log("Page does exist");
				findLastWarn(authname, data.query.pages[0].revisions[0].slots.main.content, wheading, template, reason, currentpn);
			}
	} );
}

function sendNewWarn(tname, authorn, summ, datehead, num, pagetext){
	var months2 =  ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	var dnums2 = new Date();
	var monthname2 = months2[dnums2.getMonth()];
	var year2 = dnums2.getFullYear();
	var wheading2 = monthname2+" "+year2;
	curlyb = "{";
	curlybt = "}";
	sigha = "~~";
	if(datehead == ""){//BROOD OVER IT, BUT PUT THE SOLUTION HERE
		ttoap = `

`+curlyb+curlyb+"subst:"+tname+num+curlybt+curlybt+sigha+sigha;
	const regexp = /==.*?==/g;
	const insts = [...fullpagetext.matchAll(regexp)];
	sect = insts.indexOf("== "+wheading2+" ==");
	for(var thisitem in insts){
		if(insts[thisitem] == "== "+wheading2+" =="){
			sect = thisitem;
			break;
		}
	}
	sect = (parseInt(sect))+1;
	var params = {
			action: 'edit',
			title: 'User talk:'+authorn,
			appendtext: ttoap,
			format: 'json',
			summary: summ,
			section: sect
		},
		api = new mw.Api();
		api.postWithToken( 'csrf', params ).done( function ( data ) {
				console.log( data );
		} );
	}
	else{
		ttoap =  `
== `+datehead+` ==
`+curlyb+curlyb+"subst:"+tname+num+curlybt+curlybt+sigha+sigha;
		var newparams = {
			action: 'edit',
			title: 'User talk:'+authorn,
			appendtext: ttoap,
			format: 'json',
			summary: summ,
		},
		newapi = new mw.Api();
		newapi.postWithToken( 'csrf', newparams ).done( function ( newdata ) {
				console.log( newdata );
		} );
	}
		setTimeout(() => {  document.querySelector('html').style.cursor = "auto"; }, 1500);
}

function findLastWarn(username, wikitext, sectionhead, wtplate, esumm, currentpagename){
	if(wikitext.lastIndexOf("== "+sectionhead+" ==") == -1){
		sendNewWarn(wtplate, username, esumm, sectionhead, "1", wikitext);
	}
	else{
		wikitext = wikitext.substring(wikitext.lastIndexOf("== "+sectionhead+" =="), wikitext.length);
		wikitext = wikitext.replace("== "+sectionhead+" ==", "");
		const titleregex = /==.*?==/;
		if(wikitext.search(titleregex) == -1){
			wikitext = wikitext.substring(0, wikitext.length);
		}
		else{
			wikitext = wikitext.substring(0, wikitext.search(titleregex));
		}
		if(wikitext.includes("[[File:Stop hand nuvola.svg")){
			document.querySelector('html').style.cursor = "auto";
			reportit = confirm("This user has reached Level 4 warning. Would you like to report them to AIV?");
			if(reportit){
				blockUser(username, issysop, currentpagename);
			}
		}
		else if(wikitext.includes("[[File:Nuvola apps important.svg") && !wikitext.includes("[[File:Stop hand nuvola.svg")){
			sendNewWarn(wtplate, username, esumm, "", "4", wikitext);
		}
		else if(wikitext.includes("[[File:Information orange.svg") && !wikitext.includes("[[File:Nuvola apps important.svg")){
			sendNewWarn(wtplate, username, esumm, "", "3", wikitext);
		}
		else if(wikitext.includes("[[File:Information.svg") && !wikitext.includes("[[File:Information orange.svg")){
			sendNewWarn(wtplate, username, esumm, "", "2", wikitext);
		}
	}
}

function revertChange(chuser, editsummary, pagetitle){
	var revertparams = {
			action: 'rollback',
			title: pagetitle,
			user: chuser,
			summary: editsummary,
			format: 'json'
		},
		revertapi = new mw.Api();
	
	revertapi.postWithToken( 'rollback', revertparams ).done( function ( revertdata ) {
		console.log( revertdata );
	} );
}

function blockUser(usertoblock, isadmin, primarypage){
	var aivparams = {
			action: 'query',
			prop: 'revisions',
			titles: 'Wikipedia:Administrator intervention against vandalism',
			rvslots: '*',
			rvprop: 'content',
			formatversion: '2',
			format: 'json',
		},
		aivapi = new mw.Api();
	
		aivapi.postWithToken( 'csrf', aivparams ).done( function ( aivdata ) {
			var aivtext = aivdata.query.pages[0].revisions[0].slots.main.content;
	if(aivtext.includes("Vandal|"+usertoblock+"}}") || aivtext.includes("vandal|"+usertoblock+"}}")){
		alert("This user appears to have already been reported.")
	}
	else{
		window.currentblockuser = usertoblock
		document.querySelector('html').style.cursor = "auto";
		window.modal = document.getElementById("blockModal");
		var span = document.getElementsByClassName("blockClose")[0];
		document.getElementById("blockHeader").textContent = "Blocking User: "+usertoblock;
		if(isadmin == "0"){
			document.getElementById("blockSub").textContent = "You are not an admin. This GUI will allow you to submit a block request.";
			document.getElementById("blockPrimary").value = primarypage;
			document.getElementById("blockComment").value = "Vandalism past level 4 warning.";
			modal.style.display = "block";
			// When the user clicks on <span> (x), close the modal
			span.onclick = function() {
			  modal.style.display = "none";
			}
			
			// When the user clicks anywhere outside of the modal, close it
			window.onclick = function(event) {
			  if (event.target == modal) {
			    modal.style.display = "none";
			  }
			}
		}
		else if(isadmin == "1"){
			document.getElementById("blockSub").textContent = "You are an admin. This GUI will allow you to block this user. (Except it won't, because I haven't finished it yet.)"
			notshowblock = document.getElementById("nonAdBlock")
			notshowblock.style.display = "none";
			modal.style.display = "block";
			// When the user clicks on <span> (x), close the modal
			span.onclick = function() {
			  modal.style.display = "none";
			}
			
			// When the user clicks anywhere outside of the modal, close it
			window.onclick = function(event) {
			  if (event.target == modal) {
			    modal.style.display = "none";
			  }
			}
		}
	}
	} );
}

function submitBlock(primarypage, blockmess){
	document.querySelector('html').style.cursor = "progress";
	if(primarypage.replace(/ /g, "") == ""){
		reporttext = `
* {`+`{vandal|`+currentblockuser+`}`+`} &ndash; `+blockmess+` ~~`+`~~`;
	}
	else {
		reporttext = `
* {`+`{vandal|`+currentblockuser+`}`+`} &ndash; On [[`+primarypage+`]]: `+blockmess+` ~~`+`~~`;
	}
	var reportparams = {
		action: 'edit',
		title: 'Wikipedia:Administrator intervention against vandalism',
		appendtext: reporttext,
		format: 'json',
		summary: "Reporting User [[Special:Contributions/"+currentblockuser+"|"+currentblockuser+"]] ([[User talk:"+currentblockuser+"|talk]]) to AIV. ([[User:WikiMacaroons/UTVT|UTVT]])",
		section: 1
	},
	reportapi = new mw.Api();
	reportapi.postWithToken( 'csrf', reportparams ).done( function ( reportdata ) {
		console.log( reportdata.toString() );
	} );
	modal.style.display = "none";
	setTimeout(() => {  document.querySelector('html').style.cursor = "auto"; }, 1500);
}

function protectPage(article, adminstat){
	window.currentprotpage = article;
	window.protmodal = document.getElementById("protectModal");
	var protspan = document.getElementsByClassName("protectClose")[0];
	document.getElementById("protHeader").textContent = "Protecting Page: "+article;
	protmodal.style.display = "block";
	protspan.onclick = function() {
		  protmodal.style.display = "none";
		}
		
		// When the user clicks anywhere outside of the modal, close it
		window.onclick = function(event) {
		  if (event.target == protmodal) {
		    protmodal.style.display = "none";
		  }
	}
	if(adminstat == "0"){
		document.getElementById("protSub").textContent = "You are not an admin. This GUI will allow you to submit a protection request."
	}
	
}

function submitProt(duration, protection, protcomment){
	document.querySelector('html').style.cursor = "progress";
	cbrack = "{"
	ocbrack = "}"
	if(duration == "Indefinite"){
		duration = "";
	}
	else{
		duration = "Temporary ";
	}
	protsubmit = `

=== [[:`+currentprotpage+`]] ===
* `+cbrack+cbrack+`pagelinks|1=`+currentprotpage+ocbrack+ocbrack+`

'''`+duration+protection+`:''' `+protcomment+` ~~`+`~~`;
	var protparams = {
		action: 'edit',
		title: 'Wikipedia:Requests for page protection',
		appendtext: protsubmit,
		format: 'json',
		summary: "Requesting "+duration+protection+" of [["+currentprotpage+"]]. ([[User:WikiMacaroons/UTVT|UTVT]])",
		section: 1
	},
	protapi = new mw.Api();
	protapi.postWithToken( 'csrf', protparams ).done( function ( protdata ) {
		console.log( protdata.toString() );
	} );
	modal.style.display = "none";
	setTimeout(() => {  document.querySelector('html').style.cursor = "auto"; }, 1500);
}

function settings(){
	userprefstr = window.prefstr;
	window.setmodal = document.getElementById("setModal");
	var setspan = document.getElementsByClassName("setClose")[0];
	setmodal.style.display = "block";
	setspan.onclick = function() {
		setmodal.style.display = "none";
	}
	var slider = document.getElementById("myRange");
	document.getElementById("myRange").value = getSlot(1, userprefstr);
	document.getElementById("vandalprob").textContent = slider.value.toString()+"%"; // Display the default slider value
	
	// Update the current slider value (each time you drag the slider handle)
	slider.oninput = function() {
	  //output.innerHTML = this.value;
	  document.getElementById("vandalprob").textContent = this.value.toString()+"%";
	}
		
	// When the user clicks anywhere outside of the modal, close it
	window.onclick = function(event) {
	  if (event.target == setmodal) {
	    setmodal.style.display = "none";
		}
	}
	loopnum = 2;
	listchecked = [];
	while(loopnum < 10){
		currslot = getSlot(loopnum, userprefstr);
		if(currslot.toString() == "1"){
			listchecked.push(" checked")
		}
		else{
			listchecked.push("")
		}
		loopnum += 1;
	}
	document.getElementById("namespaces").innerHTML += `<input type="checkbox" id="namespace1" name="namespace1" value="NS1"`+listchecked[0]+`>
  <label for="namespace1">Main</label><br>
  <input type="checkbox" id="namespace2" name="namespace2" value="NS2"`+listchecked[1]+`>
  <label for="namespace2">Talk</label><br>
  <input type="checkbox" id="namespace3" name="namespace3" value="NS3"`+listchecked[2]+`>
  <label for="namespace3">User</label><br>
  <input type="checkbox" id="namespace4" name="namespace4" value="NS4"`+listchecked[3]+`>
  <label for="namespace4">User talk</label><br>
  <input type="checkbox" id="namespace5" name="namespace5" value="NS5"`+listchecked[4]+`>
  <label for="namespace5">Wikipedia</label><br>
  <input type="checkbox" id="namespace6" name="namespace6" value="NS6"`+listchecked[5]+`>
  <label for="namespace6">File</label><br>
  <input type="checkbox" id="namespace7" name="namespace7" value="NS7"`+listchecked[6]+`>
  <label for="namespace7">Template</label><br>  
  <input type="checkbox" id="namespace8" name="namespace8" value="NS8"`+listchecked[7]+`>
  <label for="namespace8">Category</label><br>
	`;
}
/// FIX THE CATEGORY LINKS LATER MAYBE ///
function doSettings(settingsp){
	alert("Installing Untitled Vandalism Tracker...")
	settingsdata = `/* This is your UTVT Preferences Page. Please do not edit it Manually. */
[65][1][0][0][0][0][0][0][0]
/*`+`[  [Category:UTVT Preferences Pages]]*/`;
	var setparams = {
		action: 'edit',
		title: settingsp,
		appendtext: settingsdata,
		comment: "Installing Script. ([[User:WikiMacaroons/UTVT|UTVT]])",
		format: 'json'
	},
	setapi = new mw.Api();

	setapi.postWithToken( 'csrf', setparams ).done( function ( setdata ) {
		console.log( setdata );
	} );
	alert("Done!")
	location.reload();
}

function parseSlots(slotpage){
	var slotparams = {
			action: 'query',
			prop: 'revisions',
			titles: slotpage,
			rvslots: '*',
			rvprop: 'content',
			summary: 'Installing [[User:WikiMacaroons/UTVT/Beta 1.0|UTVT Beta 1.0]].',
			formatversion: '2',
			format: 'json',
		},
		slotapi = new mw.Api();
	
		slotapi.postWithToken( 'csrf', slotparams ).done( function ( slotdata ) {
			usevar = slotdata.query.pages[0].revisions[0].slots.main.content;
			document.getElementById("prefs").textContent = usevar;
		});
}

function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

function checkOres(oresid, userprefs){
	//alert(oresid);
	//oresid = JSON.parse(window.windowchange).revision.new;
	//alert("https://ores.wikimedia.org/v3/scores/enwiki/"+oresid.toString()+"/damaging")
	orespercentage = getSlot(1, userprefs);
	theUrl = "https://ores.wikimedia.org/v3/scores/enwiki/"+oresid.toString()+"/damaging"
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    responsetext = xmlHttp.responseText.toString().substring(1, (xmlHttp.responseText.toString().lastIndexOf("}")))
    responsetext = responsetext.substring(responsetext.indexOf("true"), responsetext.lastIndexOf("}"))
    responsetext = responsetext.replace("true\":", "")
    responsetext = responsetext.replace(/\}/g, "")
    responsetext = responsetext.replace(/ /g, "")
    responsetext = responsetext.replace(/\n/g, "")
    truescore = parseFloat(responsetext);
    if(truescore * 100 >= orespercentage){
    	return true;
    }
    else{
    	return false;
    }
}

function getSlot(slotnum, prefstring){
	prefstring = prefstring.replace(/\/\*.*?\*\//g, "");
	prefstring = prefstring.replace(/\[/g, "");
	prefstring = prefstring.replace(/\]/g, "|");
	preflist = prefstring.split("|");
	return (preflist[slotnum-1]).replace(/\s/g, "");
}

function submitSettings(){
	updatestring = "/* This is your UTVT Preferences Page. Please do not edit it Manually. */";
	usepercent = document.getElementById("myRange").value.toString()
	updatestring += `
[`+usepercent+`]`;
	namespacenum = 1;
	while(namespacenum < 9){
		if((document.getElementById("namespace"+(namespacenum.toString())).checked) == true){
			updatestring += "[1]";
		}
		else{
			updatestring += "[0]";
		}
		namespacenum += 1;
	}
	updatestring += `
/*[[`+`Category:UTVT Preferences Pages] ]*/`;
	alert("Saving settings...")
	var setparams2 = {
		action: 'edit',
		title: "User:"+(mw.user.getName( ))+"/UTVT Preferences.js",
		text: updatestring,
		comment: "Updating Preferences. ([[User:WikiMacaroons/UTVT|UTVT]])",
		format: 'json'
	},
	setapi2 = new mw.Api();

	setapi2.postWithToken( 'csrf', setparams2 ).done( function ( setdata2 ) {
		console.log( setdata2 );
	} );
	alert("Done!")
	location.reload();
	document.getElementById("setModal").style.display = "none";
	
}