MediaWiki:Gadget-Base.js
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.
/* <source lang="javascript"><nowiki> */
/**
* Derivato dal monobook.js di [[:en:User:Wayward]], basato su [[:en:User:Alphax/monobook.js]]
* Necessita dell'[[Wikisource:Monobook.js/monobook.css|apposito monobook.css]]
* Testato su Firefox e IE
* Contiene codice preso dagli script di [[Utente:Salvatore Ingala]], [[Utente:Paulatz]], [[Utente:Helios89]], [[Utente:Timendum]], [[Utente:Senpai]], [[Utente:Kiado]], [[Utente:Pietrodn]]
* Reso modulare ed elaborato da [[Utente:Jalo]]
* Forked from [[User:ABCD/monobook.js]] around April 2005
* Dual licensed under the GFDL and GPL
*/
/** VARIABILI GLOBALI **/
arrayMese = new Array(" ", "gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno",
"luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre");
arrayMeseValore = new Array(" ", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
var curTemplate;
function addLoadEvent(func)
{
if (window.addEventListener)
window.addEventListener("load", func, false);
else if (window.attachEvent)
window.attachEvent("onload", func);
}
// Utilities del monobook<br/>
// Vedi [[Wikisource:Monobook.js/Utils.js]]
mw.loader.load('//it.wikisource.org/w/index.php?title=Wikisource:Monobook.js/Utils.js&action=raw&ctype=text/javascript');
function curled (text){
return "{{"+text+"}}";
}
function curled1 (text){
return "{{"+text;
}
function curled2 (text){
return text+"}}";
}
function bracket (text){
return "<"+text+">";
}
//Questa variabile contiene il nome del browser utilizzato. Molto utile per evitare problemi
// di incompatibilita' tra la varie funzioni Javascript
// Si autovalorizza. Le sottovariabili da usare sono "BrowserDetect.browser", "BrowserDetect.version"
// e "BrowserDetect.OS"
var BrowserDetect = {
init: function () {
this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
this.version = this.searchVersion(navigator.userAgent)
|| this.searchVersion(navigator.appVersion)
|| "an unknown version";
this.OS = this.searchString(this.dataOS) || "an unknown OS";
},
searchString: function (data) {
for (var i=0;i<data.length;i++) {
var dataString = data[i].string;
var dataProp = data[i].prop;
this.versionSearchString = data[i].versionSearch || data[i].identity;
if (dataString) {
if (dataString.indexOf(data[i].subString) != -1)
return data[i].identity;
}
else if (dataProp)
return data[i].identity;
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index == -1) return;
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser: [
{ string: navigator.userAgent,
subString: "OmniWeb",
versionSearch: "OmniWeb/",
identity: "OmniWeb"
},
{
string: navigator.vendor,
subString: "Apple",
identity: "Safari"
},
{
prop: window.opera,
identity: "Opera"
},
{
string: navigator.vendor,
subString: "iCab",
identity: "iCab"
},
{
string: navigator.vendor,
subString: "KDE",
identity: "Konqueror"
},
{
string: navigator.userAgent,
subString: "Firefox",
identity: "Firefox"
},
{
string: navigator.vendor,
subString: "Camino",
identity: "Camino"
},
{ // for newer Netscapes (6+)
string: navigator.userAgent,
subString: "Netscape",
identity: "Netscape"
},
{
string: navigator.userAgent,
subString: "MSIE",
identity: "Explorer",
versionSearch: "MSIE"
},
{
string: navigator.userAgent,
subString: "Gecko",
identity: "Mozilla",
versionSearch: "rv"
},
{ // for older Netscapes (4-)
string: navigator.userAgent,
subString: "Mozilla",
identity: "Netscape",
versionSearch: "Mozilla"
}
],
dataOS : [
{
string: navigator.platform,
subString: "Win",
identity: "Windows"
},
{
string: navigator.platform,
subString: "Mac",
identity: "Mac"
},
{
string: navigator.platform,
subString: "Linux",
identity: "Linux"
}
]
};
BrowserDetect.init();
/**** Inizializzazione ****/
//Alias di document.getElementById
$ = function(id){
return document.getElementById(id);
};
/**** Carica le funzioni personalizzate ****/
//Codice adattato da Prototype 1.6.0, http://www.prototypejs.org/
//Distribuito con licenza MIT-style
(function() {
/* Support for the DOMContentLoaded event is based on work by Dan Webb,
Matthias Miller, Dean Edwards and John Resig. */
var timer, fired = false;
function fireContentLoadedEvent() {
if (fired) return;
if (timer) window.clearInterval(timer);
contentLoaded();
fired = true;
}
if (document.addEventListener) {
if (navigator.userAgent.indexOf('AppleWebKit/') > -1) {
timer = window.setInterval(function() {
if (/loaded|complete/.test(document.readyState))
fireContentLoadedEvent();
}, 0);
window.addEventListener('load', fireContentLoadedEvent, false);
} else {
document.addEventListener("DOMContentLoaded",
fireContentLoadedEvent, false);
}
} else {
//document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
$("__onDOMContentLoaded").onreadystatechange = function() {
if (this.readyState == "complete") {
this.onreadystatechange = null;
fireContentLoadedEvent();
}
};
}
})();
/** AutoComplete: Based on http://www.webreference.com/programming/javascript/gr/column5/ **/
function AutoComplete(db, oText, /* optional */ nMaxSize){
this.oText = oText;
this.nMaxSize = nMaxSize || 20;
var oDiv = document.createElement('div');
oDiv.style.border = '2px solid green';
oDiv.style.position = 'absolute';
oDiv.style.visibility = 'hidden';
oDiv.style.backgroundColor = 'white';
this.oDiv = oDiv;
oText.parentNode.insertBefore(oDiv, oText.nextSibling);
this.db = db.sort();
oText.AutoComplete = this;
oText.onkeyup = AutoComplete.prototype.onTextChange;
oText.onblur = AutoComplete.prototype.onTextBlur;
};
AutoComplete.prototype.onTextBlur = function(){ this.AutoComplete.onblur(); };
AutoComplete.prototype.onblur = function(){ this.oDiv.style.visibility = "hidden"; };
AutoComplete.prototype.onTextChange = function(){ this.AutoComplete.onchange(); };
AutoComplete.prototype.onDivMouseDown = function(){ this.AutoComplete.oText.value = this.innerHTML; };
AutoComplete.prototype.onDivMouseOver = function(){ this.style.backgroundColor = 'lime'; };
AutoComplete.prototype.onDivMouseOut = function(){ this.style.backgroundColor = 'white'; };
AutoComplete.prototype.onchange = function(){
var txt = this.oText.value;
var aStr = [];
for(var i = 0; i < this.db.length; i++)
if(this.db[i].toLowerCase().indexOf(txt.toLowerCase()) == 0)
aStr.push(this.db[i]);
var nCount = aStr.length;
if ((this.nMaxSize == -1) || ((nCount < this.nMaxSize) && (nCount > 0))){
while (this.oDiv.hasChildNodes())
this.oDiv.removeChild(this.oDiv.firstChild);
var i, n = aStr.length;
for (i = 0; i < n; i++){
var d = document.createElement('div');
this.oDiv.appendChild(d);
d.appendChild(document.createTextNode(aStr[i]));
d.onmousedown = AutoComplete.prototype.onDivMouseDown;
d.onmouseover = AutoComplete.prototype.onDivMouseOver;
d.onmouseout = AutoComplete.prototype.onDivMouseOut;
d.AutoComplete = this;
}
this.oDiv.style.left = this.oText.offsetLeft+'px'; //NON-STANDARD! offsetLeft
this.oDiv.style.top = (this.oText.offsetTop+this.oText.clientHeight)+'px'; //NON-STANDARD! offsetTop e clientHeight
this.oDiv.style.visibility = "visible";
}
else {
this.oDiv.innerHTML = "";
this.oDiv.style.visibility = "hidden";
}
};
/** AutoComplete END **/
// Recupera il valore di un cookie
function GetCookie(name)
{
var cookie = ' ' + document.cookie;
var search = ' ' + name + '=';
var setStr = '';
var offset = 0;
var end = 0;
offset = cookie.indexOf(search);
if (offset != -1)
{
offset += search.length;
end = cookie.indexOf(';', offset)
if (end == -1)
end = cookie.length;
setStr = cookie.substring(offset, end);
setStr = setStr.replace(/\\+/g, ' ');
setStr = decodeURIComponent(setStr);
}
return(setStr);
}
// Setta il valore di un cookie
function SetCookie(name, value, expires, path, domain, secure)
{
var cookie = name + '=' + encodeURIComponent(value);
if (expires != null)
cookie += '; expires=' + expires
if (path != null)
cookie += '; path=' + path;
if (domain != null)
cookie += '; domain=' + domain;
if (secure != null)
cookie += '; secure';
document.cookie = cookie;
}
/** WikiHistory **/
function getHistoryFromCookie(){
var c = GetCookie("wikiHistory");
var hist = c ? c.split('#') : [];
for(var i = 0; i < hist.length; i++)
hist[i] = decodeURIComponent(hist[i]);
return hist;
}
function saveHistoryToCookie(){
if(mw.config.get("wgNamespaceNumber") < 0) return;
var c = GetCookie("wikiHistory"), i;
var h = c ? c.split('#') : [];
var current = encodeURIComponent(mw.config.get("wgPageName").replace(/_/g, ' ')), found = -1;
for(i = 0; i < h.length; i++)
if(h[i] == current){
found = i; break;
}
if(found == -1)
h.push(current);
else
h[found] = null;
var newh = [];
for(i = Math.max(0, h.length - 100); i < h.length; i++)
if(h[i] != null)
newh.push(h[i]);
var expire = new Date(); // scadenza del cookie
expire.setTime(expire.getTime() + (60 * 60 * 1000)); //scadenza di un'ora
SetCookie('wikiHistory', newh.join('#'), expire.toGMTString(), '/');
}
/** WikiHistory END **/
function contentLoaded(){
ta['pt-logout'] = ['x', 'Logout (esci)']; //cambia l'accesskey per "logout"
akeytt();
}
/**** Funzioni per le pagine di discussione ****/
// Aggiunge il messaggio "msg" alla pagina editata, scrive "summ" nell'oggetto,
// segna o meno "segui questa pagina" a seconda dell'impostazione precedente
// e spunta "modifica minore"
function edit_summary_watch(msg, summ, watch, minor)
{
WEUpdateTextarea();
var f = document.editform, t = f.wpTextbox1;
if (t.value.length > 0)
t.value += '\n';
t.value += msg;
f.wpSummary.value = summ;
f.wpWatchthis.checked = watch;
f.wpMinoredit.checked = minor;
WEUpdateFrame();
}
// Come il precedente, ma aggiunge "msg" all'inizio della pagina
function edit_summary_watch2(msg, summ, watch, minor)
{
WEUpdateTextarea();
var f = document.editform, t = f.wpTextbox1;
t.value = msg + '\n' + t.value;
f.wpSummary.value = summ;
f.wpWatchthis.checked = watch;
f.wpMinoredit.checked = minor;
WEUpdateFrame();
}
//Aggiunge qualcosa ad un portlet.
//PARAMS:
//* id: id del portlet.
//* obj: L'oggetto da aggiungere
function addToPortlet(id, obj)
{
var f = document.getElementById(id);
f = f.getElementsByTagName("div")[0];
f.appendChild(obj);
}
/* INIZIO Segna come verificata */
mphkLinkTitle = "Segna come verificata la revisione corrente";
mphkLinkTitle2 = "Segna come verificata l'ultima revisione analizzata";
mphkLinkText = "Segna come verificata";
mphkLinkText2 = "Segna come verificata";
mphkShortLinkText = "ver"
function setMarkPatrolledHotKey(){
ta['p-verified'] = ['v', 'Segna come verificato'];
akeytt();
}
function mphkAddMarkpatrolledLink(){
//100 alla volta, comunque non più 2000 links
for(var i = mphkCounter; (i < mphkCounter + 100) && (i < mphkLinks.length) && i < 2000; i++){
var rcidpos = mphkLinks[i].href.indexOf('&rcid=');
if ((rcidpos == -1) || (mphkLinks[i].href.indexOf('&action=') != -1)) continue;
var rcid = mphkLinks[i].href.substring(rcidpos);
var mp = document.createElement('a');
mp.href = "/w/index.php?title=" + encodeURIComponent(mphkLinks[i].title) + "&action=markpatrolled"+rcid;
mp.title = mphkLinkTitle;
mp.appendChild(document.createTextNode(mphkShortLinkText));
mphkLinks[i].parentNode.insertBefore(mp, mphkLinks[i+mphkOffset].nextSibling);
mphkLinks[i].parentNode.insertBefore(document.createTextNode("; "), mp);
}
mphkCounter = i;
if (mphkCounter < mphkLinks.length && mphkCounter < 2000)
setTimeout("mphkAddMarkpatrolledLink()", 100);
else{
mphkLinks = null;
mphkCount = null;
}
}
/* INIZIO Dynamic pages */
function mbAddTrustedPages(/* params */){
if (typeof mbTrustedPages == 'undefined') mbTrustedPages = {};
for(var i = 0; i < arguments.length; i++)
mbTrustedPages[arguments[i]] = true;
}
$(function (){
if(!mw.config.get("wgIsArticle")) return; //non in modifica
if(typeof mbTrustedPages == 'undefined') return;
if (mbTrustedPages[mw.config.get("wgPageName")] == true){
var pre = $('javascriptCode');
if (!pre) return;
var code = pre.innerHTML.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<");
//eval(code);
var script = document.createElement('script');
script.appendChild(document.createTextNode(code));
document.body.appendChild(script);
}
});
/* FINE Dynamic pages */
function HelpHotkeys ()
{
var text = "";
var counter = 0;
for (codice in pulsantiHotkey)
if (pulsantiHotkey[codice] != '')
text += pulsantiDescr[codice] + " = Alt+" + pulsantiHotkey[codice] + '\n';
alert (text);
}
/* Aggiorna la lista degli hotkeys */
$(function(){
if (typeof(tastiHotkeys) == "undefined")
return;
else
for (tasto in tastiHotkeys)
{
// vietato usare lo stesso codice per 2 pulsanti diversi
for (tasto2 in pulsantiHotkey)
if (pulsantiHotkey[tasto2] == tastiHotkeys[tasto])
pulsantiHotkey[tasto2] = '';
// assegna il valore scelto dall'utente
pulsantiHotkey[tasto] = tastiHotkeys[tasto];
}
})
/* Catch di hotkeys + speedy google search*/
function catchHotkeys (){
if (BrowserDetect.browser=="Firefox" || BrowserDetect.browser=="Mozilla" || BrowserDetect.browser=="Netscape")
{
var listenerKeyPress = function(e){
e = (e) ? e : ((window.event) ? window.event : null);
if(e && e.altKey && !e.shiftKey && !e.ctrlKey){
var toCheckNum = (e.which) ? e.which : e.keyCode;
var toCheck = String.fromCharCode(toCheckNum);
for (x in pulsantiHotkey)
{
if (pulsantiHotkey[x].toUpperCase() == toCheck.toUpperCase())
eval(pulsantiComando[x]);
}
//Fermo il propagarsi degli eventi
e.stopPropagation();
//Cancello l'azione di default
e.preventDefault();
return false;
}
}
wpTextbox1 = $("wpTextbox1");
if (wpTextbox1 != null)
{
if (wpTextbox1.addEventListener)
wpTextbox1.addEventListener('keypress', listenerKeyPress, true); //Non-IE
else
wpTextbox1.onkeypress = listenerKeyPress;
}
}
var listenerMouseUp = function(e){
e = (e) ? e : ((window.event) ? window.event : null);
if(e && e.ctrlKey){
if(navigator.appName=='Microsoft Internet Explorer' && navigator.userAgent.indexOf("Opera")==-1) //IE
var t = document.selection.createRange().text;
else //Non-IE
var t = document.getSelection ? document.getSelection().toString() : window.getSelection().toString();
t = t.replace(/^\s+/, '').replace(/\s+$/, ''); //trim
var q = t.indexOf('"') == -1 ? '"' : '';
if(t)
window.open("http://www.google.com/search?q=" + q + encodeURIComponent(t) + q);
}
}
if (window.addEventListener)
window.addEventListener('mouseup', listenerMouseUp, false); //Non-IE
else
document.onmouseup = listenerMouseUp; //IE
}
$(catchHotkeys);
/** Codice di compatibilità con WikEd **/
//Copia dal frame di wikEd (//en.wikipedia.org/wiki/User:Cacycle/wikEd.js) alla wpTextbox1 textarea
function WEUpdateTextarea(){
if (typeof(wikEdUseWikEd) != 'undefined')
if (wikEdUseWikEd == true)
WikEdUpdateTextarea();
}
//Copia la wpTextbox1 textarea nel frame del wikEd
function WEUpdateFrame(){
if (typeof(wikEdUseWikEd) != 'undefined')
if (wikEdUseWikEd == true)
WikEdUpdateFrame();
}
function fullescape(text)
{
return escape(text).replace(/\+/g,"%2B");
}
// Grazie a [[:en:User:Topaz]]
function msXmlhttpreq() {
if (window.XMLHttpRequest) {
xmlhttpobj = new XMLHttpRequest()
} else {
try {
xmlhttpobj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttpobj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlhttpobj = null;
}
}
}
return xmlhttpobj;
}
// Grazie a [[:en:User:Topaz]]
function msDoReq(url,postdata,headers) {
var req = msXmlhttpreq();
req.open(postdata?"POST":"GET", url, false);
for(header in headers)
req.setRequestHeader(header,headers[header]);
req.send(postdata||null);
return req;
}
// Grazie a [[:en:User:Topaz]]
function msSetPageContent(pagename,content,summary,watch) {
var prelimresp = msDoReq("/w/index.php?title="+pagename+"&action=submit");
var edittime = prelimresp.responseText.match(/\<input type='hidden' value="(\d+)" name="wpEdittime" \/\>/)[1];
var edittoken = prelimresp.responseText.match(/\<input type='hidden' value="([^"]+)" name="wpEditToken" \/\>/)[1];
msDoReq("/w/index.php?title="+pagename+"&action=submit",
"wpEdittime="+edittime+
"&wpEditToken="+fullescape(edittoken)+
"&wpTextbox1="+encodeURIComponent(content)+
"&wpSummary="+encodeURIComponent(summary)+
(watch?"&wpWatchthis=on":"")+
"&wpSection=&wpSave=Save+page",
{"Content-Type":"application/x-www-form-urlencoded"});
}
// Grazie a [[:en:User:Topaz]]
function msGetPageContent(pagename) {
var req = msDoReq("/w/index.php?title="+pagename+"&action=edit");
var content = req.responseText.match(/\<textarea[\w\W]*?\>([\w\W]*?)\<\/textarea\>/)[1];
content = content.replace(/\<\;/gi, "<");
content = content.replace(/\>\;/gi, ">");
content = content.replace(/\"\;/gi, "\"");
content = content.replace(/\&\;/gi, "&");
return content;
}
// Controlla se il monobook e' tra tag -PRE-
function checkPre(newMonobook)
{
if (newMonobook.indexOf("//<pre>") == -1)
newMonobook = "//<pre>\n" + newMonobook;
if (newMonobook.indexOf("//</pre>") == -1)
newMonobook = newMonobook + "\n//</pre>";
return newMonobook;
}
/**** Fine ****/
// </nowiki></pre>
// </nowiki></source>