MediaWiki:CurrentIndex.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.
function parseLivre(livre) {
	var pdxpc = []; // pdxpc è una lista semplice in cui la pagina djvu è l'indice
	var pdq =[];    // pdq è  la corrispondente lista dei SAL delle pagine;
	var pd = "";    // pd è pagina djvu 
	var pc = "";    // pc è pagina cartacea
	var pq="";      // pw è il SAL
 	var pdclass="";
	// lettura dell'html della pagina Indice corrispondente a base
	html = $.ajax({
		url: "/w/index.php?action=render&title=" + livre,
		async: false
	}).responseText;
 
	// estrazione della lista dei link alle pagine
	var links = $(".pagineDellEdizione a", $(html)); // 
 
	// estrazione di pd e pc dai link e assegnazione a una lista in cui l'indice è pd e il valore è pc
	for (i = 0; i < links.length; i += 1) {
		pd = parseInt($(links[i]).attr("title").match(/\/(\d+) */)[1]);
		pc = $.trim($(links[i]).text().match(/^0*(.+)/)[1]);
		pdxpc[pd] = pc;
 		pq="";
 		pdclass=$(links[i]).attr("class");
 		if (pdclass.indexOf("new")>-1) pdq[pd]="new";
 		else pdq[pd]=/quality(\d)/.exec(pdclass)[1];
		
	}
 
	// la lista viene popolata con stringhe vuote se vi sono dei "buchi"
	for (i = 1; i < pdxpc.length - 1; i += 1) {
		if (pdxpc[i] === undefined) pdxpc[i] = "";pdq[pd]="";
	}
    // costuisco un array a chiave con chiave pc
	var pcxpd={};
	for (i = 1; i < pdxpc.length - 1; i += 1) {
		pcxpd[pdxpc[i]]=i;
	}
	var linksc=$(".tableItem",  $(html));
	var itemList=[];
	for (var item=0; item<linksc.length; item+=1){
 
		itemEl={};
		itemEl.ns0Name=$("a",linksc.eq(item)).first().attr("title").replace(" (tuttora non scritto)","");
		itemEl.ns0Title=$("a",linksc.eq(item)).first().text();
		itemEl.PageName=$("a",linksc.eq(item)).last().attr("title").replace(" (tuttora non scritto)","");
		itemEl.PageTitle=$("a",linksc.eq(item)).last().text();
		itemList.push(itemEl);
	}
	// Eseguo lettura e parsing dei dati del wikicode
	var wikiText = $.ajax({
				url: mw.config.get("wgServer")+"/w/index.php?action=raw&title=" + livre + "&random=" + Math.random(),
				async: false
			}).responseText; console.log(wikiText);
			var data = parseTemplate(":MediaWiki:Proofreadpage_index_template", wikiText)[0];
	var fonte=$(".data", $(html)).data("fonte");
	var baseImg=$(".thumbinner img",$(html)).attr("src");
	var x=/page(\d+)-(\d+)px/.exec(baseImg);
	baseImg=baseImg.replace(x[0],"page#numpage#-#width#px");
	return [pcxpd,itemList,fonte,data,baseImg,pdxpc,pdq];
}
/* As soon a ns0,Page or Index page has been opened, current index is compared with the saved one and data are updated if needed only
*/
var currentIndex = typeof(currentIndex) == 'undefined' ? "" : currentIndex;
function testIndexData() {
	if (currentIndex === '') {
		currentIndex = 'No index';
		
		if (mw.config.get("wgNamespaceNumber")===0 && mw.config.get("wgPageName").indexOf('Pagina_principale') == -1 ) {
			try {
				currentIndex=mw.config.get( 'prpSourceIndexPage' ) || decodeURIComponent($(mw.config.get("proofreadpage_source_href")).attr("href").replace("/wiki/",""))
	              .replace(/_/g," ");
			}
			catch(err) {
			     currentIndex=getCurrentIndex();
			}
		}
		if (mw.config.get("wgCanonicalNamespace")==="Page" || mw.config.get("wgCanonicalNamespace")==="Index") {
			currentIndex=mw.config.get("wgPageName").split("/")[0].replace("Pagina:","Indice:");
		}
		
		console.log("Indice corrente: "+currentIndex);
		if (currentIndex !== '' && currentIndex !=="No index" && localStorage.currentIndex !== currentIndex) {
			
			localStorage.setItem("currentIndex",currentIndex);
			var dataIndex=parseLivre(currentIndex);
			
			localStorage.setItem("currentIndexData",JSON.stringify(dataIndex[0]));
			localStorage.setItem("currentIndexSummaryData",JSON.stringify(dataIndex[1]));
			localStorage.setItem("currentIndexSource",dataIndex[2]);
			localStorage.setItem("currentIndexMetadata",JSON.stringify(dataIndex[3]));
			localStorage.setItem("currentIndexBaseImg",dataIndex[4]);
			localStorage.setItem("currentIndexPagelist",JSON.stringify(dataIndex[5]));
			localStorage.setItem("currentIndexPageSal",JSON.stringify(dataIndex[6]));
		}
	 	mw.currentIndex=localStorage.currentIndex;
	 	mw.currentIndexBaseImg=localStorage.currentIndexBaseImg;
	 	mw.currentIndexSource=localStorage.currentIndexSource;
	    mw.currentIndexData=JSON.parse(localStorage.getItem("currentIndexData"));
	    mw.currentIndexMetadata=JSON.parse(localStorage.getItem("currentIndexMetadata"));
		mw.currentIndexSummaryData=JSON.parse(localStorage.getItem("currentIndexSummaryData"));
		mw.currentIndexPagelist=JSON.parse(localStorage.getItem("currentIndexPagelist"));
		mw.currentIndexPageSal=JSON.parse(localStorage.getItem("currentIndexPageSal"));
		// if (mw.config.get("wgCanonicalNamespace")==="" && $.trim($("#wpTextbox1").val())=="") addPages();
	}
}

/* When in namespace ns0, new pages doesn't contain a proofreadpage_source_href variable; but the name of the Index page pointing to current ns0 page can be recevered bu API.
*/
function getCurrentIndex() {
	console.log('getCurrentIndex: chiamata ajax per recuperare eventuali indici che puntano a questa pagina...');
	try {
	   var bltitle=mw.config.get("wgPageName");
	   var blnamespace="110";
	   var api_url=["/w/api.php?action=query",
             "format=json",
             "list=backlinks",
             "blnamespace="+blnamespace,
             "bltitle="+bltitle,
             "redirects="].join("&");
	    var result=JSON.parse($.ajax({url:api_url,async:false}).responseText);
	    return result.query.backlinks[0].title;
		}
	catch(err) {
	    return "No index";
	}
}



function numeroPagina(nomePagina) {
	var np=nomePagina.substring(nomePagina.indexOf("/")+1);
	return np*1;
}

$(document).ready(function() {

	testIndexData();
	console.log("Chiamata di textIndexData eseguita");
});



function autoNs0_test(ns0ToBuild) {
	// "use strict";
	//var alert, window, mw, $, console, oggi, scriviBox, numeroPagina;
	var indiceSorgente = "", titolo = "", intestazione = "", testo = "", ajaxEdit = true, data = {}, dati = {}, i = 0, capCor = "", capPrec = "", capSucc = "", baseNome = "", preview = "";
	function aggiungiIndice(testo) {
		// var $, mw, count; 
		var indice = "", asteriscs = "", rigaIndice = "", l = [], titolo = mw.config.get("wgPageName").replace(/_/g, " ");
		$.each(mw.currentIndexSummaryData, function (index, value) {
			if (value.ns0Name.indexOf(titolo + "/") === 0) {
				rigaIndice = value.ns0Name.replace(titolo, "");
				asteriscs = "***********".substring(0, count(rigaIndice, "/"));
				l.push(asteriscs + " {" + "{" + "testo|" + value.ns0Name.replace(titolo, "") +
					"|" + value.ns0Title + "}}");
			}
		});
		if (l.length > 0) {
			indice  = "\n\n== Indice ==\n" + l.join("\n");
		}
		return testo + indice;
	}
	if (ns0ToBuild === undefined) {
		ns0ToBuild = mw.config.get("wgPageName").replace(/_/g, " ");
		ajaxEdit = false;
	}
	// console.log("ajaxEdit =" + ajaxEdit);
	// ns0 pagina-base
	//if (mw.config.get("wgPageName").indexOf('/') == -1) {
	if (ns0ToBuild.indexOf('/') === -1) {
		indiceSorgente = mw.currentIndex;
		if (indiceSorgente !== undefined) {
			data = mw.currentIndexMetadata;
			//costruzione template qualità e intestazione
			intestazione = '{' + '{' + 'Qualità|avz=25%|data=' + oggi() + '|arg=Da definire}}' + "{"+"{Intestazione\n| Nome e cognome dell'autore = #autore\n| Titolo =#titolo\n| Anno di pubblicazione = #anno\n| Lingua originale del testo =\n| Nome e cognome del traduttore = #traduttore\n| Anno di traduzione =\n| Progetto = #progetto\n| Argomento =\n| URL della versione cartacea a fronte = #url\n}}\n";
			titolo = data.NomePagina;
			if (data.Titolo !== "") {titolo = data.Titolo; }
			testo = intestazione.replace("#autore", data.Autore).replace("#titolo", titolo).replace("#anno", data.Anno).replace("#anno", data.Anno).replace("#traduttore", data.Traduttore === undefined ? '' : data.Traduttore).replace("#anno", data.Anno).replace("#progetto", data.Progetto).replace("#url", indiceSorgente.replace(/_/g, " "));
			//trasclusione della prima pagina (che si spera contenga il frontespizio)
			testo += '\n\n<' + 'pages index="' + indiceSorgente.replace('Indice:', '') + '" from=1 to=1 />\n\n';
		}
	} else {
	// gestione sottopagina
		dati = mw.currentIndexSummaryData;
		titolo = "";
		for (i = 0; i < dati.length; i += 1) {
			//if (dati[i].ns0Name === mw.config.get("wgPageName").replace(/_/g," ")) break;
			if (dati[i].ns0Name === ns0ToBuild) { break; }
		}
		capCor = dati[i];
		capSucc = dati[i + 1];
		capPrec = dati[i - 1];
		if (capCor.ns0Title !== undefined) {titolo = capCor.ns0Title; }
		testo = (
			'{' + '{' + 'Qualità|avz=25%|data=' + oggi() + '|arg=Da definire}}' +
			'{' + '{' + 'IncludiIntestazione|sottotitolo=#1|prec=../#2|succ=../#3}}\n\n' +
			'<'+'pages index="#4" from=#5 to=#6 fromsection= tosection= />'
		)
			.replace("#1", titolo)
			.replace("#4", mw.currentIndex.replace("Indice:", ""))
			.replace("#5", numeroPagina(capCor.PageName));
		if (capSucc !== undefined) {
			testo = testo.replace("#6", numeroPagina(capSucc.PageName));
		} else {
			testo = testo.replace("#6", "");
		}
		baseNome = ns0ToBuild.substring(0, ns0ToBuild.lastIndexOf("/") + 1);
		// caso primo della lista
		if (capPrec !== undefined) {
			testo = testo.replace("#2", capPrec.ns0Name.replace(baseNome, ""));
		} else {testo = testo.replace("../#2", ""); }
		//caso ultimo della lista
		if (capSucc !== undefined) {
			testo = testo.replace("#3", capSucc.ns0Name.replace(baseNome, ""));
		} else {testo = testo.replace("../#3", ""); }
	}
	testo = aggiungiIndice(testo);
			//prova a parsare il testo per vedere se serve il {{Sezione note}}
	preview = $.ajax({
		url: "/w/api.php?action=parse&title=" + ns0ToBuild.replace(/ /g, "_") + "&format=json&random=" + Math.random() + "&text=" + testo,
		async: false
	}).responseText;
	if (preview.indexOf('Errore nella funzione Cite: Sono presenti dei marcatori <code>&lt;ref&gt;</code> ma non \\u00e8 stato trovato alcun marcatore <code>&lt;references/&gt;</code>') !== -1) {
		testo += '\n\n{{Sezione note}}';
	}
	if (ajaxEdit) {
		new mw.Api().postWithToken('edit', {
			action: 'edit',
			title: ns0ToBuild,
			summary: "Creo pagina via ajax edit con autoNs0_test()",
			text: testo
		}).done(function (data) {
			if (data && data.edit && data.edit.result === 'Success') {
				console.log("OK, pagina " + ns0ToBuild + "creata");
				// window.location.reload();
			} else {
				alert("Errore nel salvataggio della pagina");
			}
		});
	} else {
		scriviBox(testo);
	}
	$('#wpSummary').val('Creo pagina con autoNs0_test()');
}