CPLangScript.js

// 
/*
how to run:
	get all the categorymembers of a certain clothing category, or, directly insert extra page names to Langs.pages
		Langs.get.categoryMembers("Neck Items")
//		Langs.get.pageContent("Parrot") <-- 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. contains the section already:
	1. has the {{Disambig}} template
	3. has no iteminfobox template
	4. doesn't have the following sections (checks by teh following order), and either is not about a real item or requires further clean up:
	 4.1. gallery
	 4.2. trivia
	 4.3. appearances
	 4.4. history
*/
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]*\d+[\}\| \n,]/) > -1 && Langs.content[page].search(/(\n== *[nN]ames in [oO]ther [lL]anguages *==\n|\{\{[dD]isambig(uation){0,1}\}\})/) == -1 && Langs.content[page].search(/\{\{[iI]temInfo[bB]ox[\|\n ]/) > -1) {
		var id = content.split(/\| *id *=[^\d]*/)[1].split(/[\n \|\},]/)[0],
			sectionToAppend = content.search(/\n\=\= *[gG]allery *\=\=/) > -1 ? "[gG]allery" : content.search(/\n\=\= *[tT]rivia *\=\=/) > -1 ? "[tT]rivia" : content.search(/\n\=\= *[aA]ppearance *\=\=/) > -1 ? "[aA]ppearance" : content.search(/\n\=\= *[hH]istory *\=\=/) > -1 ? "[hH]istory" : undefined,
			newContent = content.replace(new RegExp("\\n== *" + sectionToAppend + " *== *(\\n[^\n]*)*\\n==[^=]+==*"), function(a) {
				var b = a.split("\n");
				b[b.length-1] = "==Names in Other Languages==\n" + Langs.get.itemName(id) + "\n" + b[b.length-1];
				return b.join("\n");
			});
		Langs.done[page] = newContent;
		if (typeof sectionToAppend !== "undefined") {
			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);
}
Langs.exe = function() {
	var langs = ["en", "pt", "fr", "es", "de", "ru"],
		_langs = langs.concat();
	function makeLang() {
		this.file = "paper_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].paper_items;
			for (var j in data) {
				var id = data[j].paper_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
//