MediaWiki:Common.js: Difference between revisions

From Official Factorio Wiki
Jump to navigation Jump to search
(combined req-tech and consumers+stack sizes, made a fucntion that updates everything at once)
(fixed the case of the variables, added version prompt to "update all" function)
Line 3: Line 3:
/* Infobox updating */
/* Infobox updating */


var NoInfobox = ["Basic oil processing", "Advanced oil processing", "Coal liquefaction", "Empty barrel", "Heavy oil cracking", "Light oil cracking", "Solid fuel from heavy oil", "Solid fuel from light oil", "Solid fuel from petroleum gas", "Water barrel", "Crude oil barrel", "Heavy oil barrel", "Sulfuric acid barrel", "Light oil barrel", "Petroleum gas barrel", "Lubricant barrel", "Empty crude oil barrel", "Empty heavy oil barrel", "Empty light oil barrel", "Empty lubricant barrel", "Empty petroleum gas barrel", "Empty sulfuric acid barrel", "Empty water barrel", "Fill crude oil barrel", "Fill heavy oil barrel", "Fill light oil barrel", "Fill lubricant barrel", "Fill petroleum gas barrel", "Fill sulfuric acid barrel", "Fill water barrel"]
var noInfobox = ["Basic oil processing", "Advanced oil processing", "Coal liquefaction", "Empty barrel", "Heavy oil cracking", "Light oil cracking", "Solid fuel from heavy oil", "Solid fuel from light oil", "Solid fuel from petroleum gas", "Water barrel", "Crude oil barrel", "Heavy oil barrel", "Sulfuric acid barrel", "Light oil barrel", "Petroleum gas barrel", "Lubricant barrel", "Empty crude oil barrel", "Empty heavy oil barrel", "Empty light oil barrel", "Empty lubricant barrel", "Empty petroleum gas barrel", "Empty sulfuric acid barrel", "Empty water barrel", "Fill crude oil barrel", "Fill heavy oil barrel", "Fill light oil barrel", "Fill lubricant barrel", "Fill petroleum gas barrel", "Fill sulfuric acid barrel", "Fill water barrel"]
var version = "0.15.12";
var version = "0.15.12";




var Para = "";
var para = "";
function getInputPara(Item, Search, Length, Name, ItemName) {
function getInputPara(item, search, length, name, itemName) {
var ParaStart = Item.search(Search) + Length; //finds the beginning of the para, is after para-name
var paraStart = item.search(search) + length; //finds the beginning of the para, is after para-name
if (ParaStart < Length) {
if (paraStart < length) {
console.log(ItemName + ": No " + Name + " found.");
console.log(itemName + ": No " + name + " found.");
Para = "";
para = "";
} else {
} else {
var ParaCut = Item.slice(ParaStart);  //lets the string begin after the parameter name
var paraCut = item.slice(paraStart);  //lets the string begin after the parameter name
var ParaEnd = ParaCut.search(/\||}}/); //finds the end of the parameter definition
var paraEnd = paraCut.search(/\||}}/); //finds the end of the parameter definition
if (ParaEnd < 1) { //Para ends at para-end if it exists
if (paraEnd < 1) { //para ends at para-end if it exists
Para = ParaCut;
para = paraCut;
} else {
} else {
Para = ParaCut.slice(0, ParaEnd);
para = paraCut.slice(0, paraEnd);
}
}
}
}
return Para;
return para;
};
};




var PagePara = "";
var pagePara = "";
function getOldPara(Content, PageParaStart, Length, Name, ItemName) {
function getOldPara(content, pageParaStart, length, name, itemName) {
if (PageParaStart < Length) { //if the start is less than the length of the para name (Name) then the search was unsuccessful
if (pageParaStart < length) { //if the start is less than the length of the para name (name) then the search was unsuccessful
console.log(ItemName + ": No " + Name + " found on page.");
console.log(itemName + ": No " + name + " found on page.");
PagePara = "";
pagePara = "";
} else {
} else {
var PageParaCut = Content.slice(PageParaStart);
var pageParaCut = content.slice(pageParaStart);
PageParaStart = PageParaCut.search(/\w/);
pageParaStart = pageParaCut.search(/\w/);
PageParaCut = PageParaCut.slice(PageParaStart); //removes anything before the parameter that does not belong there, like = and \s
pageParaCut = pageParaCut.slice(pageParaStart); //removes anything before the parameter that does not belong there, like = and \s
var PageParaEnd = PageParaCut.search(/\||}}/); //finds the end of the parameter definition
var pageParaEnd = pageParaCut.search(/\||}}/); //finds the end of the parameter definition
if (PageParaEnd < 1) { //Para ends at para-end if it exists
if (pageParaEnd < 1) { //para ends at para-end if it exists
PagePara = PageParaCut;
pagePara = pageParaCut;
} else {
} else {
PagePara = PageParaCut.slice(0, PageParaEnd);
pagePara = pageParaCut.slice(0, pageParaEnd);
}
}
}
}
return PagePara;
return pagePara;
};
};


var Summary = "";
var summary = "";
var NewContent = "";
var newContent = "";
function UpdatePara(Content, Para, PagePara, Name, NewPageParaStart, Length, ItemName) {  //also needs version, Summary, changes NewContent and Summary
function updatePara(content, para, pagePara, name, newPageParaStart, length, itemName) {  //also needs version, summary, changes newContent and summary
if (PagePara.length > 0) {
if (pagePara.length > 0) {
var NewPageParaCut = Content.slice(NewPageParaStart); //lets the string being after the parameter name
var newPageParaCut = content.slice(newPageParaStart); //lets the string being after the parameter name
var NewPageParaEnd = NewPageParaCut.search(/\||}}/) + NewPageParaStart; //finds the end of the parameter definition, with added parastart so that it's relative to the start of the entire string, not the parameter string
var newPageParaEnd = newPageParaCut.search(/\||}}/) + newPageParaStart; //finds the end of the parameter definition, with added parastart so that it's relative to the start of the entire string, not the parameter string
if (Para.length > 0) {
if (para.length > 0) {
NewContent = Content.slice(0, NewPageParaStart) + " = " + Para + "\n" + Content.slice(NewPageParaEnd);
newContent = content.slice(0, newPageParaStart) + " = " + para + "\n" + content.slice(newPageParaEnd);
console.log("Replaced " + ItemName + " " + Name + ".");
console.log("Replaced " + itemName + " " + name + ".");
Summary = Summary + "Updated " + Name + " to " + version + ". ";
summary = summary + "Updated " + name + " to " + version + ". ";
} else {
} else {
NewPageParaStart = NewPageParaStart - Length; //makes it so that the start of the para string if before the name, so that the name also gets deleted
newPageParaStart = newPageParaStart - length; //makes it so that the start of the para string if before the name, so that the name also gets deleted
NewContent = Content.slice(0, NewPageParaStart) + Content.slice(NewPageParaEnd); //removes what is between parastart and paraend from newcontent
newContent = content.slice(0, newPageParaStart) + content.slice(newPageParaEnd); //removes what is between parastart and paraend from newcontent
console.log("Removed " + ItemName + " " + Name + ". ");
console.log("Removed " + itemName + " " + name + ". ");
Summary = Summary + "Removed " + Name + ". ";
summary = summary + "Removed " + name + ". ";
}
}
} else if (Para.length > 0) {
} else if (para.length > 0) {
var InfoboxStart = Content.search(/{{Infobox/i) + 9; //finds the start of the infobox, excludes {{infobox from the resulting string
var InfoboxStart = content.search(/{{Infobox/i) + 9; //finds the start of the infobox, excludes {{infobox from the resulting string
NewContent = Content.slice(0, InfoboxStart) + "\n|" + Name + " = " + Para + Content.slice(InfoboxStart);
newContent = content.slice(0, InfoboxStart) + "\n|" + name + " = " + para + content.slice(InfoboxStart);
console.log("Added " + ItemName + " " + Name + ". ");
console.log("Added " + itemName + " " + name + ". ");
Summary = Summary + "Added " + Name + ". ";
summary = summary + "Added " + name + ". ";
}
}
};
};




function EditPage(Title, ItemName) { //also uses Summary, globalToken, NewContent
function editPage(title, itemName) { //also uses summary, globalToken, newContent
$.ajax({
$.ajax({
url: 'https://wiki.factorio.com/api.php',
url: 'https://wiki.factorio.com/api.php',
Line 76: Line 76:
format: 'json',
format: 'json',
action: 'edit',
action: 'edit',
title: Title,
title: title,
text: NewContent,
text: newContent,
token: globalToken,
token: globalToken,
summary: Summary,
summary: summary,
bot: true,
bot: true,
nocreate: true
nocreate: true
Line 86: Line 86:
type: 'POST',
type: 'POST',
success: function( data ) {
success: function( data ) {
  console.log("Updated " + ItemName);
  console.log("Updated " + itemName);
},
},
error: function( xhr ) {
error: function( xhr ) {
console.log("Failed to update " + ItemName);
console.log("Failed to update " + itemName);
}
}
});
});
Line 101: Line 101:
function getRecipes() {
function getRecipes() {
getUserGroup();
getUserGroup();
if (UserGroup.some(isBot) == true) {
if (userGroup.some(isBot) == true) {
var RecipeInput = prompt("Please enter the recipes");
var recipeInput = prompt("Please enter the recipes");
if (RecipeInput != null) {
if (recipeInput != null) {
getToken();
getToken();
var Items = RecipeInput.split(/\s\s/g);
var items = recipeInput.split(/\s\s/g);
console.log(Items.length + " Items detected");
console.log(items.length + " items detected");
Items.forEach(RemoveDuplicateRecipesAndUpdateInfobox);
items.forEach(removeDuplicateRecipesAndUpdateInfobox);
}
}
}
}
Line 113: Line 113:




function RemoveDuplicateRecipesAndUpdateInfobox(Recipes) {
function removeDuplicateRecipesAndUpdateInfobox(recipes) {
var ItemNameEnd = Recipes.search("\\|");
var itemNameEnd = recipes.search("\\|");
var ItemName = Recipes.slice(0, ItemNameEnd);
var itemName = recipes.slice(0, itemNameEnd);
ItemName = ItemName.trim();
itemName = itemName.trim();
//Remove Itemnames if the item does not have a page on the wiki, so that the item is removed from the output
//Remove Itemnames if the item does not have a page on the wiki, so that the item is removed from the output
NoInfobox.forEach(function(InfoboxName) {
noInfobox.forEach(function(infoboxName) {
if (ItemName == InfoboxName) {
if (itemName == infoboxName) {
console.log("Removed " + ItemName + " from output.");
console.log("Removed " + itemName + " from output.");
ItemName = "";
itemName = "";
}
}
})
})
if (ItemName.length == 0) {
if (itemName.length == 0) {
return;
return;
}
}
var Recipe = getInputPara(Recipes, "\\|recipe = ", 10, "recipe", ItemName);
var recipe = getInputPara(recipes, "\\|recipe = ", 10, "recipe", itemName);
var TotalRaw = getInputPara(Recipes, "\\|total-raw = ", 13, "total-raw", ItemName);
var totalRaw = getInputPara(recipes, "\\|total-raw = ", 13, "total-raw", itemName);
var ExpRecipe = getInputPara(Recipes, "\\|expensive-recipe = ", 20, "expensive-recipe", ItemName);
var expRecipe = getInputPara(recipes, "\\|expensive-recipe = ", 20, "expensive-recipe", itemName);
var ExpTotalRaw = getInputPara(Recipes, "\\|expensive-total-raw = ", 23, "expensive-total-raw", ItemName);
var expTotalRaw = getInputPara(recipes, "\\|expensive-total-raw = ", 23, "expensive-total-raw", itemName);
//remove whitespace
//remove whitespace
Recipe = Recipe.trim();
recipe = recipe.trim();
TotalRaw = TotalRaw.trim();
totalRaw = totalRaw.trim();
ExpRecipe = ExpRecipe.trim();
expRecipe = expRecipe.trim();
ExpTotalRaw = ExpTotalRaw.trim();
expTotalRaw = expTotalRaw.trim();
//remove duplicate recipes, but only if the recipe actually exists
//remove duplicate recipes, but only if the recipe actually exists
if ((ExpTotalRaw == ExpRecipe) && (ExpTotalRaw.length > 0)) {
if ((expTotalRaw == expRecipe) && (expTotalRaw.length > 0)) {
ExpTotalRaw = "";
expTotalRaw = "";
console.log(ItemName + ": Removed expensive-total-raw because it was a duplicate of expensive-recipe.");
console.log(itemName + ": Removed expensive-total-raw because it was a duplicate of expensive-recipe.");
} else if ((ExpTotalRaw == TotalRaw) && (ExpTotalRaw.length > 0)) {
} else if ((expTotalRaw == totalRaw) && (expTotalRaw.length > 0)) {
ExpTotalRaw = "";
expTotalRaw = "";
console.log(ItemName + ": Removed expensive-total-raw because it was a duplicate of total-raw.");
console.log(itemName + ": Removed expensive-total-raw because it was a duplicate of total-raw.");
}
}
if ((ExpRecipe == Recipe) && (ExpRecipe.length > 0)) {
if ((expRecipe == recipe) && (expRecipe.length > 0)) {
ExpRecipe = "";
expRecipe = "";
console.log(ItemName + ": Removed expensive-recipe because it was a duplicate of recipe.");
console.log(itemName + ": Removed expensive-recipe because it was a duplicate of recipe.");
}
}
if ((TotalRaw == Recipe) && (TotalRaw.length > 0)) {
if ((totalRaw == recipe) && (totalRaw.length > 0)) {
TotalRaw = "";
totalRaw = "";
console.log(ItemName + ": Removed total-raw because it was a duplicate of recipe.");
console.log(itemName + ": Removed total-raw because it was a duplicate of recipe.");
}
}
//get page content of the item -> OldContent
//get page content of the item -> oldContent
var OldContent = "";
var oldContent = "";
$.ajax({
$.ajax({
url: 'https://wiki.factorio.com/api.php',
url: 'https://wiki.factorio.com/api.php',
Line 166: Line 166:
format: 'json',
format: 'json',
action: 'query',
action: 'query',
titles: ItemName + '/infobox',
titles: itemName + '/infobox',
prop: 'revisions',
prop: 'revisions',
rvprop: 'content'
rvprop: 'content'
Line 176: Line 176:
var pages = data.query.pages;
var pages = data.query.pages;
var revisions = pages[Object.keys(pages)[0]].revisions[0];
var revisions = pages[Object.keys(pages)[0]].revisions[0];
OldContent = revisions[Object.keys(revisions)[2]];
oldContent = revisions[Object.keys(revisions)[2]];
var title = pages[Object.keys(pages)[0]].title;
var title = pages[Object.keys(pages)[0]].title;
},
},
error: function( xhr ) {
error: function( xhr ) {
alert( 'Error: Request failed.' );
alert( 'Error: Request failed.' );
OldContent = "";
oldContent = "";
}
}
});
});
if (OldContent.length = 0) {
if (oldContent.length = 0) {
console.log("No " + ItemName + " page found.");
console.log("No " + itemName + " page found.");
return;
return;
}
}
//find recipes in page (OldContent)
//find recipes in page (oldContent)
var PageRecipeStart = OldContent.search(/(\s|\|)recipe/) + 7;
var pageRecipeStart = oldContent.search(/(\s|\|)recipe/) + 7;
var PageRecipe = getOldPara(OldContent, PageRecipeStart, 7, "recipe", ItemName);
var pageRecipe = getOldPara(oldContent, pageRecipeStart, 7, "recipe", itemName);


var PageTotalRawStart = OldContent.search(/(\s|\|)total-raw/) + 10;
var pageTotalRawStart = oldContent.search(/(\s|\|)total-raw/) + 10;
var PageTotalRaw = getOldPara(OldContent, PageTotalRawStart, 10, "total-raw", ItemName);
var pageTotalRaw = getOldPara(oldContent, pageTotalRawStart, 10, "total-raw", itemName);
var PageExpRecipeStart = OldContent.search(/(\s|\|)expensive-recipe/) + 17;
var pageExpRecipeStart = oldContent.search(/(\s|\|)expensive-recipe/) + 17;
var PageExpRecipe = getOldPara(OldContent, PageExpRecipeStart, 17, "expensive-recipe", ItemName);
var pageExpRecipe = getOldPara(oldContent, pageExpRecipeStart, 17, "expensive-recipe", itemName);


var PageExpTotalRawStart = OldContent.search(/(\s|\|)expensive-total-raw/) + 20;
var pageExpTotalRawStart = oldContent.search(/(\s|\|)expensive-total-raw/) + 20;
var PageExpTotalRaw = getOldPara(OldContent, PageExpTotalRawStart, 20, "expensive-total-raw", ItemName);
var pageExpTotalRaw = getOldPara(oldContent, pageExpTotalRawStart, 20, "expensive-total-raw", itemName);


//remove whitespace
//remove whitespace
PageRecipe = PageRecipe.trim();
pageRecipe = pageRecipe.trim();
PageTotalRaw = PageTotalRaw.trim();
pageTotalRaw = pageTotalRaw.trim();
PageExpRecipe = PageExpRecipe.trim();
pageExpRecipe = pageExpRecipe.trim();
PageExpTotalRaw = PageExpTotalRaw.trim();
pageExpTotalRaw = pageExpTotalRaw.trim();
Summary = "";
summary = "";
//change page if anything is different (this INCLUDES different formatting)
//change page if anything is different (this INCLUDES different formatting)
NewContent = "";
newContent = "";
if ((PageRecipe == Recipe) && (PageTotalRaw == TotalRaw) && (PageExpRecipe == ExpRecipe) && (PageExpTotalRaw == ExpTotalRaw)) {
if ((pageRecipe == recipe) && (pageTotalRaw == totalRaw) && (pageExpRecipe == expRecipe) && (pageExpTotalRaw == expTotalRaw)) {
console.log(ItemName + " page was not changed.")
console.log(itemName + " page was not changed.")
} else {
} else {
if (PageRecipe != Recipe) {
if (pageRecipe != recipe) {
NewContent = OldContent;
newContent = oldContent;
var NewPageRecipeStart = NewContent.search(/(\s|\|)recipe/) + 7;
var newPageRecipeStart = newContent.search(/(\s|\|)recipe/) + 7;
UpdatePara(NewContent, Recipe, PageRecipe, "recipe", NewPageRecipeStart, 7, ItemName);
updatePara(newContent, recipe, pageRecipe, "recipe", newPageRecipeStart, 7, itemName);
}
}
if (PageTotalRaw != TotalRaw) {
if (pageTotalRaw != totalRaw) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent
newContent = oldContent
}
}
var NewPageTotalRawStart = NewContent.search(/(\s|\|)total-raw/) + 10;
var newPageTotalRawStart = newContent.search(/(\s|\|)total-raw/) + 10;
UpdatePara(NewContent, TotalRaw, PageTotalRaw, "total-raw", NewPageTotalRawStart, 10, ItemName);
updatePara(newContent, totalRaw, pageTotalRaw, "total-raw", newPageTotalRawStart, 10, itemName);
}
}
if (PageExpRecipe != ExpRecipe) {
if (pageExpRecipe != expRecipe) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent
newContent = oldContent
}
}
var NewPageExpRecipeStart = NewContent.search(/(\s|\|)expensive-recipe/) + 17;
var newPageExpRecipeStart = newContent.search(/(\s|\|)expensive-recipe/) + 17;
UpdatePara(NewContent, ExpRecipe, PageExpRecipe, "expensive-recipe", NewPageExpRecipeStart, 17, ItemName);
updatePara(newContent, expRecipe, pageExpRecipe, "expensive-recipe", newPageExpRecipeStart, 17, itemName);
}
}
if (PageExpTotalRaw != ExpTotalRaw) {
if (pageExpTotalRaw != expTotalRaw) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent
newContent = oldContent
}
}
var NewPageExpTotalRawStart = NewContent.search(/(\s|\|)expensive-total-raw/) + 20;
var newPageExpTotalRawStart = newContent.search(/(\s|\|)expensive-total-raw/) + 20;
UpdatePara(NewContent, ExpTotalRaw, PageExpTotalRaw, "expensive-total-raw", NewPageExpTotalRawStart, 20, ItemName);
updatePara(newContent, expTotalRaw, pageExpTotalRaw, "expensive-total-raw", newPageExpTotalRawStart, 20, itemName);
}
}
}
}
//alright, NewContent should be defined, change page:
//alright, newContent should be defined, change page:
if (NewContent.length > 0) {
if (newContent.length > 0) {
EditPage(ItemName + "/infobox", ItemName);
editPage(itemName + "/infobox", itemName);
}
}
}
}
Line 256: Line 256:
function getItems() {
function getItems() {
getUserGroup();
getUserGroup();
if (UserGroup.some(isBot) == false) {
if (userGroup.some(isBot) == false) {
return;
return;
}
}
var ItemInput = prompt("Please enter the consumers, stack-sizes and required-technologies");
var itemInput = prompt("Please enter the consumers, stack-sizes and required-technologies");
if (ItemInput != null) {
if (itemInput != null) {
getToken();
getToken();
var Items = ItemInput.split(/\s\s/g);
var items = itemInput.split(/\s\s/g);
console.log(Items.length + " Items detected");
console.log(items.length + " items detected");
Items.forEach(UpdateItemInfoboxes);
items.forEach(updateItemInfoboxes);
}
}
};
};


function UpdateItemInfoboxes(Item) {
function updateItemInfoboxes(item) {
var ItemNameEnd = Item.search("\\|");
var itemNameEnd = item.search("\\|");
var ItemName = Item.slice(0, ItemNameEnd);
var itemName = item.slice(0, itemNameEnd);
ItemName = ItemName.trim();
itemName = itemName.trim();
//Remove Items that don't have Infoboxes on the wiki
//Remove items that don't have Infoboxes on the wiki
NoInfobox.forEach(function(InfoboxName) {
noInfobox.forEach(function(infoboxName) {
if (ItemName == InfoboxName) {
if (itemName == infoboxName) {
console.log("Removed " + ItemName + " from output.");
console.log("Removed " + itemName + " from output.");
ItemName = "";
itemName = "";
}
}
})
})
if (ItemName.length == 0) {
if (itemName.length == 0) {
return;
return;
}
}
var Consumers = getInputPara(Item, "\\|consumers = ", 13, "consumers", ItemName);
var consumers = getInputPara(item, "\\|consumers = ", 13, "consumers", itemName);
var StackSize = getInputPara(Item, "\\|stack-size = ", 14, "stack-size", ItemName);
var stackSize = getInputPara(item, "\\|stack-size = ", 14, "stack-size", itemName);
var ReqTech = getInputPara(Item, "\\|required-technologies = ", 25, "required-technologies", ItemName);
var reqTech = getInputPara(item, "\\|required-technologies = ", 25, "required-technologies", itemName);


Consumers = Consumers.trim();
consumers = consumers.trim();
StackSize = StackSize.trim();
stackSize = stackSize.trim();
ReqTech = ReqTech.trim();
reqTech = reqTech.trim();
//get page content of the item -> OldContent
//get page content of the item -> oldContent
var OldContent = "";
var oldContent = "";
$.ajax({
$.ajax({
url: 'https://wiki.factorio.com/api.php',
url: 'https://wiki.factorio.com/api.php',
Line 300: Line 300:
format: 'json',
format: 'json',
action: 'query',
action: 'query',
titles: ItemName + '/infobox',
titles: itemName + '/infobox',
prop: 'revisions',
prop: 'revisions',
rvprop: 'content'
rvprop: 'content'
Line 310: Line 310:
var pages = data.query.pages;
var pages = data.query.pages;
var revisions = pages[Object.keys(pages)[0]].revisions[0];
var revisions = pages[Object.keys(pages)[0]].revisions[0];
OldContent = revisions[Object.keys(revisions)[2]];
oldContent = revisions[Object.keys(revisions)[2]];
var title = pages[Object.keys(pages)[0]].title;
var title = pages[Object.keys(pages)[0]].title;
},
},
error: function( xhr ) {
error: function( xhr ) {
alert( 'Error: Request failed.' );
alert( 'Error: Request failed.' );
OldContent = "";
oldContent = "";
}
}
});
});
if (OldContent.length = 0) {
if (oldContent.length = 0) {
console.log("No " + ItemName + " page found.");
console.log("No " + itemName + " page found.");
return;
return;
}
}
//find recipes in page (OldContent)
//find recipes in page (oldContent)
var PageConsumersStart = OldContent.search(/(\s|\|)consumers/) + 10;
var pageConsumersStart = oldContent.search(/(\s|\|)consumers/) + 10;
var PageConsumers = getOldPara(OldContent, PageConsumersStart, 10, "consumers", ItemName);
var pageConsumers = getOldPara(oldContent, pageConsumersStart, 10, "consumers", itemName);
var PageStackSizeStart = OldContent.search(/(\s|\|)stack-size/) + 11;
var pageStackSizeStart = oldContent.search(/(\s|\|)stack-size/) + 11;
var PageStackSize = getOldPara(OldContent, PageStackSizeStart, 11, "stack-size", ItemName);
var pageStackSize = getOldPara(oldContent, pageStackSizeStart, 11, "stack-size", itemName);
var PageReqTechStart = OldContent.search(/(\s|\|)required-technologies/) + 22;
var pageReqTechStart = oldContent.search(/(\s|\|)required-technologies/) + 22;
var PageReqTech = getOldPara(OldContent, PageReqTechStart, 22, "required-technologies", ItemName);
var pageReqTech = getOldPara(oldContent, pageReqTechStart, 22, "required-technologies", itemName);
PageConsumers = PageConsumers.trim();
pageConsumers = pageConsumers.trim();
PageStackSize = PageStackSize.trim();
pageStackSize = pageStackSize.trim();
PageReqTech = PageReqTech.trim();
pageReqTech = pageReqTech.trim();
Summary = "";
summary = "";
NewContent = "";
newContent = "";
if ((PageConsumers == Consumers) && (PageStackSize == StackSize) && (PageReqTech == ReqTech)) {
if ((pageConsumers == consumers) && (pageStackSize == stackSize) && (pageReqTech == reqTech)) {
console.log(ItemName + " page was not changed.")
console.log(itemName + " page was not changed.")
} else {
} else {
if (PageConsumers != Consumers) {
if (pageConsumers != consumers) {
NewContent = OldContent;
newContent = oldContent;
var NewPageConsumersStart = NewContent.search(/(\s|\|)consumers/) + 10;
var newPageConsumersStart = newContent.search(/(\s|\|)consumers/) + 10;
UpdatePara(NewContent, Consumers, PageConsumers, "consumers", NewPageConsumersStart, 10, ItemName);
updatePara(newContent, consumers, pageConsumers, "consumers", newPageConsumersStart, 10, itemName);
}
}
if (PageStackSize != StackSize) {
if (pageStackSize != stackSize) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent;
newContent = oldContent;
}
}
var NewPageStackSizeStart = NewContent.search(/(\s|\|)stack-size/) + 11;
var newPageStackSizeStart = newContent.search(/(\s|\|)stack-size/) + 11;
UpdatePara(NewContent, StackSize, PageStackSize, "stack-size", NewPageStackSizeStart, 11, ItemName);
updatePara(newContent, stackSize, pageStackSize, "stack-size", newPageStackSizeStart, 11, itemName);
}
}
if (PageReqTech != ReqTech) {
if (pageReqTech != reqTech) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent;
newContent = oldContent;
}
}
var NewPageReqTechStart = NewContent.search(/(\s|\|)required-technologies/) + 22;
var newPageReqTechStart = newContent.search(/(\s|\|)required-technologies/) + 22;
UpdatePara(NewContent, ReqTech, PageReqTech, "required-technologies", NewPageReqTechStart, 22, ItemName);
updatePara(newContent, reqTech, pageReqTech, "required-technologies", newPageReqTechStart, 22, itemName);
}
}
}
}
//alright, NewContent should be defined, change page:
//alright, newContent should be defined, change page:
if (NewContent.length > 0) {
if (newContent.length > 0) {
EditPage(ItemName + "/infobox", ItemName);
editPage(itemName + "/infobox", itemName);
}
}
}
}
Line 377: Line 377:
function getTechnologies() {
function getTechnologies() {
getUserGroup();
getUserGroup();
if (UserGroup.some(isBot) == false) {
if (userGroup.some(isBot) == false) {
return;
return;
}
}
var TechInput = prompt("Please enter the technologies");
var techInput = prompt("Please enter the technologies");
if (TechInput != null) {
if (techInput != null) {
getToken();
getToken();
var Techs = TechInput.split(/\s\s/g);
var techs = techInput.split(/\s\s/g);
console.log(Techs.length + " Techs detected");
console.log(techs.length + " techs detected");
Techs.forEach(UpdateTechnologyInfobox);
techs.forEach(updateTechnologyInfobox);
}
}
}
}


function UpdateTechnologyInfobox(Tech) {
function updateTechnologyInfobox(tech) {
var TechNameEnd = Tech.search("\\|");
var techNameEnd = tech.search("\\|");
var TechName = Tech.slice(0, TechNameEnd);
var techName = tech.slice(0, techNameEnd);
TechName = TechName.trim();
techName = techName.trim();
var Cost = getInputPara(Tech, "\\|cost = ", 8, "cost", TechName);
var cost = getInputPara(tech, "\\|cost = ", 8, "cost", techName);
var CostMulti = getInputPara(Tech, "\\|cost-multiplier = ", 19, "cost-multiplier", TechName);
var costMulti = getInputPara(tech, "\\|cost-multiplier = ", 19, "cost-multiplier", techName);
var ExpCostMulti = getInputPara(Tech, "\\|expensive-cost-multiplier = ", 29, "expensive-cost-multiplier", TechName);
var expCostMulti = getInputPara(tech, "\\|expensive-cost-multiplier = ", 29, "expensive-cost-multiplier", techName);
var ReqTech = getInputPara(Tech, "\\|required-technologies = ", 25, "required-technologies", TechName);
var reqTech = getInputPara(tech, "\\|required-technologies = ", 25, "required-technologies", techName);
var Allows = getInputPara(Tech, "\\|allows = ", 10, "allows", TechName);
var allows = getInputPara(tech, "\\|allows = ", 10, "allows", techName);
var Effects = getInputPara(Tech, "\\|effects = ", 11, "effects", TechName);
var effects = getInputPara(tech, "\\|effects = ", 11, "effects", techName);


Cost = Cost.trim();
cost = cost.trim();
CostMulti = CostMulti.trim();
costMulti = costMulti.trim();
ExpCostMulti = ExpCostMulti.trim();
expCostMulti = expCostMulti.trim();
ReqTech = ReqTech.trim();
reqTech = reqTech.trim();
Allows = Allows.trim();
allows = allows.trim();
Effects = Effects.trim();
effects = effects.trim();
//get page content of the tech -> OldContent
//get page content of the tech -> oldContent
var OldContent = "";
var oldContent = "";
$.ajax({
$.ajax({
url: 'https://wiki.factorio.com/api.php',
url: 'https://wiki.factorio.com/api.php',
Line 418: Line 418:
format: 'json',
format: 'json',
action: 'query',
action: 'query',
titles: TechName + ' (research)/infobox',
titles: techName + ' (research)/infobox',
prop: 'revisions',
prop: 'revisions',
rvprop: 'content'
rvprop: 'content'
Line 428: Line 428:
var pages = data.query.pages;
var pages = data.query.pages;
var revisions = pages[Object.keys(pages)[0]].revisions[0];
var revisions = pages[Object.keys(pages)[0]].revisions[0];
OldContent = revisions[Object.keys(revisions)[2]];
oldContent = revisions[Object.keys(revisions)[2]];
var title = pages[Object.keys(pages)[0]].title;
var title = pages[Object.keys(pages)[0]].title;
},
},
error: function( xhr ) {
error: function( xhr ) {
alert( 'Error: Request failed.' );
alert( 'Error: Request failed.' );
OldContent = "";
oldContent = "";
}
}
});
});
if (OldContent.length = 0) {
if (oldContent.length = 0) {
console.log("No " + TechName + " page found.");
console.log("No " + techName + " page found.");
return;
return;
}
}
//find costs etc in page (OldContent)
//find costs etc in page (oldContent)
var PageCostStart = OldContent.search(/(\s|\|)cost(\s|=)/) + 6;
var pageCostStart = oldContent.search(/(\s|\|)cost(\s|=)/) + 6;
var PageCost = getOldPara(OldContent, PageCostStart, 6, "cost", TechName);
var pageCost = getOldPara(oldContent, pageCostStart, 6, "cost", techName);
var PageCostMultiStart = OldContent.search(/(\s|\|)cost-multiplier/) + 16;
var pageCostMultiStart = oldContent.search(/(\s|\|)cost-multiplier/) + 16;
var PageCostMulti = getOldPara(OldContent, PageCostMultiStart, 16, "cost-multiplier", TechName);
var pageCostMulti = getOldPara(oldContent, pageCostMultiStart, 16, "cost-multiplier", techName);
var PageExpCostMultiStart = OldContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
var pageExpCostMultiStart = oldContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
var PageExpCostMulti = getOldPara(OldContent, PageExpCostMultiStart, 26, "expensive-cost-multiplier", TechName);
var pageExpCostMulti = getOldPara(oldContent, pageExpCostMultiStart, 26, "expensive-cost-multiplier", techName);
var PageReqTechStart = OldContent.search(/(\s|\|)required-technologies/) + 22;
var pageReqTechStart = oldContent.search(/(\s|\|)required-technologies/) + 22;
var PageReqTech = getOldPara(OldContent, PageReqTechStart, 22, "required-technologies", TechName);
var pageReqTech = getOldPara(oldContent, pageReqTechStart, 22, "required-technologies", techName);
var PageAllowsStart = OldContent.search(/(\s|\|)allows/) + 7;
var pageAllowsStart = oldContent.search(/(\s|\|)allows/) + 7;
var PageAllows = getOldPara(OldContent, PageAllowsStart, 7, "allows", TechName);
var pageAllows = getOldPara(oldContent, pageAllowsStart, 7, "allows", techName);
var PageEffectsStart = OldContent.search(/(\s|\|)effects/) + 8;
var pageEffectsStart = oldContent.search(/(\s|\|)effects/) + 8;
var PageEffects = getOldPara(OldContent, PageEffectsStart, 8, "effects", TechName);
var pageEffects = getOldPara(oldContent, pageEffectsStart, 8, "effects", techName);


PageCost = PageCost.trim();
pageCost = pageCost.trim();
PageCostMulti = PageCostMulti.trim();
pageCostMulti = pageCostMulti.trim();
PageExpCostMulti = PageExpCostMulti.trim();
pageExpCostMulti = pageExpCostMulti.trim();
PageReqTech = PageReqTech.trim();
pageReqTech = pageReqTech.trim();
PageAllows = PageAllows.trim();
pageAllows = pageAllows.trim();
PageEffects = PageEffects.trim();
pageEffects = pageEffects.trim();
Summary = "";
summary = "";
NewContent = "";
newContent = "";
//change page if anything is different (this INCLUDES different formatting)
//change page if anything is different (this INCLUDES different formatting)
if ((PageCost == Cost) && (PageCostMulti == CostMulti) && (PageExpCostMulti == ExpCostMulti) && (PageReqTech == ReqTech) && (PageAllows == Allows) && (PageEffects == Effects)) {
if ((pageCost == cost) && (pageCostMulti == costMulti) && (pageExpCostMulti == expCostMulti) && (pageReqTech == reqTech) && (pageAllows == allows) && (pageEffects == effects)) {
console.log(TechName + " page was not changed.")
console.log(techName + " page was not changed.")
} else {
} else {
if (PageCost != Cost) {
if (pageCost != cost) {
NewContent = OldContent;
newContent = oldContent;
var NewPageCostStart = NewContent.search(/(\s|\|)cost(\s|=)/) + 6;
var newPageCostStart = newContent.search(/(\s|\|)cost(\s|=)/) + 6;
UpdatePara(NewContent, Cost, PageCost, "cost", NewPageCostStart, 6, TechName);
updatePara(newContent, cost, pageCost, "cost", newPageCostStart, 6, techName);
}
}
if (PageCostMulti != CostMulti) {
if (pageCostMulti != costMulti) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent;
newContent = oldContent;
}
}
var NewPageCostMultiStart = NewContent.search(/(\s|\|)cost-multiplier/) + 16;
var newPageCostMultiStart = newContent.search(/(\s|\|)cost-multiplier/) + 16;
UpdatePara(NewContent, CostMulti, PageCostMulti, "cost-multiplier", NewPageCostMultiStart, 16, TechName);
updatePara(newContent, costMulti, pageCostMulti, "cost-multiplier", newPageCostMultiStart, 16, techName);
}
}
if (PageExpCostMulti != ExpCostMulti) {
if (pageExpCostMulti != expCostMulti) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent;
newContent = oldContent;
}
}
var NewPageExpCostMultiStart = NewContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
var newPageExpCostMultiStart = newContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
UpdatePara(NewContent, ExpCostMulti, PageExpCostMulti, "expensive-cost-multiplier", NewPageExpCostMultiStart, 26, TechName);
updatePara(newContent, expCostMulti, pageExpCostMulti, "expensive-cost-multiplier", newPageExpCostMultiStart, 26, techName);
}
}
if (PageReqTech != ReqTech) {
if (pageReqTech != reqTech) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent;
newContent = oldContent;
}
}
var NewPageReqTechStart = NewContent.search(/(\s|\|)required-technologies/) + 22;
var newPageReqTechStart = newContent.search(/(\s|\|)required-technologies/) + 22;
UpdatePara(NewContent, ReqTech, PageReqTech, "required-technologies", NewPageReqTechStart, 22, TechName);
updatePara(newContent, reqTech, pageReqTech, "required-technologies", newPageReqTechStart, 22, techName);
}
}
if (PageAllows != Allows) {
if (pageAllows != allows) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent;
newContent = oldContent;
}
}
var NewPageAllowsStart = NewContent.search(/(\s|\|)allows/) + 7;
var newPageAllowsStart = newContent.search(/(\s|\|)allows/) + 7;
UpdatePara(NewContent, Allows, PageAllows, "allows", NewPageAllowsStart, 7, TechName);
updatePara(newContent, allows, pageAllows, "allows", newPageAllowsStart, 7, techName);
}
}
if (PageEffects != Effects) {
if (pageEffects != effects) {
if (NewContent.length == 0) {
if (newContent.length == 0) {
NewContent = OldContent;
newContent = oldContent;
}
}
var NewPageEffectsStart = NewContent.search(/(\s|\|)effects/) + 8;
var newPageEffectsStart = newContent.search(/(\s|\|)effects/) + 8;
UpdatePara(NewContent, Effects, PageEffects, "effects", NewPageEffectsStart, 8, TechName);
updatePara(newContent, effects, pageEffects, "effects", newPageEffectsStart, 8, techName);
}
}
}
}
//alright, NewContent should be defined, change page:
//alright, newContent should be defined, change page:
if (NewContent.length > 0) {
if (newContent.length > 0) {
EditPage(TechName + " (research)/infobox", TechName);
editPage(techName + " (research)/infobox", techName);
}
}
}
}
Line 530: Line 530:
function getAll() {
function getAll() {
getUserGroup();
getUserGroup();
if (UserGroup.some(isBot) == false) {
if (userGroup.some(isBot) == false) {
return;
return;
}
}
getToken();
getToken();
var RecipeInput = prompt("Please enter the recipes.");
version = prompt("Please enter the new version.");
var ItemInput = prompt("Please enter the consumers, stack-sizes and required-technologies.");
version = version.trim();
var TechInput = prompt("Please enter the technologies.");
var recipeInput = prompt("Please enter the recipes.");
var itemInput = prompt("Please enter the consumers, stack-sizes and required-technologies.");
var techInput = prompt("Please enter the technologies.");
if (RecipeInput != null) {
if (recipeInput != null) {
var RecipeArray = RecipeInput.split(/\s\s/g);
var recipeArray = recipeInput.split(/\s\s/g);
console.log(RecipeArray.length + " Recipes detected");
console.log(recipeArray.length + " recipes detected");
RecipeArray.forEach(RemoveDuplicateRecipesAndUpdateInfobox);
recipeArray.forEach(removeDuplicateRecipesAndUpdateInfobox);
}
}
if (ItemInput != null) {
if (itemInput != null) {
var Items = ItemInput.split(/\s\s/g);
var items = itemInput.split(/\s\s/g);
console.log(Items.length + " Items detected");
console.log(items.length + " items detected");
Items.forEach(UpdateItemInfoboxes);
items.forEach(updateItemInfoboxes);
}
}
if (TechInput != null) {
if (techInput != null) {
var Techs = TechInput.split(/\s\s/g);
var techs = techInput.split(/\s\s/g);
console.log(Techs.length + " Techs detected");
console.log(techs.length + " techs detected");
Techs.forEach(UpdateTechnologyInfobox);
techs.forEach(updateTechnologyInfobox);
}
}
}
}
/* User is bot if UserGroup.some(isBot) == true */
/* User is bot if UserGroup.some(isBot) == true */



Revision as of 17:59, 6 June 2017

/* Any JavaScript here will be loaded for all users on every page load. */
	
/* Infobox updating */

var noInfobox = ["Basic oil processing", "Advanced oil processing", "Coal liquefaction", "Empty barrel", "Heavy oil cracking", "Light oil cracking", "Solid fuel from heavy oil", "Solid fuel from light oil", "Solid fuel from petroleum gas", "Water barrel", "Crude oil barrel", "Heavy oil barrel", "Sulfuric acid barrel", "Light oil barrel", "Petroleum gas barrel", "Lubricant barrel", "Empty crude oil barrel", "Empty heavy oil barrel", "Empty light oil barrel", "Empty lubricant barrel", "Empty petroleum gas barrel", "Empty sulfuric acid barrel", "Empty water barrel", "Fill crude oil barrel", "Fill heavy oil barrel", "Fill light oil barrel", "Fill lubricant barrel", "Fill petroleum gas barrel", "Fill sulfuric acid barrel", "Fill water barrel"]
var version = "0.15.12";


var para = "";
function getInputPara(item, search, length, name, itemName) {
	var paraStart = item.search(search) + length; //finds the beginning of the para, is after para-name
	if (paraStart < length) {
		console.log(itemName + ": No " + name + " found.");
		para = "";
	} else {
		var paraCut = item.slice(paraStart);  //lets the string begin after the parameter name
		var paraEnd = paraCut.search(/\||}}/); //finds the end of the parameter definition
		if (paraEnd < 1) { //para ends at para-end if it exists
			para = paraCut;
		} else {
			para = paraCut.slice(0, paraEnd);
		}
	}
	return para;
};


var pagePara = "";
function getOldPara(content, pageParaStart, length, name, itemName) {
	if (pageParaStart < length) { //if the start is less than the length of the para name (name) then the search was unsuccessful
		console.log(itemName + ": No " + name + " found on page.");
		pagePara = "";
	} else {
		var pageParaCut = content.slice(pageParaStart);
		pageParaStart = pageParaCut.search(/\w/);
		pageParaCut = pageParaCut.slice(pageParaStart); //removes anything before the parameter that does not belong there, like = and \s
		var pageParaEnd = pageParaCut.search(/\||}}/); //finds the end of the parameter definition
		if (pageParaEnd < 1) { //para ends at para-end if it exists
			pagePara = pageParaCut;
		} else {
			pagePara = pageParaCut.slice(0, pageParaEnd);
		}
	}
	return pagePara;
};

var summary = "";
var newContent = "";
function updatePara(content, para, pagePara, name, newPageParaStart, length, itemName) {  //also needs version, summary, changes newContent and summary
	if (pagePara.length > 0) {
		var newPageParaCut = content.slice(newPageParaStart); //lets the string being after the parameter name
		var newPageParaEnd = newPageParaCut.search(/\||}}/) + newPageParaStart; //finds the end of the parameter definition, with added parastart so that it's relative to the start of the entire string, not the parameter string
		if (para.length > 0) {
			newContent = content.slice(0, newPageParaStart) + " = " + para + "\n" + content.slice(newPageParaEnd);
			console.log("Replaced " + itemName + " " + name + ".");
			summary = summary + "Updated " + name + " to " + version + ". ";
		} else {
			newPageParaStart = newPageParaStart - length; //makes it so that the start of the para string if before the name, so that the name also gets deleted
			newContent = content.slice(0, newPageParaStart) + content.slice(newPageParaEnd); //removes what is between parastart and paraend from newcontent
			console.log("Removed " + itemName + " " + name + ". ");
			summary = summary + "Removed " + name + ". ";
		}
	} else if (para.length > 0) {
		var InfoboxStart = content.search(/{{Infobox/i) + 9; //finds the start of the infobox, excludes {{infobox from the resulting string
		newContent = content.slice(0, InfoboxStart) + "\n|" + name + " = " + para + content.slice(InfoboxStart);
		console.log("Added " + itemName + " " + name + ". ");
		summary = summary + "Added " + name + ". ";
	}
};


function editPage(title, itemName) { //also uses summary, globalToken, newContent
	$.ajax({
		url: 'https://wiki.factorio.com/api.php',
		data: {
			format: 'json',
			action: 'edit',
			title: title,
			text: newContent,
			token: globalToken,
			summary: summary,
			bot: true,
			nocreate: true
		},
		dataType: 'json',
		type: 'POST',
		success: function( data ) {
		   console.log("Updated " + itemName);
		},
		error: function( xhr ) {
			console.log("Failed to update " + itemName);
		}
	});
};


$("#RecipeUpdate").click(function(){
    getRecipes();
});

function getRecipes() {
	getUserGroup();
	if (userGroup.some(isBot) == true) {
		var recipeInput = prompt("Please enter the recipes");
		if (recipeInput != null) {
			getToken();
			var items = recipeInput.split(/\s\s/g);
			console.log(items.length + " items detected");
			items.forEach(removeDuplicateRecipesAndUpdateInfobox);
		}
	}
};


function removeDuplicateRecipesAndUpdateInfobox(recipes) {
	var itemNameEnd = recipes.search("\\|");
	var itemName = recipes.slice(0, itemNameEnd);
	itemName = itemName.trim();
	
	//Remove Itemnames if the item does not have a page on the wiki, so that the item is removed from the output
	noInfobox.forEach(function(infoboxName) {
	if (itemName == infoboxName) {
		console.log("Removed " + itemName + " from output.");
		itemName = "";
	}
	})
	if (itemName.length == 0) {
		return;
	}
	
	var recipe = getInputPara(recipes, "\\|recipe = ", 10, "recipe", itemName);
	var totalRaw = getInputPara(recipes, "\\|total-raw = ", 13, "total-raw", itemName);
	var expRecipe = getInputPara(recipes, "\\|expensive-recipe = ", 20, "expensive-recipe", itemName);
	var expTotalRaw = getInputPara(recipes, "\\|expensive-total-raw = ", 23, "expensive-total-raw", itemName);
	
	//remove whitespace
	recipe = recipe.trim();
	totalRaw = totalRaw.trim();
	expRecipe = expRecipe.trim();
	expTotalRaw = expTotalRaw.trim();	
	
	
	//remove duplicate recipes, but only if the recipe actually exists
	if ((expTotalRaw == expRecipe) && (expTotalRaw.length > 0)) {
		expTotalRaw = "";
		console.log(itemName + ": Removed expensive-total-raw because it was a duplicate of expensive-recipe.");
	} else if ((expTotalRaw == totalRaw) && (expTotalRaw.length > 0)) {
		expTotalRaw = "";
		console.log(itemName + ": Removed expensive-total-raw because it was a duplicate of total-raw.");
	}
	if ((expRecipe == recipe) && (expRecipe.length > 0)) {
		expRecipe = "";
		console.log(itemName + ": Removed expensive-recipe because it was a duplicate of recipe.");
	}
	if ((totalRaw == recipe) && (totalRaw.length > 0)) {
		totalRaw = "";
		console.log(itemName + ": Removed total-raw because it was a duplicate of recipe.");
	}
	
	
	//get page content of the item -> oldContent
	var oldContent = "";
	$.ajax({
		url: 'https://wiki.factorio.com/api.php',
		data: {
			format: 'json',
			action: 'query',
			titles: itemName + '/infobox',
			prop: 'revisions',
			rvprop: 'content'
		},
		async: false,
		dataType: 'json',
		type: 'GET',
		success: function( data ) {
			var pages = data.query.pages;
			var revisions = pages[Object.keys(pages)[0]].revisions[0];
			oldContent = revisions[Object.keys(revisions)[2]];
			var title = pages[Object.keys(pages)[0]].title;
		},
		error: function( xhr ) {
			alert( 'Error: Request failed.' );
			oldContent = "";
		}
	});
	if (oldContent.length = 0) {
		console.log("No " + itemName + " page found.");
		return;
	}
	
	
	//find recipes in page (oldContent)
	var pageRecipeStart = oldContent.search(/(\s|\|)recipe/) + 7;
	var pageRecipe = getOldPara(oldContent, pageRecipeStart, 7, "recipe", itemName);

	var pageTotalRawStart = oldContent.search(/(\s|\|)total-raw/) + 10;
	var pageTotalRaw = getOldPara(oldContent, pageTotalRawStart, 10, "total-raw", itemName);
	
	var pageExpRecipeStart = oldContent.search(/(\s|\|)expensive-recipe/) + 17;
	var pageExpRecipe = getOldPara(oldContent, pageExpRecipeStart, 17, "expensive-recipe", itemName);

	var pageExpTotalRawStart = oldContent.search(/(\s|\|)expensive-total-raw/) + 20;
	var pageExpTotalRaw = getOldPara(oldContent, pageExpTotalRawStart, 20, "expensive-total-raw", itemName);

	
	//remove whitespace
	pageRecipe = pageRecipe.trim();
	pageTotalRaw = pageTotalRaw.trim();
	pageExpRecipe = pageExpRecipe.trim();
	pageExpTotalRaw = pageExpTotalRaw.trim();
	
	summary = "";
	
	//change page if anything is different (this INCLUDES different formatting)
	newContent = "";
	if ((pageRecipe == recipe) && (pageTotalRaw == totalRaw) && (pageExpRecipe == expRecipe) && (pageExpTotalRaw == expTotalRaw)) {
		console.log(itemName + " page was not changed.")
	} else {
		if (pageRecipe != recipe) {
			newContent = oldContent;
			var newPageRecipeStart = newContent.search(/(\s|\|)recipe/) + 7;
			updatePara(newContent, recipe, pageRecipe, "recipe", newPageRecipeStart, 7, itemName);
		}
		if (pageTotalRaw != totalRaw) {
			if (newContent.length == 0) {
				newContent = oldContent
			}
			var newPageTotalRawStart = newContent.search(/(\s|\|)total-raw/) + 10;
			updatePara(newContent, totalRaw, pageTotalRaw, "total-raw", newPageTotalRawStart, 10, itemName);
		}
		if (pageExpRecipe != expRecipe) {
			if (newContent.length == 0) {
				newContent = oldContent
			}
			var newPageExpRecipeStart = newContent.search(/(\s|\|)expensive-recipe/) + 17;
			updatePara(newContent, expRecipe, pageExpRecipe, "expensive-recipe", newPageExpRecipeStart, 17, itemName);
		}
		if (pageExpTotalRaw != expTotalRaw) {
			if (newContent.length == 0) {
				newContent = oldContent
			}
			var newPageExpTotalRawStart = newContent.search(/(\s|\|)expensive-total-raw/) + 20;
			updatePara(newContent, expTotalRaw, pageExpTotalRaw, "expensive-total-raw", newPageExpTotalRawStart, 20, itemName);
		}
	}
	//alright, newContent should be defined, change page:
	if (newContent.length > 0) {
		editPage(itemName + "/infobox", itemName);
	}	
}

$("#ItemUpdate").click(function(){
    getItems();
});

function getItems() {
	getUserGroup();
	if (userGroup.some(isBot) == false) {
		return;
	}
	var itemInput = prompt("Please enter the consumers, stack-sizes and required-technologies");
	if (itemInput != null) {
		getToken();
		var items = itemInput.split(/\s\s/g);
		console.log(items.length + " items detected");
		items.forEach(updateItemInfoboxes);
	}
};

function updateItemInfoboxes(item) {
	var itemNameEnd = item.search("\\|");
	var itemName = item.slice(0, itemNameEnd);
	itemName = itemName.trim();
	
	//Remove items that don't have Infoboxes on the wiki
	noInfobox.forEach(function(infoboxName) {
	if (itemName == infoboxName) {
		console.log("Removed " + itemName + " from output.");
		itemName = "";
	}
	})
	if (itemName.length == 0) {
		return;
	}
	var consumers = getInputPara(item, "\\|consumers = ", 13, "consumers", itemName);
	var stackSize = getInputPara(item, "\\|stack-size = ", 14, "stack-size", itemName);
	var reqTech = getInputPara(item, "\\|required-technologies = ", 25, "required-technologies", itemName);
	

	consumers = consumers.trim();
	stackSize = stackSize.trim();
	reqTech = reqTech.trim();
	
	
	//get page content of the item -> oldContent
	var oldContent = "";
	$.ajax({
		url: 'https://wiki.factorio.com/api.php',
		data: {
			format: 'json',
			action: 'query',
			titles: itemName + '/infobox',
			prop: 'revisions',
			rvprop: 'content'
		},
		async: false,
		dataType: 'json',
		type: 'GET',
		success: function( data ) {
			var pages = data.query.pages;
			var revisions = pages[Object.keys(pages)[0]].revisions[0];
			oldContent = revisions[Object.keys(revisions)[2]];
			var title = pages[Object.keys(pages)[0]].title;
		},
		error: function( xhr ) {
			alert( 'Error: Request failed.' );
			oldContent = "";
		}
	});
	if (oldContent.length = 0) {
		console.log("No " + itemName + " page found.");
		return;
	}
	
	//find recipes in page (oldContent)
	var pageConsumersStart = oldContent.search(/(\s|\|)consumers/) + 10;
	var pageConsumers = getOldPara(oldContent, pageConsumersStart, 10, "consumers", itemName);
	
	var pageStackSizeStart = oldContent.search(/(\s|\|)stack-size/) + 11;
	var pageStackSize = getOldPara(oldContent, pageStackSizeStart, 11, "stack-size", itemName);
	
	var pageReqTechStart = oldContent.search(/(\s|\|)required-technologies/) + 22;
	var pageReqTech = getOldPara(oldContent, pageReqTechStart, 22, "required-technologies", itemName);
	
	
	pageConsumers = pageConsumers.trim();
	pageStackSize = pageStackSize.trim();
	pageReqTech = pageReqTech.trim();	
	
	
	summary = "";
	newContent = "";
	if ((pageConsumers == consumers) && (pageStackSize == stackSize) && (pageReqTech == reqTech)) {
		console.log(itemName + " page was not changed.")
	} else {
		if (pageConsumers != consumers) {
			newContent = oldContent;
			var newPageConsumersStart = newContent.search(/(\s|\|)consumers/) + 10;
			updatePara(newContent, consumers, pageConsumers, "consumers", newPageConsumersStart, 10, itemName);
		}
		if (pageStackSize != stackSize) {
			if (newContent.length == 0) {
				newContent = oldContent;
			}
			var newPageStackSizeStart = newContent.search(/(\s|\|)stack-size/) + 11;
			updatePara(newContent, stackSize, pageStackSize, "stack-size", newPageStackSizeStart, 11, itemName);
		}
		if (pageReqTech != reqTech) {
			if (newContent.length == 0) {
				newContent = oldContent;
			}
			var newPageReqTechStart = newContent.search(/(\s|\|)required-technologies/) + 22;
			updatePara(newContent, reqTech, pageReqTech, "required-technologies", newPageReqTechStart, 22, itemName);
		}
	}
	
	//alright, newContent should be defined, change page:
	if (newContent.length > 0) {
		editPage(itemName + "/infobox", itemName);
	}
}

$("#TechUpdate").click(function(){
    getTechnologies();
});

function getTechnologies() {
	getUserGroup();
		if (userGroup.some(isBot) == false) {
		return;
	}
	var techInput = prompt("Please enter the technologies");
	if (techInput != null) {
		getToken();
		var techs = techInput.split(/\s\s/g);
		console.log(techs.length + " techs detected");
		techs.forEach(updateTechnologyInfobox);
	}
}

function updateTechnologyInfobox(tech) {
	var techNameEnd = tech.search("\\|");
	var techName = tech.slice(0, techNameEnd);
	techName = techName.trim();
	
	
	var cost = getInputPara(tech, "\\|cost = ", 8, "cost", techName);
	var costMulti = getInputPara(tech, "\\|cost-multiplier = ", 19, "cost-multiplier", techName);
	var expCostMulti = getInputPara(tech, "\\|expensive-cost-multiplier = ", 29, "expensive-cost-multiplier", techName);
	var reqTech = getInputPara(tech, "\\|required-technologies = ", 25, "required-technologies", techName);
	var allows = getInputPara(tech, "\\|allows = ", 10, "allows", techName);
	var effects = getInputPara(tech, "\\|effects = ", 11, "effects", techName);

	
	cost = cost.trim();
	costMulti = costMulti.trim();
	expCostMulti = expCostMulti.trim();
	reqTech = reqTech.trim();
	allows = allows.trim();
	effects = effects.trim();
	
	
	//get page content of the tech -> oldContent
	var oldContent = "";
	$.ajax({
		url: 'https://wiki.factorio.com/api.php',
		data: {
			format: 'json',
			action: 'query',
			titles: techName + ' (research)/infobox',
			prop: 'revisions',
			rvprop: 'content'
		},
		async: false,
		dataType: 'json',
		type: 'GET',
		success: function( data ) {
			var pages = data.query.pages;
			var revisions = pages[Object.keys(pages)[0]].revisions[0];
			oldContent = revisions[Object.keys(revisions)[2]];
			var title = pages[Object.keys(pages)[0]].title;
		},
		error: function( xhr ) {
			alert( 'Error: Request failed.' );
			oldContent = "";
		}
	});
	if (oldContent.length = 0) {
		console.log("No " + techName + " page found.");
		return;
	}
	
	
	//find costs etc in page (oldContent)
	var pageCostStart = oldContent.search(/(\s|\|)cost(\s|=)/) + 6;
	var pageCost = getOldPara(oldContent, pageCostStart, 6, "cost", techName);
	
	var pageCostMultiStart = oldContent.search(/(\s|\|)cost-multiplier/) + 16;
	var pageCostMulti = getOldPara(oldContent, pageCostMultiStart, 16, "cost-multiplier", techName);
	
	var pageExpCostMultiStart = oldContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
	var pageExpCostMulti = getOldPara(oldContent, pageExpCostMultiStart, 26, "expensive-cost-multiplier", techName);
	
	var pageReqTechStart = oldContent.search(/(\s|\|)required-technologies/) + 22;
	var pageReqTech = getOldPara(oldContent, pageReqTechStart, 22, "required-technologies", techName);
	
	var pageAllowsStart = oldContent.search(/(\s|\|)allows/) + 7;
	var pageAllows = getOldPara(oldContent, pageAllowsStart, 7, "allows", techName);
	
	var pageEffectsStart = oldContent.search(/(\s|\|)effects/) + 8;
	var pageEffects = getOldPara(oldContent, pageEffectsStart, 8, "effects", techName);

	
	pageCost = pageCost.trim();
	pageCostMulti = pageCostMulti.trim();
	pageExpCostMulti = pageExpCostMulti.trim();
	pageReqTech = pageReqTech.trim();
	pageAllows = pageAllows.trim();
	pageEffects = pageEffects.trim();
	
	
	summary = "";
	newContent = "";
	
	//change page if anything is different (this INCLUDES different formatting)
	if ((pageCost == cost) && (pageCostMulti == costMulti) && (pageExpCostMulti == expCostMulti) && (pageReqTech == reqTech) && (pageAllows == allows) && (pageEffects == effects)) {
		console.log(techName + " page was not changed.")
	} else {
		if (pageCost != cost) {
			newContent = oldContent;
			var newPageCostStart = newContent.search(/(\s|\|)cost(\s|=)/) + 6;
			updatePara(newContent, cost, pageCost, "cost", newPageCostStart, 6, techName);
		}
		if (pageCostMulti != costMulti) {
			if (newContent.length == 0) {
				newContent = oldContent;
			}
			var newPageCostMultiStart = newContent.search(/(\s|\|)cost-multiplier/) + 16;
			updatePara(newContent, costMulti, pageCostMulti, "cost-multiplier", newPageCostMultiStart, 16, techName);
		}
		if (pageExpCostMulti != expCostMulti) {
			if (newContent.length == 0) {
				newContent = oldContent;
			}
			var newPageExpCostMultiStart = newContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
			updatePara(newContent, expCostMulti, pageExpCostMulti, "expensive-cost-multiplier", newPageExpCostMultiStart, 26, techName);
		}
		if (pageReqTech != reqTech) {
			if (newContent.length == 0) {
				newContent = oldContent;
			}
			var newPageReqTechStart = newContent.search(/(\s|\|)required-technologies/) + 22;
			updatePara(newContent, reqTech, pageReqTech, "required-technologies", newPageReqTechStart, 22, techName);
		}
		if (pageAllows != allows) {
			if (newContent.length == 0) {
				newContent = oldContent;
			}
			var newPageAllowsStart = newContent.search(/(\s|\|)allows/) + 7;
			updatePara(newContent, allows, pageAllows, "allows", newPageAllowsStart, 7, techName);
		}
		if (pageEffects != effects) {
			if (newContent.length == 0) {
				newContent = oldContent;
			}
			var newPageEffectsStart = newContent.search(/(\s|\|)effects/) + 8;
			updatePara(newContent, effects, pageEffects, "effects", newPageEffectsStart, 8, techName);
		}	
	}
	//alright, newContent should be defined, change page:
	if (newContent.length > 0) {
		editPage(techName + " (research)/infobox", techName);
	}	
}

$("#AllUpdate").click(function(){
    getAll();
});

function getAll() {
	getUserGroup();
		if (userGroup.some(isBot) == false) {
		return;
	}
	getToken();
	version = prompt("Please enter the new version.");
	version = version.trim();
	var recipeInput = prompt("Please enter the recipes.");
	var itemInput = prompt("Please enter the consumers, stack-sizes and required-technologies.");
	var techInput = prompt("Please enter the technologies.");
	
	if (recipeInput != null) {
		var recipeArray = recipeInput.split(/\s\s/g);
		console.log(recipeArray.length + " recipes detected");
		recipeArray.forEach(removeDuplicateRecipesAndUpdateInfobox);
	}
	if (itemInput != null) {
		var items = itemInput.split(/\s\s/g);
		console.log(items.length + " items detected");
		items.forEach(updateItemInfoboxes);
	}
	if (techInput != null) {
		var techs = techInput.split(/\s\s/g);
		console.log(techs.length + " techs detected");
		techs.forEach(updateTechnologyInfobox);
	}
}


/* User is bot if UserGroup.some(isBot) == true */

var UserGroup = "";

function getUserGroup() {
	$.ajax({
		url: 'https://wiki.factorio.com/api.php',
		data: {
			format: 'json',
			action: 'query',
			meta: 'userinfo',
			uiprop: 'groups',
		},
		async: false,
		dataType: 'json',
		type: 'GET',
		success: function(data) {
			UserGroup = data.query.userinfo.groups
		},
	});
};

function isBot(group) {
	return group == "bot";
}

var globalToken;

function getToken() {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            meta: 'tokens',
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           globalToken = data.query.tokens.csrftoken;
        },
        error: function( xhr ) {
            console.log("Failed to perform null edit");
        }
    });
}

/*** Language template ***/
if($(".languages-flags .flag").length == 0) {
 console.log("Not showing languages bar because there's no other language's version of this page.");
 $(".languages-container").hide();
}

//Spoiler template JavaScript
$(".spoiler-container .button").click(function() {
  $(this).siblings(".text").toggle("slow");
});

var wantedPagesListsLocation = "User:TheWombatGuru/WantedPages"
$("#create-wanted-pages-list").click(function(){
    getToken();
    createWantedPagesLists();
});

function createWantedPagesLists() {
    getUserGroup();
    if (UserGroup.some(isBot) == false) {
       return;
    }
    var wantedPages = getWantedPages();
    wantedPages = wantedPages.sort(compare);
    splitWantedPagesIntoDifferentLanguages(wantedPages);
};

function splitWantedPagesIntoDifferentLanguages(wantedPages) {
  var czechWantedPages = []; 
  var germanWantedPages = [];
  var spanishWantedPages = [];
  var frenchWantedPages = [];
  var italianWantedPages = [];
  var japaneseWantedPages = [];
  var dutchWantedPages = [];
  var polishWantedPages = [];
  var portugueseWantedPages = [];
  var russianWantedPages = [];
  var swedishWantedPages = [];
  var ukrainianWantedPages = [];
  var chineseWantedPages = [];
  var turkishWantedPages = [];
  var wantedFiles = [];
  var wantedTemplates = [];
  var otherWantedPages = [];

  for (var i = 0; i < wantedPages.length; i++) {
    switch (wantedPages[i].title.slice(-3)) {//"/cs", "/de", "/es", "/fr", "/it", "/ja", "/nl", "/pl", "/-br", "/ru", "/sv", "/uk", "/zh", "/tr"
      case "/cs": czechWantedPages.push(wantedPages[i]); break;
      case "/de": germanWantedPages.push(wantedPages[i]); break;
      case "/es": spanishWantedPages.push(wantedPages[i]); break;
      case "/fr": frenchWantedPages.push(wantedPages[i]); break;
      case "/it": italianWantedPages.push(wantedPages[i]); break;
      case "/ja": japaneseWantedPages.push(wantedPages[i]); break;
      case "/nl": dutchWantedPages.push(wantedPages[i]); break;
      case "/pl": polishWantedPages.push(wantedPages[i]); break;
      case "-br": portugueseWantedPages.push(wantedPages[i]); break;
      case "/ru": russianWantedPages.push(wantedPages[i]); break;
      case "/sv": swedishWantedPages.push(wantedPages[i]); break;
      case "/uk": ukrainianWantedPages.push(wantedPages[i]); break;
      case "/zh": chineseWantedPages.push(wantedPages[i]); break;
      case "/tr": turkishWantedPages.push(wantedPages[i]); break;
      default: if (wantedPages[i].title.slice(0, 5) == "File:") {wantedFiles.push(wantedPages[i])} else if (wantedPages[i].title.slice(0, 9) == "Template:") {wantedTemplates.push(wantedPages[i])} else {otherWantedPages.push(wantedPages[i])}; break;
    }
  }

  createWantedPagesPage("cs", czechWantedPages, "Czech");
  createWantedPagesPage("de", germanWantedPages, "German");
  createWantedPagesPage("es", spanishWantedPages, "Spanish");
  createWantedPagesPage("fr", frenchWantedPages, "French");
  createWantedPagesPage("it", italianWantedPages, "Italian");
  createWantedPagesPage("ja", japaneseWantedPages, "Japanese");
  createWantedPagesPage("nl", dutchWantedPages, "Dutch");
  createWantedPagesPage("pl", polishWantedPages, "Polish");
  createWantedPagesPage("pt-br", portugueseWantedPages, "Portuguese");
  createWantedPagesPage("ru", russianWantedPages, "Russian");
  createWantedPagesPage("sv", swedishWantedPages, "Swedish");
  createWantedPagesPage("uk", ukrainianWantedPages, "Ukrainian");
  createWantedPagesPage("zh", chineseWantedPages, "Chinese");
  createWantedPagesPage("tr", turkishWantedPages, "Turkish");

  createWantedPagesPage("file", wantedFiles, "Files");
  createWantedPagesPage("template", wantedTemplates, "Templates");
  createWantedPagesPage("other", otherWantedPages, "Other");
}

function createWantedPagesPage(location, wantedPages, language) {
  var formattedWantedPages = "Number of wanted pages in " + language + ": " + wantedPages.length + "\n{|class=wikitable\n!#\n!Page\n!Links to this page";

  for (var i = 0; i < wantedPages.length; i++) {
    formattedWantedPages = formattedWantedPages.concat("\n|-\n|" + (i + 1) + "\n|[https://wiki.factorio.com/index.php?title=" + encodeURI(wantedPages[i].title) + " " + wantedPages[i].title + "]\n|[https://wiki.factorio.com/index.php?title=Special:WhatLinksHere/" + encodeURI(wantedPages[i].title) + " " + wantedPages[i].value + "]");
  }

  formattedWantedPages = formattedWantedPages.concat("\n|}");

  createPage(wantedPagesListsLocation + "/" + location, formattedWantedPages, "(BOT) - Update the list of wanted pages for " + language + ".");
}

function performNullEdit(pageTitle, summary) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            section: 0,
            text: "",
            token: globalToken,
            summary: summary,
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           console.log("Performed null edit");
        },
        error: function( xhr ) {
            console.log("Failed to perform null edit");
        }
    });
}

function purgeWhatLinksHere(pageTitle) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: "json",
            action: 'query',
            list: "backlinks",
            bltitle: pageTitle,
            bllimit: 500
        },
        async: true,
        type: 'GET',
        success: function( data ) {
            console.log(data);
            for (var i = 0; i < data.query.backlinks.length; i++) {
                purgePage(data.query.backlinks[i].title);
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
            console.log("Failed purging");
        }
    });
}

function purgePage(pageTitle) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            action: 'purge',
            forcelinkupdate: true,
            titles: pageTitle,
            prop: "info"
        },
        async: true,
        type: 'GET',
        success: function( data ) {
            console.log("purging " + pageTitle);
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
            console.log("Failed purging");
        }
    });
}

function compare(a,b) {
  if (parseInt(a.value) > parseInt(b.value))
    return -1;
  if (parseInt(a.value) < parseInt(b.value))
    return 1;
  if (a.title < b.title)
    return -1;
  if (a.title > b.title)
    return 1;
  return 0;
}

function createPage(pageTitle, content, summary) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            token: globalToken,
            summary: summary,
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           console.log("created page");
        },
        error: function( xhr ) {
            console.log("failed to create page");
        }
    });
}

function getWantedPages() {
   var wantedPages = [];

   $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'querypage',
            qppage: 'Wantedpages',
            qplimit: '5000',
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var results = data.query.querypage.results;
            for (var i = 0; i < results.length; i++) {
               var pageObject = new WantedPage(results[i].title, results[i].value);
               var alreadyInArray = false;
               for (var j = 0; j < wantedPages.length; j++) {
                 if (wantedPages[j].title == pageObject.title) {
                    alreadyInArray = true;
                 }
               }
               if (!alreadyInArray) {
                 wantedPages.push(pageObject);
               }
               if (pageObject.title == "Rocket defense/it") {
               }
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
  });

$.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'querypage',
            qppage: 'Wantedpages',
            qplimit: '5000',
            qpoffset: '3000',
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var results = data.query.querypage.results;
            for (var i = 0; i < results.length; i++) {
               var pageObject = new WantedPage(results[i].title, results[i].value);
               var alreadyInArray = false;
               for (var j = 0; j < wantedPages.length; j++) {
                 if (wantedPages[j].title == pageObject.title) {
                    alreadyInArray = true;
                 }
               }
               if (!alreadyInArray) {
                 wantedPages.push(pageObject);
               }
               if (pageObject.title == "Rocket defense/it") {
               }
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
  });
  return wantedPages;
};

function WantedPage(pageTitle, pageValue) {
   this.title = pageTitle;
   this.value = pageValue;
}


/* OLD INFOBOX CONVERSION TOOLS */
/*function targetAllPagesInCategory(category) {
    var languageSuffixes = ["/fr", "/ru", "/de"]; //, "/cs", "/de", "/es", "/fr", "/it", "/nl", "/pl", "/pt-br", "/ru", "/sv", "/uk", "/zh", ""];
    for (var j = 0; j < languageSuffixes.length; j++) {
      $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'categorymembers',
            cmtitle: (category + languageSuffixes[j]),
            cmlimit: 500
        },
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var pages = data.query.categorymembers;
            for (var i = 0; i < pages.length; i++) {
                    //purgePage(pages[i].title);
                    extractPageInfo(pages[i].title, "9c28a1344a20bf189fda7d58339e518257f2dd9b+\\");
                
            }

            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info + 'Category' );
            } else {
                //alert( 'Error: Unknown result from API. Category' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
    });
  }
}

function extractPageInfo(pageTitle, token) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            titles: pageTitle,
            prop: 'revisions',
            rvprop: 'content'
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var pages = data.query.pages;
            var revisions = pages[Object.keys(pages)[0]].revisions[0];
            var content = revisions[Object.keys(revisions)[2]]
            var title = pages[Object.keys(pages)[0]].title;
            createNewInfoboxPage(title, content, token);
            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    });
}

function createNewInfoboxPage(page, contentOfMainPage, token) {
    var infoboxText = getInfoboxFromFullPageContent(contentOfMainPage);

    var infoboxPageTitle = page.replace(/\/(de|fr|nl|it|es|ru|pt\-br|cs|pl|sv|uk|zh)/g, function(piece) {return "";}).concat("/infobox");
    var oldPageRevisedText = getOldPageRevisedText(page, contentOfMainPage, infoboxPageTitle);	
    removeInfoboxFromMain(page, oldPageRevisedText, token);

    if (infoboxText != null) {
      if (/\/(de|fr|nl|it|es|ru|pt\-br|cs|pl|sv|uk|zh)/g.test(page)) {
        return;
      }
      var newPageTitle = page.concat("/infobox");
      var convertedInfoboxText = convertInfobox(infoboxText, token);
      createPage(newPageTitle, convertedInfoboxText, token, page, contentOfMainPage);
    }
}

function getOldPageRevisedText(pageTitle, content, infoboxPageTitle) {
    content = content.replace(/{{\bCombat\b(\s+(\||{).+)+\s}}/gi, function (piece) {
        return "{{:" + infoboxPageTitle + "}}";
    });
    return content;
}

function removeInfoboxFromMain(pageTitle, content, token) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            bot: true,
            token: token,
            summary: "(BOT) - Replaced old infobox with a link to the /infobox subpage"
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
            if ( data && data.edit && data.edit.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    })
};

function getInfoboxFromFullPageContent(contentOfPage) {
    var matches = contentOfPage.match(/{{\bCombat\b(\s+\|.+)+\s}}/gi);
if (matches != null && matches.length > 0) {
 infoboxText = matches[0];
} else {
 infoboxText = null;
}
    return infoboxText;
}

function convertInfobox(text) {
    text = text.replace(/{{(\w+)/g, function (piece, $1) {
        var returnText = "{{Infobox\n| category = ";

        $1 = $1.toLowerCase();

        switch ($1) {
            case "item":
                returnText = returnText.concat("Items");
                break;
            case "machinery":
                returnText = returnText.concat("Machinery");
                break;
            case "combat":
                returnText = returnText.concat("Combat");
                break;
            case "technology":
                returnText = returnText.concat("Technology");
        }

        switch ($1) {
            case "machinery":
                returnText = returnText.concat("\n| category-name = Machine");
                break;
            case "item":
                returnText = returnText.concat("\n| category-name = Item");
                break;
        }

        return returnText;
    });

    text = text.replace("stack_size", "stack-size");
    text = text.replace("poweroutput", "power-output");
    text = text.replace("input", "recipe");
    text = text.replace("raw", "total-raw");
    text = text.replace("technologies", "required-technologies");
    text = text.replace("costmultiplier", "cost-multiplier");
    text = text.replace("requirements", "required-technologies");
    text = text.replace("walkingspeed", "walking-speed");
    text = text.replace("storagesize", "storage-size");
    text = text.replace("gridsize", "grid-size");
    text = text.replace("shootingspeed", "shooting-speed");
    text = text.replace("damagebonus", "damage-bonus");
    text = text.replace("clustersize", "cluster-size");
    text = text.replace("aoesize", "area-of-effect-size");
    text = text.replace("magazinesize", "magazine-size");
    text = text.replace("recharge", "robot-recharge-rate");
    text = text.replace("rechargebuffer", "internal-buffer-recharge-rate");
    text = text.replace("wirereach", "wire-reach");
    text = text.replace("craftingspeed", "crafting-speed");
    text = text.replace("smeltingspeed", "smelting-speed");
    text = text.replace("miningpower", "mining-power");
    text = text.replace("miningspeed", "mining-speed");
    text = text.replace("miningarea", "mining-area");
    text = text.replace("supplyarea", "supply-area");
    text = text.replace("constructionarea", "construction-area");
    text = text.replace("lifetime", "lifespan");
    text = text.replace("inventorysizebonus", "inventory-size-bonus");
    text = text.replace("gridsize", "grid-size");
    text = text.replace("boosttechs", "boosting-technologies");
    text = text.replace("allowstech", "allows");
    text = text.replace("storage", "storage-size");
    text = text.replace(/\|\s*\brecipe\b\s*=\s*(.+)\n\|\s*\boutput\b\s*=\s*(.+)/g, function (piece, $1, $2) {
        return "| recipe = " + $1 + " = " + $2;
    });

    text = text.concat("<noinclude>[[Category:Infobox page]]</noinclude>");

    return text;
}

function createPage(pageTitle, content, token, page, contentOfMainPage) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            bot: true,
            createonly: true,
            token: token,
            summary: "(BOT) - Created infobox sub page for " + page
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           
            if ( data && data.edit && data.edit.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    });
}*/
/* END OF OLD INFOBOX CONVERSION TOOL */