Utente:Alebot/getPageNew.js

Da Wikisource.

Nota: dopo aver pubblicato, potrebbe essere necessario pulire la cache del proprio browser per vedere i cambiamenti.

  • Firefox / Safari: tieni premuto il tasto delle maiuscole Shift e fai clic su Ricarica, oppure premi Ctrl-F5 o Ctrl-R (⌘-R su Mac)
  • Google Chrome: premi Ctrl-Shift-R (⌘-Shift-R su un Mac)
  • Internet Explorer / Edge: tieni premuto il tasto Ctrl e fai clic su Aggiorna, oppure premi Ctrl-F5
  • Opera: premi Ctrl-F5.
/* General string functions by Alex */

/* gets the content of main textbox (area parameter can be used to read header and footer textboxes into nsPage) */
function leggiBox(area) {
	if (area == undefined) {
		if (wgCanonicalNamespace == "Pagina") area = 1;
		else area = 0;
	}
	return $('textarea')[area].value;
}

/* puts testo into main textbox (area parameter can be used to write into header and footer textboxes into nsPage;
ss and se are optionally used to manage selection) */
function scriviBox(testo, area, ss, se) {
	if (area == undefined || area == "") {
		if (wgCanonicalNamespace == "Pagina") area = 1;
		else area = 0;
	}
	$('textarea')[area].value = testo;
	if (ss != undefined && se != undefined) {
		$('textarea')[area].selectionStart = ss;
		$('textarea')[area].selectionEnd = se;
	}
}
/* counts occurrences of stringa into testo */
function count(testo, stringa) {
	n = 0;
	while (testo.indexOf(stringa) > -1) {
		n = n + 1;
		testo = testo.replace(stringa, "");
	}
	return n;
}

/* 
Searches into testo a substring beginning with idi and ending with idf (idi and idf are the delimiters).
 
If dc==1 script returns substring and delimiters; if dc==0 it returns substring without delimiters. 
If there's no idi....idf substring, script returns an empty string.

Last optional parameter x is used to solve the case of nested substrings (i.e. nested templates into wiki code). When the shared string into possibly nested sunstrings is passed (as "{{" for wiki templates or "<div" for nested div into html) the script searches for "logically closing delimiter".
 
examples:
find_stringa("abcd[efg]hil","[","]",1) returns [efg]
find_stringa("abcd[efg]hil","[","]",0) returns efg
find_stringa("abcd[e[f]g]hil","[","]",1,"[") returns [e[f]g]

*/
function find_stringa(testo, idi, idf, dc, x) {
	idip = testo.indexOf(idi);
	idfp = testo.indexOf(idf, idip + idi.length) + idf.length;
	if (idip > -1 && idfp > -1) {
		if (x != "") {
			while (count(testo.slice(idip, idfp), x) > count(testo.slice(idip, idfp), idf)) {
				idfp = testo.indexOf(idf, idfp) + idf.length;
			}
		}
		if (dc == 0) {
			vvalore = testo.slice(idip + idi.length, idfp - idf.length);
		} else {
			vvalore = testo.slice(idip, idfp);
		}
	} else {
		vvalore = "";
	}
	return vvalore;
}

// same sintax of find_stringa, but returns the list of idi...idf strings into testo
function produciLista(testo, s1, s2, delim, x) {
	lista = new Array();
	while (find_stringa(testo, s1, s2, true, x) > "") {
		elemento = find_stringa(testo, s1, s2, true, x);
		testo = testo.replace(elemento, "");
		if (delim) {
			lista.push(elemento);
		} else {
			lista.push(elemento.slice(s1.length, - s2.length));
		}
	}
	return lista;
}


/* 
# Launches and interwiki API query revisions and gets a JSON object;
# gets wikitext or "-1" from getText();
# gets a template object from parseTemplate();
# saves the result into div.ourDiv data;
#runs an optional callback function

*/

function getPageNew(title, site, template, callback) {
	if ($(".ourDiv").length == 0) $("body").append($('<div class="ourDiv" style="display:none"></div>'));
	$.ajax({
		url: 'https://' + site + '/w/api.php',
		async: false,
		data: {
			format: 'json',
			action: 'query',
			titles: title,
			prop: 'revisions',
			rvlimit: '1',
			rvprop: 'content'
		},
		dataType: 'jsonp' // this is the important one!
	}).done(function (data) {
		var testo = getText(data);
		if (testo == "-1") {
			$(".ourDiv").data(site + "." + template.toLocaleLowerCase(), "-1");
		} else {
			var templateData = parseTemplate(template, testo).concat(data);
			$(".ourDiv").data(site + "." + template.toLocaleLowerCase(), templateData);
		}
	        callback(site,template);
        }


	);
}

/* 
Gets the result of a API query in JSON format from getPageNew() and returns wikitext if page exists, "-1" if it does not exists
*/
function getText(dato) {
	var l = "";
	for (i in dato.query.pages) {
		l = i;
		break;
	}
	if (l == "-1") return l;
	var testo = dato.query.pages[l].revisions[0]["*"];
	return testo;
}

/* 
Internally used by parseTemplate, to avoid mismatch from | characters
*/
function cod(testo) {
	var l = produciLista(testo, "{"+"{", "}}", 1, "{{");
	for (var i = 0; i < l.length; i += 1) {
		testo = testo.replace(l[i], l[i].replace(/\|/g, "__!__"));
	}
	l = produciLista(testo, "[[", "]]", 1, "[[");
	for (var i = 0; i < l.length; i += 1) {
		testo = testo.replace(l[i], l[i].replace(/\|/g, "__!__"));
	}
	return testo;
}

/* 
Gets a parameter name and a wikitext where the template is contained (default, current page).
It extracts the template code from the text, then it parses it into parameters buildin a resulting js obiect:
# object is a list of two elements, a dictionary and a list;
# dictionary has parameter names (for nominal parameters) or number (for positional ones) as keys; the name of template is into "0" key;
# list contains the parameter keys into the original order, so that rewriteTemplate( can re-build the template code in original order.
*/
function parseTemplate(template, testo) {
	if (testo == undefined) testo = leggiBox();
	var tmplUpper = template.substring(0, 1).toLocaleUpperCase() + template.substring(1);
	var tmplLower = template.substring(0, 1).toLocaleLowerCase() + template.substring(1);
	if (testo.indexOf("{" + "{" + tmplUpper) != -1) {
		template = tmplUpper;
	} else {
		template = tmplLower;
	}
	if (testo.indexOf("{" + "{" + template) == -1) return [{}, []]; // template lacks into testo

	var t = find_stringa(testo, "{" + "{" + template, "}}", 1, "{{");
	var l = []; // keys list is initialized
	var t = "0=" + t.substring(2, t.length - 2) // template is stored under key "0"
	l.push["0"]; // "0" value is stored into list of keys
	var ts = {}; // param dictionary is initialized
	var n = 1;
	t = cod(t); //  | characters are coded if they are not template parameters separators
	t = t.split("|"); // template code is spitted into parameters

	// element for element
	for (i = 0; i < t.length; i += 1) {
		// case param is positional
		if (t[i].indexOf("=") == -1) {
			t[i] = n + "=" + t[i];
			n = n + 1;
		}
		var els = [];
		els[0] = t[i].substring(0, t[i].indexOf("=")).trim();
		els[1] = t[i].substring(t[i].indexOf("=") + 1).trim();
		if (els[1][els[1].length - 1] == "\n") els[1] = els[1].substring(0, els[1].length - 1);

		ts[els[0]] = decod(els[1]);
		l.push(els[0]);
	}

	return [ts, l];
}

/* 
Removes transformed | characters; used by parseTemplate()
*/
function decod(testo) {
	testo = testo.replace(/__!__/g, "|");
	return testo;
}

/* 
Builds a "template object" (not used)
*/
function templateObj(nomeTemplate) {
	data = parseTemplate(nomeTemplate);
	this.keys = data[1];
	this.dict = data[0];
}

/* 
Builds a template code from a parseTemplate() obiect passed as parameter and returns wikicode of template
Works both on nominal and positional template parameters 
*/
function rewriteTemplate(x) {
	var testo = "";
	$.each(x[1], function (indice, valore) {
		if (valore != "0") testo += " | " + valore + " = " + x[0][valore] + "\n";
	});
	testo = "{{" + x[0]["0"] + "\n" + testo + "}}\n";
	testo = testo.replace(/\n\s\|\s\d*\s=\s/g, "\n | ");
	return testo
}

/* opens a show box to look any hmtl code */
function showNew(data) {

	$("#show").remove();
	$('<div id="show"></div>').appendTo($("body"));
	$("#show").attr("style", "white-space:pre-wrap; background-color:#FCFCFC; font-family:Courier; font-size:0.7pc; position:fixed; width:45%; height:70%; top:20px; right:20px; z-index:999; overflow:auto; border:1px solid #bbb;").attr("ondblclick", '$("#show").remove()');

	$('<div style="white-space:pre-wrap; width:100%; height:17px; background-color:#4D8AC0;" id="showCodeBar"></div>\n').appendTo($("#show"));

	$("#showCodeBar").append($('<img src="//upload.wikimedia.org/wikipedia/commons/f/f8/Tooltip-CloseButton.png" onclick="delShow()" style="align:right;cursor:pointer;"/>'));
	$("#show").append($(data));
}

function activeTab(r, nomi) {
	// creazione box
	$('<div ondblclick="saveActiveTab()" style="line-height:1em; background-color:#FCFCFC; font-family:Courier; font-size:0.8pc; position:absolute; width:100%; top:0px; right:0px; z-index:999; border:1px solid #bbb;" id="showCode"></div>').appendTo($("#mw-content-text"));

	// creazione tabella
	$("#showCode").append($('<table class="tabella" border="1" cellspacing="0" cellpadding="2" width="100%" ></table'));

	// aggiunta righe 1-5
	for (var i = 1; i < r[0].length + 1; i += 1) {
		html = '<tr class="riga' + i + '"></tr>';
		$(".tabella").append($(html));
	}

	// aggiunta colonne 1-4
	$("tr", $(".tabella")).each(function () {
		for (var i = 0; i < r.length + 2; i += 1) {
			var classe = $(this).attr("class");
			var html = $('<td class="' + classe + ' ' + 'colonna' + i + '"> </td>');
			if (i == 0) html.attr("width", "15%");
			if (i == 1) html.attr("width", "30%");
			$(this).append(html);
		}
	})

	// caricamento
	for (var i = 0; i < r.length; i += 1) {
		for (var j = 0; j < r[0].length; j += 1) {
			$(".riga" + (j + 1) + " .colonna" + (i + 2)).html(r[i][j]);
		}

	}


	// attivazione

	$(".colonna1").append($("<textarea col='30' row='2' />"));
	$("td:not([class~='colonna0'],[class~='colonna1'])", $(".tabella")).click(function () {
		$(this).siblings("td:not([class~='colonna0'],[class~='colonna1'])").css("background-color", "white");
		$(this).css("background-color", "yellow");
		$("textarea", $(this).parent()).val($(this).text());
	});

	for (i = 1; i < r[0].length + 1; i += 1) {
		$(".riga" + i + " textarea").val($(".riga" + i + " .colonna2").text())
	}
	for (i = 1; i < nomi.length; i += 1) {
		$(".riga" + i + " .colonna0").html(nomi[i])
	}
}


function loadActiveTab(template) {
	if ($(".ourDiv").length == 0) $("body").append($('<div class="ourDiv" style="display:none"></div>'));
	if (template == undefined) {
		scriviBox(leggiBox().replace("{{intestazione", "{{Intestazione").replace("{{includiIntestazione", "{{IncludiIntestazione").replace("{{autore", "{{Autore").replace("{{book", "{{Book").replace("{{creator", "{{Creator"));
		var templName = "";
		if (wgCanonicalNamespace == "" && wgPageName.indexOf("/") == -1) templName = "Intestazione";
		if (wgCanonicalNamespace == "" && wgPageName.indexOf("/") != -1) templName = "IncludiIntestazione";
		if (wgCanonicalNamespace == "Autore") templName = "Autore";
		if (wgCanonicalNamespace == "Creator") templName = "Creator";
		if (wgCanonicalNamespace == "File") templName = "Book";

	} else {
		templName = template;
	}
	var templCode = find_stringa(leggiBox(), "{" + "{" + templName, "}}", 1, "{{");
	var templObj = parseTemplate(templName, templCode);
	var lista = [];
	for (i = 1; i < templObj[1].length; i += 1) {
		lista.push(templObj[0][templObj[1][i]]);
	}
	$(".ourDiv").data("templName", templName);
	$(".ourDiv").data("templCode", templCode);
	$(".ourDiv").data("templObj", templObj);
	activeTab([lista], templObj[1]);

}

function saveActiveTab() {

	for (i = 1; i < $(".ourDiv").data("templObj")[1].length; i += 1) {
		$(".ourDiv").data("templObj")[0][$(".riga" + i + " .colonna0").html()] = $(".riga" + i + " textarea").val();
	}
	$("#showCode").remove();
	scriviBox(leggiBox().replace(find_stringa(leggiBox(), "{" + "{" + $(".ourDiv").data("templName"), "}}", 1, "{{"), rewriteTemplate($(".ourDiv").data("templObj"))));
}

// nuovo getPage()


/* WIP converting parameter (from it:w and en:w homologous infoboxes) names into those of Creator template */
function customToCreator(site, template) {
	if (site == "it" + ".wikipedia.org") var obj = $(".ourDiv").data(site + "." + template.toLocaleLowerCase());
	if (site == "en" + ".wikipedia.org") var obj = $(".ourDiv").data(site + "." + template.toLocaleLowerCase());

	// caso it
	if (site == "it.wikipedia.org") {
		obj[0].Name = obj[0].Nome + " " + obj[0].Cognome;
		obj[0]["Alternative names"] = "";
		obj[0].Nationality = obj[0]["Nazionalità"];
		obj[0].Gender = obj[0].Sesso;
		obj[0].Occupation = obj[0]["Attività"];
		obj[0].Birthdate = obj[0].GiornoMeseNascita + " " + obj[0].AnnoNascita;
		obj[0].Birthloc = obj[0].LuogoNascita;
		obj[0].Deathdate = obj[0].GiornoMeseMorte + " " + obj[0].AnnoMorte;
		obj[0].Deathloc = obj[0].LuogoMorte;
		obj[0].Workperiod = "";
		obj[0].Workloc = "";
		obj[0].Image = obj[0].Immagine;
		obj[0].Sortkey = obj[0].Cognome + ", " + obj[0].Nome;
		obj[0].Option = "{{{1|}}}";
		obj[0].Homecat = "Alex brollo/Tabella attiva.js";
		obj[0].Linkback = "Utente:Alex brollo/Tabella attiva.js";
		obj[0].Autority = "<!-- {{Authority control|VIAF=|LCCN=|ULAN=|PND=|bare=1}} -->";
	}
	// caso en
	if (site == "en.wikipedia.org") {
		obj[0].Name = obj[0].name;
		obj[0]["Alternative names"] = "";
		obj[0].Nationality = obj[0].nationality;
		obj[0].Gender = "";
		obj[0].Occupation = obj[0].occupation;
		obj[0].Birthdate = obj[0].birth_date;
		obj[0].Birthloc = obj[0].birth_place;
		obj[0].Deathdate = obj[0].death_date;
		obj[0].Deathloc = obj[0].death_place;
		obj[0].Workperiod = "";
		obj[0].Workloc = "";
		obj[0].Image = obj[0].image;
		obj[0].Sortkey = "";
		obj[0].Option = "{{{1|}}}";
		obj[0].Homecat = "Alex brollo/Tabella attiva.js";
		obj[0].Linkback = "Utente:Alex brollo/Tabella attiva.js";
		obj[0].Autority = "<!-- {{Authority control|VIAF=|LCCN=|ULAN=|PND=|bare=1}} -->";
	}
	$(".ourDiv").data(site + "." + template.toLocaleLowerCase(), obj);
}
function getHtml(title, site, callback) {
	
	$.ajax({
		url: 'https://' + site + '/w/api.php',
		async: false,
		data: {
			format: 'json',
			action: 'parse',
			page: title,
			prop: 'text'
		},
		dataType: 'jsonp' // this is the important one!
	}).done(function (data) {
		$(".ourDiv").data("indexItWikisource", data);
		callback();

	});

}

function insertHtml() {
	var html = $($(".ourDiv").data("indexItWikisource").parse.text["*"]);
	$("a", html).each(function () {
		var href = "//it.wikisource.org" + $(this).attr("href");
		$(this).attr("href", href)
	});
	html.appendTo(".contenuto");
}