MediaWiki:Common.js

维基教科书,自由的教学读本

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的变更的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Internet Explorer或Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5
  • Opera:Ctrl-F5
/*
==定期強制用戶更新cache==

*/

mw.loader.using( 'mediawiki.cookie' ).then( function () {

if( (""+mw.config.get('wgUserGroups')).indexOf("user")!=-1 && (mw.config.get('wgAction')=="view") ){
 var today=new Date();

 if(!$.cookie("lastload") || isNaN($.cookie("lastload")) ){
  $.cookie("lastload", today.getTime());
 }else{

  if( today.getTime()-$.cookie("lastload") >= 7*24*60*60*1000 ){
   $.cookie("lastload", today.getTime());
   if( $.cookie("lastload")==today.getTime() ) window.location.reload(true);
  }else if( today.getTime()-$.cookie("lastload") < 0 ){
   $.cookie("lastload", today.getTime());
  }

 }

}

});

/*
== 中文處理 ==

*/

//返回繁簡字串
function wgULS(hans,hant,cn,tw,hk,sg,zh){
	ret = {
		'zh-hans':hans||cn||sg,
		'zh-hant':hant||tw||hk,
		'zh-cn':cn||hans||sg,
		'zh-sg':sg||hans||cn,
		'zh-tw':tw||hant||hk,
		'zh-hk':hk||hant||tw
	};
	if (ret[mw.config.get('wgUserLanguage')])
		return ret[mw.config.get('wgUserLanguage')];
	else
		return zh||hant||hans||cn||tw||hk||sg;//保證每一語言有值
}

/* 當需要時載入對應的 scripts */

if (mw.config.get('wgAction') == "edit" || mw.config.get('wgAction') == "submit") {
    //scripts specific to editing pages
    importScript("MediaWiki:Common.js/edit.js");
}

/*

== 辅助处理 ==
*/
//功能設定
if(!window.JSConfig){var JSConfig={};}
JSConfig.collapseText=wgULS('隐藏▲','隱藏▲');//指示折叠收缩的默认文字
JSConfig.expandText=wgULS('显示▼','顯示▼');//指示折叠展开的默认文字
JSConfig.autoCollapse=2;  //文章少于 autoCollapse 个折叠块时,不自动折叠
JSConfig.SpecialSearchEnhancedDisabled=false; //是否禁止增加其它搜索引擎

//遍历
function applyEach(callback,array){
	var i=0,j=array.length;
	while(i<j){callback(array[i++]);}
}

var addHandler = function(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else if (element.addEvent) { // for IE
		element.attachEvent("on" + type, handler);
	} else { // DOM Level 0
		element["on" + type] = handler;
	}
};

// 移動元素
function elementMoveto(node, refNode, pos){//默认位置为refNode前
	if(node && refNode){
		var parent=refNode.parentNode;
		if (pos && pos=='after') {refNode=refNode.nextSibling;}
		try {
			if(refNode){
				parent.insertBefore(node, refNode);
			}else{
				parent.appendChild(node);
			}
		} catch (DOMException) {}
	}
}
//创建元素
function createElement(tag,children,props){
	var element = document.createElement(tag);
	if(!(children instanceof Array)){children=[children];}
	applyEach(function(child){
		if(typeof child=='string'){child=document.createTextNode(child);}
		if(child){element.appendChild(child);}
	},children);
	if(typeof props=='object'){
		for(var k in props){
			switch(k){
			case 'styles':
				var styles=props.styles;
				for(var s in styles){element.style[s]=styles[s];}
				break;
			case 'events':
				var events=props.events;
				for(var e in events){ addHandler(element,e,events[e]); }
				break;
			case 'class':
				element.className=props[k];break;
			default:
				element.setAttribute(k,props[k]);
			}
		}
	}
	return element;
}

//wiki URL
var wgProjectURL={
	en:'//en.wikibooks.org',de:'//de.wikibooks.org',fr:'//fr.wikibooks.org',
	pl:'//pl.wikibooks.org',ja:'//ja.wikibooks.org',it:'//it.wikibooks.org',
	nl:'//hu.wikibooks.org',pt:'http://pt.wikibooks.org',es:'//es.wikibooks.org',
	sv:'//sq.wikibooks.org',//僅列前十名其它語言百科
	m:'//meta.wikimedia.org',b:'//zh.wikipedia.org',q:'//zh.wikiquote.org',
	n:'//zh.wikinews.org',wikt:'//zh.wiktionary.org',mw:'//www.mediawiki.org',
	commons:'//commons.wikimedia.org'
};
/**
* 将页面名称转换为URL
*
* @param page 页面名称
* @param paras 附加后缀对象,用空对象{}做参数可以取得源码
*/
function getWikiPath(page,paras){
	var reg=/^[a-z]+:/;
	var pre=page.match(reg);
	pre = pre && wgProjectURL[pre[0].replace(/:$/,'').toLowerCase()];
	if (pre) {page=page.replace(reg,'');} else {pre=mw.config.get('wgServer');} //保障没有相对路径,以照顾在线代理。
	var url = pre + mw.config.get('wgScript') + '?title=' + encodeURI( page.replace( ' ', '_' ) );
	if(typeof paras=='object'){
		paras.ctype=paras.ctype||'text';
		paras.dontcountme=paras.dontcountme||'s';
		paras.action=paras.action||'raw';
		for(var k in paras){url += '&' + k + '=' + paras[k]; }
	}
	return url;
}

//引入[[Special:Gadgets]]要求的腳本和樣式
if(window.requireScripts instanceof Array){
	applyEach(importScript,requireScripts);
}
if(window.requireStylesheets instanceof Array){
	applyEach(importStylesheet,requireStylesheets);
}

/*

== IE兼容性修正 ==
*/
function fixIE(){
}

//修正摺疊後定位變化
$(function(){if(location.hash){location.href=location.hash;}});

/*

== 首頁輸出修正 ==
*/
/** 首页输出修正 *******************************************************
  描述:
  维护者: [[User:Fdcn]]
*/

// "首頁" == mw.config.get('wgTitle') 代表重定向頁
if ( mw.config.get('wgIsMainPage') ) {
  mw.loader.using(['mediawiki.util']).then(function () {
		$( function () {
			mw.util.addPortletLink('p-lang', getWikiPath('Wikibooks:维基教科书语言列表'), 
			wgULS('维基教科书语言列表','維基教科書語言列表'), 'interwiki-completelist',wgULS('维基教科书的完整各语言列表', '維基教科書的完整各語言列表'));
		});
  });
}

/*

== 取消討論頁的[+]按鈕 ==
*/

$(function () {
	if(document.getElementById('no-newsection') && document.getElementById('ca-addsection')) {
		document.getElementById('ca-addsection').style.display="none";
	}
});

/*

==WikiMiniAtlas世界地圖==
*/
/**
 * WikiMiniAtlas is a popup click and drag world map.
 * See [[meta:WikiMiniAtlas]] for more information.
 * 創建者: [[:en:User:Dschwen]]
 */
mw.loader.load('//meta.wikimedia.org/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript');

/*
==反frame==
*/
try {
	if (top.location != self.location) {
		top.location.replace(self.location);
	}

}catch(ex){
	top.location.replace(self.location);
}

/*
==保護選項校正==
*/

if(mw.config.get('wgAction')=="protect") {

 $( function(){
  var pform=document.getElementById("mw-Protect-Form");
  var timeoptions;

  timeoptions=pform["wpProtectExpirySelection-edit"].options;
  if(timeoptions[0].value!="existing"){
   timeoptions[timeoptions.length-1].selected=true;
   ProtectionForm.updateExpiryList(pform["wpProtectExpirySelection-edit"]);
  }

  timeoptions=pform["wpProtectExpirySelection-move"].options;
  if(timeoptions[0].value!="existing"){
   timeoptions[timeoptions.length-1].selected=true;
   ProtectionForm.updateExpiryList(pform["wpProtectExpirySelection-move"]);
  }
 
 });

}

/*
==擷取選單文字按鈕==
*/

function addGetMenuTextButton(id, srcMenu, targetText, tiptext, afterSelIdx) {
 var btnAdd=createElement("a", ((!tiptext)?"(+)":tiptext), {
  'id': id ,
  'href' : '#'
 });
 btnAdd.srcMenu=srcMenu;
 btnAdd.targetText=targetText;
 btnAdd.afterSelIdx=(!afterSelIdx || isNaN(afterSelIdx))?0:afterSelIdx;
 btnAdd.onclick=function(){
  this.targetText.value+=this.srcMenu.options[srcMenu.selectedIndex].value;
  srcMenu.selectedIndex=this.afterSelIdx;
  return false;
 }


 srcMenu.parentNode.appendChild(btnAdd);
}

$( function(){
 var useForm;

 if(mw.config.get('wgAction')=="protect" || mw.config.get('wgAction')=="unprotect"){     //保護理由
  useForm=document.getElementById("mw-Protect-Form");
  addGetMenuTextButton("wpProtectReasonSelectionAdd", useForm.wpProtectReasonSelection, useForm["mwProtect-reason"], "", 0);

 }else if(mw.config.get('wgPageName').toLowerCase()=="special:blockip"){     //封禁理由
  useForm=document.getElementById("blockip");
  addGetMenuTextButton("wpBlockReasonListAdd", useForm.wpBlockReasonList, useForm.wpBlockReason, "", 0);

 }

} );

/*
==修正登入後即登出問題==
*/

if(mw.config.get('wgPageName').toLowerCase()=="special:userlogin" && (""+window.location).toLowerCase().indexOf("returnto=special:userlogout")!=-1) {
 window.location.replace(mw.config.get('wgServer')+mw.config.get('wgScript')+"?title=Special:UserLogin");
}

/*
==繁简logo显示==
*/

$(function() {
	var plogo = document.getElementById("p-logo");
	// Timeless 皮肤可以直接用不带文字的默认皮肤,参考其他站点的做法
	if ( mw.config.get('skin') === 'timeless' ) return;
	if ( navigator.appName == "Microsoft Internet Explorer" ) {
		if ( navigator.appVersion.match("MSIE 7.0") == null) {
			plogo.getElementsByTagName("span")[0].style.filter = "progid:DXImageTransform."

				+ "Microsoft.AlphaImageLoader(src=//upload.wikimedia.org/wikibooks/"
				+ wgULS("zh/b/bc/Wiki.png", "zh/0/06/Wiki_zh-hant.png")+ ")";
		}
		else {
			var a = plogo.firstChild;
			a.style.backgroundImage = "url(//upload.wikimedia.org/wikibooks/"
				+ wgULS("zh/b/bc/Wiki.png", "zh/0/06/Wiki_zh-hant.png")+ ")";
		}
	}
	else {
		var a = plogo.getElementsByTagName("A")[0];
		a.style.backgroundImage = "url(//upload.wikimedia.org/wikibooks/"

			+ wgULS("zh/b/bc/Wiki.png", "zh/0/06/Wiki_zh-hant.png")+ ")";
	}
});

/*
==避免在主條目中出現捲軸框==

*/

if(!mw.config.get('wgCanonicalNamespace')) $( function(){

 var divs=document.getElementsByTagName("div");

 for(var i=0; i<divs.length; i++){
  if(divs[i].id=="CContentList"){
   if(divs[i].parentNode.parentNode.id=="TagConversionHeader") continue;
  }

  if(divs[i].style.overflow.toLowerCase()=="auto" && divs[i].getElementsByTagName("img").length==0){
   divs[i].style.overflow="";
   divs[i].style.overflowY="visible";
   divs[i].style.padding="";
   divs[i].style.border="";
   divs[i].style.height="";
  }
 }

});

/* 
== metaBox ==

HERE STARTS THE WORKING-CODE OF "METABOXES"*/
 
 /* Funcionament de la Plantilla:Metacaixa
 Implementat per: Usuari:Peleguer.
 Actualitzat per Joanjoc seguint les indicacions d'en Martorell
 */
 
 function MetaCaixaInit(){
  //S'executa al carregar-se la pàgina, si hi ha metacaixes,
  // s'assignen els esdeveniments als botons
  //alert("MetaCaixaInit");
 
  var i=0       //Inicialitzem comptador de caixes
  for (i=0;i<=9;i++){
     var vMc = document.getElementById("mc"+i);
     if (!vMc) break;
     //alert("MetaCaixaInit, trobada Metacaixa mc"+i);
 
     var j=1    //Inicialitzem comptador de botons dins de la caixa
     var vPsIni = 0  //Pestanya visible inicial
     for (j=1;j<=9;j++){
        var vBt = document.getElementById("mc"+i+"bt"+j);
        if (!vBt) break;
        //alert("MetaCaixaInit, trobat botó mc"+i+"bt"+j);
        vBt.onclick = MetaCaixaMostraPestanya;          //A cada botó assignem l'esdeveniment onclick
        //alert (vBt.className);
        if (vBt.className=="mcBotoSel") vPsIni=j;  //Si tenim un botó seleccionat, en guardem l'index
     }
     //alert ("mc="+i+", ps="+j+", psini="+vPsIni );
     if (vPsIni == 0) { //Si no tenim cap botó seleccionat, n'agafem un aleatòriament
         vPsIni = 1+Math.floor((j-1)*Math.random()) ;
         //alert ("Activant Pestanya a l'atzar; _mc"+i+"bt"+vPsIni +"_");
         document.getElementById("mc"+i+"ps"+vPsIni).style.display = "block";
         document.getElementById("mc"+i+"ps"+vPsIni).style.visibility = "visible";
         document.getElementById("mc"+i+"bt"+vPsIni).className="mcBotoSel";
     } 
  }
 }
 
 function MetaCaixaMostraPestanya(){
  //S'executa al clicar una pestanya,
  //aquella es fa visible i les altres s'oculten
  var vMcNom = this.id.substr(0,3); //A partir del nom del botó, deduïm el nom de la caixa
  var vIndex = this.id.substr(5,1); //I l'index
 
  var i=1
  for (i=1;i<=9;i++){        //busquem totes les pestanyes d'aquella caixa
      //alert(vMcNom+"ps"+i);
        var vPsElem = document.getElementById(vMcNom+"ps"+i);
        if (!vPsElem) break;
        if (vIndex==i){ //Si és la pestanya bona la mostrem i canviem la classe de botó
                vPsElem.style.display = "block";
                vPsElem.style.visibility = "visible";
                document.getElementById(vMcNom+"bt"+i).className="mcBotoSel";
        } else {             //Sinó, l'ocultem i canviem la classe de botó
                vPsElem.style.display = "none";
                vPsElem.style.visibility = "hidden";
                document.getElementById(vMcNom+"bt"+i).className="mcBoto";
        }
  }
  return false; //evitem la recàrrega de la pàgina
 }
 
 $(MetaCaixaInit);
 
// fixing /zh/xxx urls
 
jQuery(function() {
    jQuery('a[href^="/zh/"]').each(function() {
        jQuery(this).attr('href', mw.config.get('wgScript') + '?title=' + encodeURIComponent(decodeURI(jQuery(this).attr('href')).slice(4)) + '&variant=zh');
    });
    jQuery('a[href^="/zh-hans/"]').each(function() {
        jQuery(this).attr('href', mw.config.get('wgScript') + '?title=' + encodeURIComponent(decodeURI(jQuery(this).attr('href')).slice(9)) + '&variant=zh-hans');
    });
    jQuery('a[href^="/zh-hant/"]').each(function() {
        jQuery(this).attr('href', mw.config.get('wgScript') + '?title=' + encodeURIComponent(decodeURI(jQuery(this).attr('href')).slice(9)) + '&variant=zh-hant');
    });
    jQuery('a[href^="/zh-cn/"]').each(function() {
        jQuery(this).attr('href', mw.config.get('wgScript') + '?title=' + encodeURIComponent(decodeURI(jQuery(this).attr('href')).slice(7)) + '&variant=zh-cn');
    });
    jQuery('a[href^="/zh-hk/"]').each(function() {
        jQuery(this).attr('href', mw.config.get('wgScript') + '?title=' + encodeURIComponent(decodeURI(jQuery(this).attr('href')).slice(7)) + '&variant=zh-hk');
    });
    jQuery('a[href^="/zh-sg/"]').each(function() {
        jQuery(this).attr('href', mw.config.get('wgScript') + '?title=' + encodeURIComponent(decodeURI(jQuery(this).attr('href')).slice(7)) + '&variant=zh-sg');
    });
    jQuery('a[href^="/zh-tw/"]').each(function() {
        jQuery(this).attr('href', mw.config.get('wgScript') + '?title=' + encodeURIComponent(decodeURI(jQuery(this).attr('href')).slice(7)) + '&variant=zh-tw');
    });
});