CPLangScript.js/furn

// 
/*
how to run:
	get all the categorymembers of a certain furniture category, or, directly insert extra page names to Langs.pages
		Langs.get.categoryMembers("Room Furniture")
//		Langs.get.pageContent("Fern") <-- an optional way of running on a sigle page
	set delay and/or limit to number of pages if needed, via the Langs object
	when ready, do:
	Langs.exe();
errors:
the script won't add the section to a page in the following scenarios:
	1. modify Langs.parse.content
	2. modify Langs.parse.content
*/
Langs = {
	"pages": [],
	"content": {},
	"done": {},
	"parse": {},
	"items": {},
	"get": {},
	"summary": "Adding names in other languages",
	"delay": 3000
}
Langs.get.categoryMembers = function(cat, cont) {
	$.getJSON("/api.php?action=query&format=json&list=categorymembers&cmtitle=Category:" + encodeURIComponent(cat) + "&cmnamespace=0&cmlimit=500&cb=" + new Date().getTime() + (typeof cont !== "undefined" ? "&cmcontinue=" + cont : ""), function(data) {
		var a = data.query.categorymembers;
		for (var i = 0; i < a.length; i++) {
		Langs.pages.push(data.query.categorymembers[i].title);
			if (i + 1 == a.length) {
				if (typeof data["query-continue"] === "object") {
					return Langs.get.categoryMembers(cat, data["query-continue"].categorymembers.cmcontinue);
				} else {
					console.log("Done!");
				}
			}
		}
	});
}
Langs.get.pageContent = function(page) {
	$.getJSON("/api.php?action=query&format=json&prop=revisions&titles=" + encodeURIComponent(page) + "&rvprop=content&cb=" + new Date().getTime(), function(data) {
		var a = data.query.pages;
		for (var pageid in a) {
//			console.log(a[pageid].revisions[0]["*"]);
			Langs.content[page] = a[pageid].revisions[0]["*"];
			Langs.parse.content(page);
		}
	});
}
Langs.get.itemName = function(id) {
	var lang = ["pt", "fr", "es", "de", "ru"],
		output = [];
	function foo(langName, id) {
		return Langs.items[id][langName];
	}
	for (var i = 0; i < lang.length; i++) {
		output.push(
			"|" + lang[i] + "= " + foo(lang[i], id)
		);
		if (i + 1 == lang.length) {
			return "{{Language\n" + output.join("\n") + "\n}}\n";
		}
	}
}
Langs.parse.content = function(page) {
	var content = Langs.content[page];
	if (
			Langs.content[page].search(/\| *id *=[^\d\n]*\d+[\}\| \n,]/) > -1 && // has id
			Langs.content[page].search(/(\n\=\= *[nN]ames in [oO]ther [lL]anguages *\=\=\n|\{\{[dD]isambig(:?uation)?\}\})/) == -1 && // not disambig and doesn't already have lang template
			Langs.content[page].search(/\{\{[fF]urnitureInfobox[\|\n ]/) > -1 // has infobox
		) {
		var content = Langs.content[page],
			newContent = String(content);
			id = content.split(/\| *id *=[^\d]*/)[1].split(/[\n \|\},]/)[0],
			sections = content.match(/^\={2}(?:[^\=]+| +\S+ +)\={2} *$/gmi).join("\n"),
			sectionToAppend = (
				content.search(/\n\=\= *[gG]allery *\=\=/) > -1 ? "[gG]allery" :
				content.search(/\n\=\= *[tT]rivia *\=\=/) > -1 ? "[tT]rivia" :
				content.search(/\n\=\= *[aA]rrow [kK]ey [cC]hanges *\=\=/) > -1 ? "[aA]rrow [kK]ey [cC]hanges" :
				content.search(/\n\=\= *[aA]ppearance *\=\=/) > -1 ? "[aA]ppearance" :
				content.search(/\n\=\= *[hH]istory *\=\=/) > -1 ? "[hH]istory" :
				content.search(/\n\=\= *[sS]ee [aA]lso *\=\=/) > -1 ? "seealso" : undefined
			);
		if (typeof sectionToAppend !== "undefined") {
			if (sectionToAppend == "seealso") {
				// prepend rather than append
				var newContent = content.replace(/\n\=\= *[sS]ee [aA]lso *\=\=\n/, "\n==Names in Other Languages==\n" + Langs.get.itemName(id) + "\n\n==See also==\n");
			} else {
				// normal
				var splitted = sections.split(new RegExp("\\={2} *" + sectionToAppend + " *\\={2} *", "m")); // see if there are other sections
				if (splitted[1] == "") {
					// no more sections
					var newContent = content.replace(/\={2} *[gG]allery *\={2} *(:?\n(?!\{).*)+/, "$&\n==Names in Other Languages==\n" + Langs.get.itemName(id));
				} else {
					// at least one more section afterwards
					var nextSection = splitted[1].match(/\={2}.+\={2}/)[0],
						newContent = content.replace(splitted[1].match(/\={2}.+\={2}/)[0], "==Names in Other Languages==\n" + Langs.get.itemName(id) + "\n" +splitted[1].match(/\={2}.+\={2}/)[0]);
				}
/*
					content.replace(
					new RegExp(
							"\\n== *" + sectionToAppend + " *== *" + // section to append lang template to
							"(\\n.*)*\\n(?:\\={2}(?: +[^\\n\\= ]+ +|[^\\n\\=]+)+\\=\\=|\\{|$)"
					), function(m) {
						var a = m.split("\n");
						if (a[m.length - 1] == "{") {
							a[m.length - 1] = "\n\n==Names in Other Languages==" + Langs.get.itemName(id) + "{";
							return a.join("\n");
						} else {
							a[a.length - 2] += "\n\n==Names in Other Languages==" + Langs.get.itemName(id);
							return a.join("\n");
						}
					});*/
			}
		}
		if (newContent != content) {
			// changes made
			Langs.done[page] = newContent.replace(/\n{3,}/g, "\n\n");
			Langs.save(page, Langs.done[page]);
		}
	} else {
		Langs.error.push(page);
		console.log("Error - problematic page - may need manual editing and checking its content first.");
		
	}
}
Langs.save = function(page, content) {/*
	$.ajax({
		url: "/api.php?action=edit&format=json&title=" + encodeURIComponent(page) + "&text=" + encodeURIComponent(content) + (typeof Langs.summary === "string" ? "&summary=" + Langs.summary : "") + "&bot&minor&token=" + encodeURIComponent(mw.user.tokens.values.editToken),
		dataType: 'json',
		type: 'POST',
		success: function( data ) {
			if ( data && data.edit && data.edit.result == 'Success' ) {
				console.log("Success: " + page); // edit was successful
			} else if ( data && data.error ) {
				console.log( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
			} else {
				console.log( 'Error: Unknown result from API.' );
			}
		},
		error: function( xhr ) {
			console.log( 'Error: Request failed.' );
		}
	});//*/ console.log("Pseudo save for " + page + "\n\n\n" + content);
}
Langs.exe = function() {
	var langs = ["en", "pt", "fr", "es", "de", "ru"],
		_langs = langs.concat();
	function makeLang() {
		this.file = "furniture_items";
		this.lang = langs.shift();
	}
	function exe() {
		var i = 0;
		var count = setInterval(function() {
			if (Langs.pages.hasOwnProperty(i)) {
				Langs.get.pageContent(Langs.pages[i]);
			}
			if (i + 1 == Langs.pages.length) {
				clearInterval(count);
			}
			i++;
		}, (isNaN(Langs.delay) ? 3000 : Langs.delay));
	}
	$cp.json.multi([
		new makeLang,
		new makeLang,
		new makeLang,
		new makeLang,
		new makeLang,
		new makeLang
	], function() {
		for (var i in _langs) {
			var lang = _langs[i],
				data = $cp.json.val[lang].furniture_items;
			for (var j in data) {
				var id = data[j].furniture_item_id;
				if (typeof Langs.items[id] === "undefined") {
					Langs.items[id] = {};
				}
				Langs.items[id][lang] = data[j].prompt.length > 0 ? data[j].prompt : data[j].label;
			}
		}
		// done loading and processing the json data
		exe();
	});
}
Langs.error = []; // object for problematic pages - non-articles or pages that may need manual work and further expansion
//