Utente:Alex brollo/Libreria.js: differenze tra le versioni

Da Wikiquote, aforismi e citazioni in libertà.
Contenuto cancellato Contenuto aggiunto
Nessun oggetto della modifica
Riga 183: Riga 183:
async: false
async: false
}).responseText;
}).responseText;
var contenuto = find_stringa(wikitext, '<rev contentformat="text/x-wiki" xml:space="preserve">', "</rev>", 0, '<rev contentformat="text/x-wiki" xml:space="preserve">');
var rev=find_stringa(wikitext,"'<rev contentformat",">",1);
var contenuto = find_stringa(wikitext, rev, "</rev>", 0, '<rev contentformat="text/x-wiki" xml:space="preserve">');
var l = produciLista(contenuto, "{{", "}}", 1, "{{");
var l = produciLista(contenuto, "{{", "}}", 1, "{{");
for (var i = 0; i < l.length; i += 1) {
for (var i = 0; i < l.length; i += 1) {

Versione delle 19:19, 27 lug 2013

mw.loader.load('//commons.wikimedia.org/w/index.php?title=MediaWiki:JSValidator.js&action=raw&ctype=text/javascript');

/* aggiunge un metodo conta all'oggetto String. 
Restistuisce il numero di sottostringhe stringa contenute nella stringa principale. Il confronto è sensibile 
alle maiuscole/minuscole.  */
String.prototype.count = function(stringa) {
	var n = 0;
	var testo = this
	while (testo.indexOf(stringa) > -1) {
		n = n + 1;
		testo = testo.replace(stringa, "");
	}
	return n;
}
/* aggiunge il metodo isOdd a Number */
Number.prototype.isOdd = function() {
	if (this % 1 != 0 || this < 0) {
		return undefined;
	}
	if (this % 2 == 0) {
		return true;
	} else {
		return false;
	}
}
/* conta il numero di occorrenze di stringa dentro testo*/
function count(testo, stringa) {
	n = 0;
	while (testo.indexOf(stringa) > -1) {
		n = n + 1;
		testo = testo.replace(stringa, "");
	}
	return n;
}
/* 
Ricerca nella stringa testo la sottostringa che inizia con idi e termina con idf.  (idi e idf sono stringhe).
 
Se dc ("delimitatori compresi") è 1, restituisce la sottostringa completa di idi e idf; se dc è 0, restituisce la stringa
senza delimitatori; parametro opzionale con default 0.
Per risolvere correttamente il caso di ricerca di tag annidati, come i template, in cui l'identificatore iniziale ha una 
parte non aspecifica, e una parte specifica, può essere passato un quinto parametro, che definisce  la parte aspecifica dell'identificatore iniziale.
 
Esempio: volendo ottenere l'intero contenuto del template {{centrato|{{sc|Testo di prova}}|l=18em}}, il risultato corretto
NON proviene dalla ricerca find_stringa("{{centrato|","}}",1), perchè sarebbe {{centrato|{{sc|Testo di prova}}. 
Impostando invece find_stringa("{{centrato|","}}",1,"{{"), visto che "{{" è la parte aspecifica del primo delimitatore,
si ottiene il risultato corretto, a prescindere dal numero dei template annidati. 
 
Se la sottostringa non viene trovata, la funzione restituisce una stringa vuota "". 
 
*/
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;
}

// delim true: con delimitatori, false: senza delimitatori
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;
}

function leggiBox(area) {
	if (area == undefined) {
		if (wgCanonicalNamespace == "Pagina") area = 1;
		else area = 0;
	}
	return $('textarea')[area].value;
}

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;
	}
}

function selection(area) {
	if (area == undefined) {
		if (wgCanonicalNamespace == "Pagina") area = 1;
		else area = 0;
	}
	txtarea = $('textarea')[area];
	return [$(txtarea).val().substring(0, txtarea.selectionStart),
	$(txtarea).val().substring(txtarea.selectionStart, txtarea.selectionEnd),
	$(txtarea).val().substring(txtarea.selectionEnd)];
}

$("#content").append($('<div id="newtattoo" align="right" style="position:fixed;bottom:0; right:0; background-color:white; border: 1px solid; border-color:#F0F0F0; z-index:1500;"><span>&nbsp;</span></dir>'));

function newButton(nome, funzione) {
	if (wgAction == "history") {
		return;
	}
	if (find_stringa(funzione, "(", ")", 1) == "") {
		funzione += "()";
	}

	if (nome.substring(0, 2) == "//") {
		var html = '<img src="' + nome + '" onclick="' + funzione + '" />';
		$("#newtattoo").append($(html));
	} else {

		$("#newtattoo").append($('<button type="button" onclick="' + funzione + '"><small>' + nome + '</small></button>'));
	}
}

// rimuove il box di visualizzazione
function delShow() {
	$(".showCode").remove();
}

//apre un box fixed in cui visualizzare il wikicode e ci aggiunge una barra e il wikicode
function show(option) {
	if (option == undefined) option = 0;

	var commandBar = '<div style="white-space:pre-wrap; width:100%; height:17px; background-color:#4D8AC0;"><img src="//upload.wikimedia.org/wikipedia/commons/f/f8/Tooltip-CloseButton.png" onclick="delShow()" style="align:right;cursor:pointer;"/></div>\n';
	var box = '<div ondblclick="delShow()" 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;" class="showCode">';
	box += commandBar;
	if (option == 0) {
		var wt = acchiappaWikicode(wgPageName);
		var headerDiv = '<div style="white-space:pre-wrap; width:97%; padding:5px;  background-color:#D9FFFF;">' + wt[0] + '</div>\n';
		var bodyDiv = '<div style="white-space:pre-wrap; width:97%; padding:5px; background-color:#FCFCFC;">' + wt[1] + '</div>\n';
		var footerDiv = '<div style="white-space:pre-wrap; width:97%; padding:5px; background-color:#CCFFFF;">' + wt[2] + ' </div>\n';
		if (wt[0] != "") box += headerDiv;
		box += bodyDiv;
		if (wt[0] != "") box += footerDiv;
	}
	if (option == 1) {
		divData = parseMetadata();
		box += divData[0];
	}
	if (option == 2) {
		// la funzione viene chiamata dentro un callback di getPage e dispone di una variabile lista
		// che contiene un oggetto jQuery lista
		box += $(lista).html();
	}
	box += '</div>';

	$(box).appendTo($("body"));
	mw.loader.using(["jquery.ui.resizable"], function() { //'jquery.ui.draggable', niente draggabilità per ora
		$(".showCode").resizable(); // .draggable() occorre applicare un handle, altrimenti col cavolo che si seleziona...
	});

}

function acchiappaWikicode(pagina, progetto) {
	if (progetto == undefined) {
		progetto = "";
	} else {
		progetto = "//" + progetto;
	}
	var wikitext = $.ajax({
		url: progetto + "/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&titles=" + pagina,
		async: false
	}).responseText;
	var rev=find_stringa(wikitext,"'<rev contentformat",">",1);
	
	var contenuto = find_stringa(wikitext, rev, "</rev>", 0, '<rev contentformat="text/x-wiki" xml:space="preserve">');
	var l = produciLista(contenuto, "{{", "}}", 1, "{{");
	for (var i = 0; i < l.length; i += 1) {
		contenuto = contenuto.replace(l[i], '<span style="color: red;">' + l[i] + '</span>');
	}
	contenuto = contenuto.replace(/\&lt;/g, '<span style="color:blue">&lt;').replace(/\&gt;/g, '&gt;</span>').replace(/\n/g, "<br />");
	if (wgCanonicalNamespace == "Pagina") {
		var noincludeList = produciLista(contenuto, '<span style="color:blue">&lt;noinclude&gt;</span>', '<span style="color:blue">&lt;/noinclude&gt;</span>', 1);
		var header = noincludeList[0];
		var footer = noincludeList[noincludeList.length - 1];
		var body = find_stringa(contenuto, header, footer, 0);
		contenuto = [header, body, footer];
	} else {
		contenuto = ["", contenuto, ""];
	}
	return contenuto;
}

function incapsula(pre, post) {
	t = selection();
	t[0] = t[0] + pre.replace(/&quote;/g, '"');
	t[2] = post.replace(/&quote;/g, '"') + t[2];
	scriviBox(t.join(""));
}

function citazFumagalli() {
	var frase = "citato in [[Giuseppe Fumagalli]], ''[[s:Chi l'ha detto?|Chi l'ha detto?]]'', Hoepli, 1921, p. #pag";
	var t = selection();
	var tt = t[1].split(" ");
	var pag = tt[0];
	var cit = "";
	if (tt.length > 1) cit = tt[1];
	var link = "[[s:Pagina:Chi l'ha detto.djvu/#pagdjvu|#pagcarta]]".replace("#pagcarta", pag).replace("#pagdjvu", pag * 1 + 32);
	if (cit != "") link = "[[s:Pagina:Chi l'ha detto.djvu/#pagdjvu#cit|#pagcarta]]".replace("#pagcarta", pag).replace("#pagdjvu", pag * 1 + 32).replace("#cit", "#c" + cit);
	t[1] = frase.replace("#pag", link);
	scriviBox(t.join(""));
}

function citazFumagalliLink() {
	var frase = "#pag";
	var t = selection();
	var tt = t[1].split(" ");
	var pag = tt[0];
	var cit = "";
	if (tt.length > 1) cit = tt[1];
	var link = "[[s:Pagina:Chi l'ha detto.djvu/#pagdjvu|#pagcarta]]".replace("#pagcarta", pag).replace("#pagdjvu", pag * 1 + 32);
	if (cit != "") link = "[[s:Pagina:Chi l'ha detto.djvu/#pagdjvu#cit|#pagcarta]]".replace("#pagcarta", pag).replace("#pagdjvu", pag * 1 + 32).replace("#cit", "#c" + cit);
	t[1] = frase.replace("#pag", link);
	scriviBox(t.join(""));
}

/* *********************  funzioni per parseTemplate ***********************/
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;
}

function parseTemplate(template, testo) {
	if (testo == undefined) testo = leggiBox();
	var t = find_stringa(testo, "{{" + template, "}}", 1, "{{");
	var l = [] // lista delle keys
	var t = "0=" + t.substring(2, t.length - 2) // nome del template in parametro "0"
	l.push["0"]
	var ts = {}
	var n = 1;
	t = cod(t);
	t = t.split("|");

	// 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];
}

function decod(testo) {
	testo = testo.replace(/__!__/g, "|");
	return testo;
}

function templateObj(nomeTemplate) {
	data = parseTemplate(nomeTemplate);
	this.keys = data[1];
	this.dict = data[0];
}

/************************ funzioni per getPage() ***************************/
oggetto = "";
datiAjax = "";

function getPage(title, site) {
	$("#spinnerIcon").css("display", "inline");
	$.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) {
		datiAjax = data;

		lista = "<ul><li>La pagina non esiste</li></ul>";
		oggetto = wikitext(data);
		if (oggetto != "-1") lista = makeLista();
		show(2);
		$("#spinnerIcon").css("display", "none");
	});
	//while ($("#spinnerIcon").css("display")=="inline"){continue;}
	//return oggetto;
}

function wikitext(oggetto) {
	l = [];
	for (i in oggetto.query.pages) {
		l.push(i);
	}
	if (l[0] == "-1") return "-1";
	testo = oggetto.query.pages[l[0]].revisions[0]["*"];
	testo = testo.replace("{{Information", "{{information").replace("{{Book", "{{book").replace("{{Creator", "{{creator").replace("{{Bio", "{{bio").replace(":MediaWiki:Proofreadpage_index_template", "MediaWiki_Proofreadpage_index_template");
	dati = {
		information: parseTemplate("information", testo),
		book: parseTemplate("book", testo),
		creator: parseTemplate("creator", testo),
		bio: parseTemplate("bio", testo),
		MediaWiki_Proofreadpage_index_template: parseTemplate("MediaWiki_Proofreadpage_index_template", testo)
	};
	return dati;
}

function makeLista(data) {
	lista = $("<ul></ul>");
	//{{:MediaWiki:Proofreadpage_index_template
	$.each(oggetto["MediaWiki_Proofreadpage_index_template"][1], function(index, key) {
		value = oggetto["MediaWiki_Proofreadpage_index_template"][0][key];
		keyDisp = key;
		if (key == "0") {
			keyDisp = "Nome template:";
		}
		if (value != "") $("<li><b>" + keyDisp + ": </b>" + value + "</li>\n").appendTo(lista);
	});
	$.each(oggetto["bio"][1], function(index, key) {
		value = oggetto["bio"][0][key];
		keyDisp = key;
		if (key == "0") {
			keyDisp = "Nome template:";
		}
		if (value != "") $("<li><b>" + keyDisp + ": </b>" + value + "</li>\n").appendTo(lista);
	});
	$.each(oggetto["creator"][1], function(index, key) {
		value = oggetto["creator"][0][key];
		keyDisp = key;
		if (key == "0") {
			keyDisp = "Nome template:";
		}
		if (value != "") $("<li><b>" + keyDisp + ": </b>" + value + "</li>\n").appendTo(lista);
	});
	$.each(oggetto["book"][1], function(index, key) {
		value = oggetto["book"][0][key];
		keyDisp = key;
		if (key == "0") {
			keyDisp = "Nome template:";
		}
		if (value != "") $("<li><b>" + keyDisp + ": </b>" + value + "</li>\n").appendTo(lista);
	});
	$.each(oggetto["information"][1], function(index, key) {
		value = oggetto["information"][0][key];
		keyDisp = key;
		if (key == "0") {
			keyDisp = "Nome template";
		}
		if (value != "") $("<li><b>" + keyDisp + ": </b>" + value + "</li>\n").appendTo(lista);
	});
	return lista;
}

function parseMetadata(divdata) {
	if (divdata == undefined || divdata == "") {
		if (wgSiteName == "Wikiquote") {
			if ($("a[href*='Indice:']").attr("title") != undefined) {
				link = $("a[href*='Indice:']").attr("title");
				fileUrl = link.replace(/ /g, "_").replace("s:Indice:", "File:");
			} else {
				fileUrl = "";
			}

		}
		if (wgCanonicalNamespace == "File") fileUrl = wgPageName;
		if (wgSiteName == "Wikisource") {
			if (wgCanonicalNamespace == "Indice") fileUrl = wgPageName.replace("Indice:", "File:");
			if (wgCanonicalNamespace == "Pagina") fileUrl = wgPageName.substring(0, wgPageName.lastIndexOf("/")).replace("Pagina:", "File:");
			if (wgCanonicalNamespace == "" && wgPageName.indexOf("/") == -1) {
				fileUrl = $('a[title^="Indice:"]').attr("title").replace("Indice:", "File:");
			}

			if (wgCanonicalNamespace == "" && wgPageName.indexOf("/") > -1) {
				fileUrl = $('a[title^="Pagina:"]').attr("title").replace("Pagina:", "File:");
				fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/"));
			}
		}
		html = $.ajax({
			url: "http://" + location.hostname + "/wiki/" + fileUrl,
			async: false
		}).responseText;
		divdata = $(".hproduct", html).html();
	}
	var tabellaDati = [];
	/* 
   var tr=$("tr",divdata);
   for (i=0; i<tr.length; i+=1) {     
      tabellaDati.push( [$("td",tr[i]).eq(0).attr("id").replace("fileinfotpl_",""),
                           $("td",tr[i]).eq(0).text(),
                           $("td",tr[i]).eq(1).html()]);
  } */
	return [divdata, tabellaDati];

}
importScript('User:Alex_brollo/Bottoni.js')