User:Utter solitude/FileUpdaterCode.js

// // // Options processing if (typeof (LIRoptions) !== "undefined"){ if (typeof (LIRoptions.bottomMessage) === "undefined"){ LIRoptions.bottomMessage = ""; }	if (typeof (LIRoptions.editSummary) === "undefined"){ LIRoptions.editSummary = "Updating file links (automatic)"; }	if (typeof (LIRoptions.singleButtonText) !== "undefined"){ if (LIRoptions.singleButtonText == ""){ LIRoptions.singleButtonText = "Rename and replace"; }	}else{ LIRoptions.singleButtonText = "Rename and replace"; }	if (typeof (LIRoptions.queueButtonText) !== "undefined"){ if (LIRoptions.queueButtonText == ""){ LIRoptions.queueButtonText = "Rename and add to queue"; }	}else{ LIRoptions.queueButtonText = "Rename and add to queue"; } }else{ LIRoptions = { bottomMessage: "", editSummary: 'Updating file links (automatic)', singleButtonText: 'Rename and replace', queueButtonText: 'Rename and add to queue' } } if (typeof localStorage.LIRQueuedUpdates === "undefined"){ localStorage.LIRQueuedUpdates = 0; localStorage.LIRQueuedUpdatesPos = 1; } LIR = { started: false, /*************************************	// Add image to queue function chain **************************************/	start: function(type){ if (!Storage){ return false; }		/* Checks if function has already started */ if (LIR.started == true && typeof LIR.queuePosition === "undefined"){ return false; }		/* Checks whether renaming single image or adding to queue */ if (typeof(type) !== "undefined"){ if (type == "single"){ LIR.started = true; /* Toggles appearance of the loading GIF */ document.getElementById("liveLoader").style.display="inline-block"; $("#queueStatus").html(" Processing"); LIR.type = "single"; }else if (type == "multi"){ LIR.started = true; if (typeof LIR.queuePosition === "undefined"){ LIR.queuePosition = ++localStorage.LIRQueuedUpdates; /* Toggles appearance of the loading GIF */ document.getElementById("liveLoader").style.display="inline-block"; }				if (LIR.queuePosition != localStorage.LIRQueuedUpdatesPos){ $("#queueStatus").html(" Number " + (LIR.queuePosition - localStorage.LIRQueuedUpdatesPos) + " in line to add to queue"); setTimeout(function{LIR.start(type)}, 500); return false; }				$("#queueStatus").html(" Processing"); LIR.type = "multi"; }else{ alert("Incorrect type specified"); return false; }		}else{ LIR.started = true; /* Toggles appearance of the loading GIF */ document.getElementById("liveLoader").style.display="inline-block"; $("#queueStatus").html(" Processing"); LIR.type = "single"; }		/* Retrieves queue, or resets variables if doesn't exist */ if (typeof (localStorage[wgUserName + "_LIRQueueData"]) !== "undefined" && typeof (localStorage[wgUserName + "_LIRPageKey"]) !== "undefined"){ LIR.queueData = JSON.parse(localStorage[wgUserName + "_LIRQueueData"]); LIR.pageKey = JSON.parse(localStorage[wgUserName + "_LIRPageKey"]); }else{ LIR.queueData = []; LIR.pageKey = []; }		/* Sets variables used by the function */ var oldImageName = $('input[name="wpOldTitle"]').val.slice(5); var newImageName = document.getElementById("wpNewTitleMain").value; var current = { page: 0, content: "" }		/* Checks old or new file name is currently part of the queue */ for (i=0; i<LIR.queueData.length; i++){ if (LIR.queueData[i].newImage == oldImageName || LIR.queueData[i].newImage == newImageName){ alert("Image is already added to the queue, or the destination image name is already queued to be used by another file."); LIR.started = false; $("#queueStatus").html(""); if (typeof LIR.queuePosition !== "undefined"){ localStorage.LIRQueuedUpdatesPos++; delete LIR.queuePosition; }				document.getElementById("liveLoader").style.display="none"; return false; }		}		/* Checks if destination file name is valid (since Wikia's server-sided code usually validates this) */ if (newImageName.slice(-4).search(/\.png/i) == -1 && newImageName.slice(-4).search(/\.jpg/i) == -1 && newImageName.slice(-5).search(/\.jpeg/i) == -1 && newImageName.slice(-4).search(/\.gif/i) == -1 && newImageName.slice(-4).search(/\.svg/i) == -1){ alert("File name does not contain a valid file extension. Please add a valid file extension."); LIR.started = false; $("#queueStatus").html(""); if (typeof LIR.queuePosition !== "undefined"){ localStorage.LIRQueuedUpdatesPos++; delete LIR.queuePosition; }			document.getElementById("liveLoader").style.display="none"; return false; }		/* Check if detination file name is in use */ $.getJSON("/api.php?action=query&list=imageusage&iutitle=File:"+encodeURIComponent(newImageName)+"&format=json", function(result){			if (result.query.imageusage.length == 0){				/* If not, then get file usage for image */				$.getJSON("/api.php?action=query&list=imageusage&iutitle=File:"+encodeURIComponent(oldImageName)+"&iulimit=500&format=json", function(result){ imageUsage = result.query.imageusage; if (console) console.log("Image usage successfully retrieved"); if (imageUsage.length > 0){ /* Resets queue-related variables if only renaming and replacing a single image */ if (LIR.type == "single"){ LIR.queueData = []; LIR.pageKey = []; }												/* Adds pages image is used on to window.LIR.pageKey to help keep track of pages in window.LIR.pageData later on */ for (current.page = 0; current.page < imageUsage.length; current.page++){ if (console) console.log("Beginning page "+current.page); var title = imageUsage[current.page].title; if (LIR.pageKey.indexOf(title) == -1){ LIR.pageKey[LIR.pageKey.length] = title; }							/* Temporary until Wikia fixes issue with editing blog comments through the API */ if (title.search(/User blog comment/i) == -1){ LIR.queueData[LIR.queueData.length] = { oldImage: oldImageName, newImage: newImageName, title: title, }							}else{ LIRBlogComment = true; }						}						/* Temporary until Wikia fixes issue with editing blog comments through the API */ if (typeof(LIRBlogComment) === "undefined"){ /* Stores queue if renaming multiple images, or updates file usage if only renaming one */ if (LIR.type == "multi"){ LIR.storeQueue(function {									LIR.started = false;									localStorage.LIRQueuedUpdatesPos++;									$("#wpReason").val($("#wpReason").val + " (pages added to update queue)");									$("#movepage").submit;								}); }else{ /* This may seem odd, but because I use LIR.processQueue for both single and multiple image updating, it requires LIR.started to be false to start */ LIR.started = false; LIR.processQueue(function{									$("#movepage").submit;								}); }						}else{ $("#queueStatus").html(""); if (typeof LIR.queuePosition !== "undefined"){ localStorage.LIRQueuedUpdatesPos++; delete LIR.queuePosition; }							document.getElementById("liveLoader").style.display="none"; alert("One of pages this image is used on is a blog comment. There is currently a bug with Wikia's API concerning editing blog comments. Please update the file links manually."); }					}else{ /* Else, prompt to use normal renaming, since this is kind of pointless otherwise */ alert("Image is not being used on any pages. Please use the regular rename button."); LIR.started = false; $("#queueStatus").html(""); if (typeof LIR.queuePosition !== "undefined"){ localStorage.LIRQueuedUpdatesPos++; delete LIR.queuePosition; }						document.getElementById("liveLoader").style.display="none"; }				});			}else{				alert("This desired file name already exists. If you wish to use that file name, please either delete or rename the existing image.");				LIR.started = false;				$("#queueStatus").html("");				if (typeof LIR.queuePosition !== "undefined"){					localStorage.LIRQueuedUpdatesPos++;					delete LIR.queuePosition;				}				document.getElementById("liveLoader").style.display="none";			}		}); },	storeQueue: function(callback){ /* Standalone function to store the queue in window.localStorage uses wgUserName as a variable key so mulitple-user computers on the same wiki don't get each other's queue*/ localStorage[wgUserName + "_LIRPageKey"] = JSON.stringify(LIR.pageKey); localStorage[wgUserName + "_LIRQueueData"] = JSON.stringify(LIR.queueData); if (typeof(callback) === "function"){ callback; }	},	/**************************************	// Process stored queue function chain **************************************/	processQueue: function(callback){ if (localStorage.LIRQueuedUpdates < localStorage.LIRQueuedUpdatesPos && localStorage.LIRQueuedUpdates != 0){ localStorage.LIRQueuedUpdates = 0; localStorage.LIRQueuedUpdatesPos = 1; }		/* Check if operation already started */ if (LIR.started == true){ return false; }		/* Defaults to multi, since this function is called standalone when processing an existing queue */ if (typeof(LIR.type) === "undefined"){ LIR.type = "multi"; }		/* Variable redeclaration */ LIR.started = true; LIR.requestCompleted = []; LIR.pageData = []; /* Queue retrieval, returns false if no queue */ if (LIR.type == "multi" && localStorage.LIRQueuedUpdates == 0){ if (typeof (localStorage[wgUserName + "_LIRQueueData"]) !== "undefined" && typeof (localStorage[wgUserName + "_LIRPageKey"]) !== "undefined"){ LIR.queueData = JSON.parse(localStorage[wgUserName + "_LIRQueueData"]); LIR.pageKey = JSON.parse(localStorage[wgUserName + "_LIRPageKey"]); if (console) console.log("Queue retrieved sucessfully."); }else{ if (console) console.log("Queue does not exist or was unable to be retrieved."); alert("Queue does not exist or was unable to be retrieved."); LIR.started = false; return false; }		}else if (LIR.type == "multi" && localStorage.LIRQueuedUpdates != 0){ if (console) console.log("Pages still being added to the queue."); alert("Pages are still waiting to be added to the queue. If this is not the case, please use the \"Reset waiting pages\" button to be able to process the queue."); LIR.started = false; return false; }		if (console) console.log("Begin queue execution"); /* Sets progress checking variables */ for (i = 0; i<LIR.pageKey.length; i++){ LIR.requestCompleted[i] = false; }		/* Begin getting page contents */ if (console) console.log("Getting page contents"); titlesString = ""; /* Constructing string of page titles for API query */ for (i in LIR.pageKey){ if (i == 0){ titlesString += LIR.pageKey[i]; }else{ titlesString += "|"+LIR.pageKey[i]; }		}		/* Calls API for page contents */ $.post(			"/api.php",			{				action: "query",				prop: "revisions",				rvprop: "content",				titles: titlesString,				format: "json"			},			function(result){				/* Saves page contents for each page in window.LIR.pageData */				for (i in result.query.pages){					keyNum = LIR.pageKey.indexOf(result.query.pages[i].title);					LIR.pageData[keyNum] = {title: LIR.pageKey[keyNum], content: result.query.pages[i].revisions[0]["*"], changed: false};				}				if (console) console.log("Page contents retrieved and saved");				LIR.log("Page contents retrieved and saved");				if (console) console.log("Begin processing page content.");				/* Replacing image name on each page */				for (i=0; i<LIR.queueData.length; i++){					pageKey = LIR.pageKey.indexOf(LIR.queueData[i].title);					escapedName = window.LIR.queueData[i].oldImage.replace(/\*/gi, "\\*").replace(/\?/gi, "\\?").replace(/\./gi, "\\.").replace(/ /gi, "[ _]*?").replace(/\(/gi, "\\(").replace(/\)/gi, "\\)"); pageReplacement = new RegExp("(\\n[ ]*?|:?File:[ ]*?|=[ ]*?|\\|)" + escapedName + "([ ]*?\\n|[ ]*?\\||\\]|\\})", "gi"); replacementReg = new RegExp(escapedName, "gi"); if (LIR.pageData[pageKey].content.search(pageReplacement) != -1){ LIR.pageData[pageKey].changed = true; if (console) console.log("\""+LIR.queueData[i].oldImage+"\" replaced on page \""+LIR.queueData[i].title+"\""); while ((regExec = pageReplacement.exec(LIR.pageData[pageKey].content)) != null){ LIR.pageData[pageKey].content = LIR.pageData[pageKey].content.replace(regExec[0], regExec[0].replace(replacementReg, LIR.queueData[i].newImage)); pageReplacement.lastIndex += (regExec[0].replace(replacementReg, LIR.queueData[i].newImage).length - regExec[0].length) - (regExec[2].length); }					}else{ if (LIR.type == "multi"){ LIR.failedLog(LIR.queueData[i].oldImage, LIR.queueData[i].newImage, LIR.queueData[i].title); }else{ alert("Unable to find \""+LIR.queueData[i].oldImage+"\" on page \""+LIR.queueData[i].title+"\". Please rename manually."); }					}				}				LIR.log("Page content processed, saving"); if (console) console.log("Begin submitting processed page content."); /* Submits edited pages */ if (LIR.type == "multi"){ $(".modalToolbar").prepend("  "); LIR.queueProgress = 0; }				for (i=0; i<LIR.pageData.length; i++){ if (LIR.pageData[i].changed == true){ LIR.submitChangedPages(i, callback); }else{ LIR.requestCompleted[i] = true; }				}			},			"json" );	},	submitChangedPages: function(pageKey, callback) {		$.ajax({ url: "/api.php", type: "POST", async: true, data: { action: "edit", title: LIR.pageData[pageKey].title, summary: LIRoptions.editSummary, text: LIR.pageData[pageKey].content, minor: true, nocreate: true, redirect: false, bot: true, token: mediaWiki.user.tokens.get("editToken") },			contentType: "application/x-www-form-urlencoded", error: function{ LIR.requestCompleted[pageKey] = true; alert("Unable to publish page \""+LIR.pageKey[pageKey]+"\". Please rename images on that page manually."); if (LIR.requestCompleted.indexOf(false) == -1){ delete localStorage[wgUserName + "_LIRPageKey"]; delete localStorage[wgUserName + "_LIRQueueData"]; LIR.started = false; if (typeof(callback) === "function"){ callback; }				}				},			success: function{ LIR.requestCompleted[pageKey] = true; if (console) console.log("Posted page \""+LIR.pageKey[pageKey]+"\""); if (LIR.type == "multi"){ $("#LIRProgressInd").css("width", ((++LIR.queueProgress) / LIR.pageKey.length * 100) + "%"); }				if (LIR.requestCompleted.indexOf(false) == -1){ if (LIR.type == "multi"){ /* Cleans up localStorage variables */ delete localStorage[wgUserName + "_LIRPageKey"]; delete localStorage[wgUserName + "_LIRQueueData"]; LIR.started = false; $("#LIRQueueProgress").remove; }					/* Call callback if exists */ if (typeof(callback) === "function"){ callback; }				}			}							});	},	/**************************************	// Modal-related functions	**************************************/	log: function(message){		if (typeof(LIR.logMessages) === "undefined"){			LIR.logMessages = " Queue system started. ";		}		LIR.logMessages = LIR.logMessages + " " + message + " ";		if ($("#LIRLog").length > 0){			document.getElementById("LIRLog").innerHTML = LIR.logMessages;			$("#LIRLog").scrollTop(100000000)			$("#LIRLog div:odd").css("background-color", "grey");		}	},	failedLog: function(oldI, newI, page){		if (typeof(LIR.logFailed) === "undefined"){			LIR.logFailed = "";		}		LIR.logFailed += " " + oldI + " --&gt; " + newI + " on " + page + " "; if ($("#LIRFailedLog").length > 0){ document.getElementById("LIRFailedLog").innerHTML = LIR.logFailed; $("#LIRFailedLog div:odd").css("background-color", "darkred"); }	},	updateQueueListing: function{ if (typeof (localStorage[wgUserName + "_LIRQueueData"]) !== "undefined"){ LIR.queueData = JSON.parse(localStorage[wgUserName + "_LIRQueueData"]); }else{ document.getElementById("LIRQueue").innerHTML = " There is currently nothing in the queue. "; LIR.log("Queue updated."); return false; }		LIRCurrentQueueData = LIR.queueData; queueToAdd = ""; for (i = 0; i" + LIRCurrentQueueData[i].oldImage + " --&gt; " + LIRCurrentQueueData[i].newImage + " on " + LIRCurrentQueueData[i].title + " ";		}		document.getElementById("LIRQueue").innerHTML = queueToAdd;		$("#LIRQueue div:odd").css("background-color", "lightgrey");		LIR.log("Queue updated.");	},	showQueueModal: function{		$.showCustomModal( 			"Image link updating queue", 			'   Failed items appear here after execution. ', 			{				id: "optionsWindow", width: 800, buttons: [ {						id: "close", message: "Close", handler: function { $(".close").click; }					},					{						id: "resetCounter", message: "Reset waiting pages", handler: function { if (confirm("This will reset the list of pages waiting to be added to the queue in-case there was a problem processing a page that's preventing you from executing the queue. \n\nNote that there are still " + (localStorage.LIRQueuedUpdates - localStorage.LIRQueuedUpdatesPos - 1) + " page(s) waiting to be added to the queue.  If you are absolutely positive that you currently have no pages open that are waiting in line to be processed or a problem has occured that has halted page processing, then press OK to clear the list of waiting pages. \n\nIf you do have any pages waiting to be processed, you will have to reload and resubmit those pages to the queue to add them.")){ localStorage.LIRQueuedUpdates = 0; localStorage.LIRQueuedUpdatesPos = 1; alert("List of waiting pages cleared"); }						}					},					{						id: "updateButton", message: "Refresh", handler: function{ LIR.updateQueueListing; }					},					{						id: "executeButton", message: "Execute", defaultButton: true, handler: function{ if (typeof localStorage[wgUserName + "_LIRQueueData"] !== "undefined" && typeof localStorage[wgUserName + "_LIRPageKey"] !== "undefined"){ LIR.log("Queue execution started."); LIR.processQueue(function{									LIR.log("Queue executed.");									LIR.updateQueueListing;								}); }else{ LIR.log("No queue exists to be executed"); }						}					}/*,					{						id: "saveQueue", defaultButton: true, message: "Save", handler: function { if (confirm("Save the queue? These changes can't be undone.")){ }						}					}					*/				],				callback: function{ $(".blackout, .close").off("click").click(function{						if ((LIR.started == false || typeof(LIR.started) === "undefined")){							delete LIRCurrentQueueData;							delete LIRCurrentPageKey;							$("#optionsWindow").remove;							$(".blackout").fadeOut(function{ $(this).remove; });						}					});					LIR.log("Queue system opened."); LIR.updateQueueListing; }			}		);	} } if (wgPageName.indexOf("Special:MovePage/File:") != -1){	LIR.appendButtonText = "" + LIRoptions.singleButtonText + "</a>";	if (Storage){		LIR.appendButtonText += "" + LIRoptions.queueButtonText + "</a>";	}	LIR.appendButtonText += " <img src='http://slot1.images.wikia.nocookie.net/__cb62004/common/skins/common/progress-wheel.gif' />

The \""+LIRoptions.singleButtonText+"\" button updates file usages across pages for a single image, while the \""+LIRoptions.queueButtonText+"\" button adds the file usages of the image to a queue to be updated at one time as a group. When updating file usages using the queue, usages located on like pages are grouped together into one edit, rather than one edit per usage. The queue can be accessed and executed through any file page inside the \"Edit\" drop-down. Please note that a saved queue is local to the computer being used, and does not carry over to other computers. ";	if (LIRoptions.bottomMessage != ""){	LIR.appendButtonText += (' ' + LIRoptions.bottomMessage + ' ');	}	$('td.mw-submit').append(LIR.appendButtonText); } if (wgCanonicalNamespace == "File" && Storage){	$("#WikiaPageHeader nav ul").append("<li>Queue</a></li>"); } // //