MediaWiki:Common.js: difference between revisions

From Wiktionary, the free dictionary
Jump to navigation Jump to search
Content deleted Content added
oops
Conrad.Irwin (talk | contribs)
Line 422: Line 422:
===Fix Wikified section titles===
===Fix Wikified section titles===
<pre>*/
<pre>*/
addOnloadHook(function () {
//[[Link]]
if (/\.5B/.test(window.location.href)) {
var url=window.location.href.replace(/.5B.5B:/g,"").replace(/.5B/g, "").replace(/.5D/g, "");
window.location = url;
}


// {temp|template}
//[[Link]]
if (/\.5B/.test(window.location.href)) {
if (/\.7B\.7Btemp\.7C(.*?)\.7D\.7D/.test(window.location.href)) {
var url=window.location.href.replace(/.5B.5B:/g,"").replace(/.5B/g, "").replace(/.5D/g, "");
var url=window.location.href.replace(/\.7B\.7Btemp.7C/g, ".7B.7B");
window.location = url;
window.location = url;
}
}
});

// {temp|template}
if (/\.7B\.7Btemp\.7C(.*?)\.7D\.7D/.test(window.location.href)) {
var url=window.location.href.replace(/\.7B\.7Btemp.7C/g, ".7B.7B");
window.location = url;
}


/** Change Special:Search to use a radio menu *******************************************************
/** Change Special:Search to use a radio menu *******************************************************

Revision as of 20:49, 25 June 2009

/* Any JavaScript here will be loaded for all users on every page load. */

/*</pre>
==JavaScript standard library==
<pre>*/

/*</pre>
===importScript===
<pre>*/

/**
 * importScript inserts a javascript page either 
 *    from Wiktionary: importScript('User:Connel MacKensie/yetanother.js');
 *    from another Wikimedia wiki: importScript('User:Lupin/insane.js','en.wikipedia.org');
 *
 *    by specifying the third argument, an oldid can be passed to ensure that updates to the script are not included.
 *    by specifying the fourth argument, a specific version of JavaScript can be declared.
 *
 *    based on [[w:MediaWiki:Common.js]] 2007-11-29
**/
var importedScripts={};
function importScript(page, wiki, oldid, jsver) {
    //Default to local
    if(!wiki)
      wiki=wgScript;
    else
      wiki='http://'+escape(wiki)+'/w/index.php';
 
    //Only include scripts once
    if(importedScripts[wiki+page])
        return false;
    importedScripts[wiki+page] = true;
 
    var url = wiki // From above
            + '?title=' +encodeURIComponent( page.replace(/ /g, '_') )
            + (oldid?'&oldid='+encodeURIComponent( oldid ):'')
            + '&action=raw&ctype=text/javascript&dontcountme=s';
 
    var scriptElem = document.createElement("script");
    scriptElem.setAttribute("src",url);
    scriptElem.setAttribute("type", jsver ? "application/javascript;version=" + jsver : "text/javascript");
    document.getElementsByTagName("head")[0].appendChild(scriptElem);
    return true;
}

/*</pre>
===importExternalScript===
<pre>*/

/**
 * importExternalScript inserts a javascript page 
 *    from anywhere including your local hard drive: importExternalScript('file:///C:/Documents%20and%20Settings/Andrew/My%20Documents/apitest.js');
 *
 *    based on importScript above 2008-01-21
**/
function importExternalScript(url) {
    //Only include scripts once
    if(importedScripts[url])
        return false;
    importedScripts[url] = true;
 
    var scriptElem = document.createElement("script");
    scriptElem.setAttribute("src",url);
    scriptElem.setAttribute("type","text/javascript");
    document.getElementsByTagName("head")[0].appendChild(scriptElem);
    return true;
}

/*</pre>
=== CSS ===
<pre>*/

/* Cross browser CSS - yurk */
var p_styleSheet=false;
 
window.addCSSRule = function (selector,cssText){
  if(!p_styleSheet) return setupCSS(selector,cssText);
  if(p_styleSheet.insertRule){
    p_styleSheet.insertRule( selector+' { '+cssText+' }', p_styleSheet.cssRules.length );
  }else if(p_styleSheet.addRule){ //Guess who...
    p_styleSheet.addRule(selector,cssText);
  }
 
  function setupCSS(selector,cssText){
    if(document.styleSheets){
      var i = document.styleSheets.length-1;
      while(i>=0){
        try{ //This loop tries to get around the irritation that some extensions
             //include external, and thus read-only, stylesheets. Bah.
          p_styleSheet = document.styleSheets[i];
          var media = p_styleSheet.media.mediaType?p_styleSheet.media.mediaType:p_styleSheet.media;
          if( media.indexOf('screen') > -1 || media == '' ){
            addCSSRule(selector,cssText);
            return true;
          }
        }catch(e){ i--; }
      }  
    }
    //Ok document.stylesheets isn't an option :(... take this for hacky
    //It might be better to create one <style> element and write into it
    // but it doesn't work :(
    window.addCSSRule = function(sel,css){
      var head = document.getElementsByTagName('head')[0];
      var text = sel + '{' + css + '}';
      try { head.innerHTML += '<style type="text/css">' + text + '</style>'; }
      catch(e) {
        var style = document.createElement('style');
        style.setAttribute('type', 'text/css');
        style.appendChild(document.createTextNode(text));
        head.appendChild(style);
      }
    }
    addCSSRule(selector,cssText);
  }
}
/*</pre>

===Cookies===
<pre>*/

function setCookie(cookieName, cookieValue) {
 var today = new Date();
 var expire = new Date();
 var nDays = 30;
 expire.setTime( today.getTime() + (3600000 * 24 * nDays) );
 document.cookie = cookieName + "=" + escape(cookieValue)
                 + ";path=/w"
                 + ";expires="+expire.toGMTString();
 document.cookie = cookieName + "=" + escape(cookieValue)
                 + ";path=/wiki"
                 + ";expires="+expire.toGMTString();
}

function getCookie(cookieName) {
  var start = document.cookie.indexOf( cookieName + "=" );
  if ( start == -1 ) return "";
  var len = start + cookieName.length + 1;
  if ( ( !start ) &&
    ( cookieName != document.cookie.substring( 0, cookieName.length ) ) )
      {
        return "";
      }
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function deleteCookie(cookieName) {
  if ( getCookie(cookieName) ) {
    document.cookie = cookieName + "=" + ";path=/w" +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    document.cookie = cookieName + "=" + ";path=/wiki" +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
  }
}

/*</pre>
==Wiktionary Customisation==
<pre>*/

/*</pre>
===WT:PREFS===
<pre>*/

if (wgUserName == "Hippietrail") {
  if (getCookie('WiktPrefs') || wgPageName == "Wiktionary:Preferences") {
     importScript('User:Hippietrail/custom-alpha.js');
  }
} else {
  if (getCookie('WiktPrefs') || wgPageName == "Wiktionary:Preferences") {
     //importScript('User:Connel_MacKenzie/custom.js');
     importScript('User:Hippietrail/custom.js');
  }
}

/*</pre>
===Page specific extensions===
<pre>*/

/*</pre>
====Wiktionary:Main Page====
<pre>*/
// Hide the title and "Redirected from" (maybe we should keep the redirected from so's people update their bookmarks ;)
if ( wgPageName == 'Wiktionary:Main_Page' && !( wgAction == 'view' || wgAction == 'submit' ) ){
  addCSSRule('.firstHeading','display: block !important;');
  addCSSRule('#contentSub','display: inline !important;');
}

/*</pre>
====WT:CUSTOM====
<pre>*/

else if( wgPageName=='Help:Customizing_your_monobook' ){
    importScript('MediaWiki:CustomSearch.js');
}

/*</pre>
====Turn headings in comments into real headings on JavaScript source pages====
<pre>*/

else if ((wgNamespaceNumber == 2 || wgNamespaceNumber == 8) && wgTitle.lastIndexOf('.js') != -1 && wgAction == 'view') {
    importScript('MediaWiki:JavascriptHeadings.js');
}

/*</pre>
====Add editor.js for editing translations====
<pre>*/

/** Trial run 2009-04-14. Please disable if causing problems. **/
importScript('User:Conrad.Irwin/editor.js');

/*</pre>
====Make Citations: tabs ====
<pre>*/
function citations_tab(){
  
  var mt_caption = 'entry';
  var mt_title = 'View the content page [alt-c]';
  var ct_caption = 'citations';
  var ct_title = 'View the citations page';

  var lookup = new Object();
  var ct_class = '';
  var safeTitle = encodeURIComponent(wgTitle.replace(/ /g,"_"));

  //Where to put Citations tab
  var insbef = document.getElementById('ca-edit');
  if(! insbef) insbef = document.getElementById('ca-viewsource');
  if(! insbef) return false;
  
  if( wgCanonicalNamespace == 'Citations' ){  
 
    //Remove accesskeys etc from Citations tab
    var ct = document.getElementById('ca-nstab-citations');
    ct.removeAttribute('accesskey');
    ct.setAttribute('title',ct_title);
    
    //Reset discussion tab to point to Talk:
    var dt = document.getElementById('ca-talk');
    
    for(var i=0;i<dt.childNodes.length;i++){
      var anc = dt.childNodes[i];
      if(anc.nodeName.toUpperCase()=='A'){
        anc.setAttribute('href',wgArticlePath.replace("$1","Talk:"+safeTitle));
        lookup['Talk:'+wgTitle] = dt;
      }
    }
    if(dt.className) dt.className = dt.className.replace('new','');
    
    //Create main tab before citations tab
    addPortletLink('p-cactions',wgArticlePath.replace("$1",safeTitle),mt_caption,'ca-nstab-main',mt_title,null,ct)
    lookup[wgTitle] = document.getElementById('ca-nstab-main');
    
    //Move Citations tab to correct position
    var tabbar = ct.parentNode;
    tabbar.removeChild(ct);
    tabbar.insertBefore(ct,insbef);
    
  }else if( wgCanonicalNamespace == '' || wgCanonicalNamespace == 'Talk' ){
  
    addPortletLink('p-cactions',wgArticlePath.replace("$1",'Citations:'+safeTitle),ct_caption,'ca-nstab-citations',ct_title,null,insbef); 
    lookup['Citations:'+wgTitle]=document.getElementById('ca-nstab-citations');

  }else{ //Nothing to see here...
  
    return false;
  
  }
  
  //Now check for red pages
  var ajaxer = sajax_init_object();
  if(! ajaxer) return false;
  
  var url = wgScriptPath+ '/api.php?format=txt&action=query&prop=info&titles=';
  var spl = '';
  for(var page in lookup){
    url+=spl+encodeURIComponent(page);
    spl='|';
  }
  
  ajaxer.onreadystatechange = function(){
    if( ajaxer.readyState == 4 ){
      if( ajaxer.status == 200 ){
        var resps = ajaxer.responseText.split("Array\n");
        for(var i in resps){
          if(resps[i].indexOf('[missing]')>0 ){
            var start = resps[i].indexOf("[title] => ")+11;
            var end = resps[i].indexOf("\n",start);
            make_tab_red(lookup[resps[i].substr(start,end-start)]);
          }
        }
      }
    }
  }

  ajaxer.open("GET", url);
  ajaxer.send('');

  function make_tab_red(tab){

    tab.className = tab.className?'new':tab.className+' new';

    for( var i=0;i<tab.childNodes.length;i++ ){
      var lnk = tab.childNodes[i];    
      if(lnk.nodeName.toUpperCase() == 'A' ){
        var href = lnk.getAttribute('href');
        lnk.setAttribute('href',href+(href.indexOf('?')>0?'&':'?')+'action=edit');
      }
    }
  }
}

addOnloadHook( citations_tab );

/*</pre>
====Geonotice====
<pre>*/

if (wgPageName == "Special:Watchlist") //watchlist scripts
{
    importScriptURI('http://toolserver.org/~para/geoip.fcgi');
    addOnloadHook(function() { importScriptURI('http://en.wiktionary.org/w/index.php?title=MediaWiki:Geonotice.js&action=raw&ctype=text/javascript&maxage=3600'); });
}

/*</pre>

==URL Fixes==
<pre>*/

/**
 * doRedirect will redirect if a did you mean box is found, and create a 
 * "redirected from X" if a rdfrom is passed in the get parameters
 * The first half is an ugly workaround for Bugzilla:3339, :(
 * The second half is an ugly workaround for not having serverware support :(
**/

/*</pre>
===Did you mean ____ redirects===
<pre>*/

function doRedirect() {
  var dym = document.getElementById('did-you-mean')
  var wiktDYMfrom= window.location.href.replace(/^(.+[&\?]rdfrom=([^&]+).*|.*)?$/,"$2");
  var wiktRndLang= window.location.href.replace(/^(.+[&\?]rndLang=([^&]+).*|.*)?$/,"$2");

// REDIRECTED FROM
  if( window.location.href.indexOf('rdfrom=')!=-1 ) {
    var insertPosition= document.getElementById("siteSub");
    var div=document.createElement("div");
    if(insertPosition){
      div.setAttribute("id","contentSub");
      var tt=document.createElement('tt');
      var lnk =document.createElement('a');
      lnk.setAttribute("href",wgArticlePath.replace("$1",wiktDYMfrom)+ '?redirect=no');
      lnk.className="new"; //As they are redlinks
      lnk.appendChild(document.createTextNode(decodeURIComponent(wiktDYMfrom)));
      tt.appendChild(lnk);
      div.appendChild(document.createTextNode("(Auto-redirected from "));
      div.appendChild(tt);
      div.appendChild(document.createTextNode(")"));
      insertPosition.parentNode.insertBefore(div,insertPosition.nextSibling);
      } else {
        alert('No insertposition');
      }

// DID YOU MEAN
    }else{
      if( dym 
          && !window.location.href.match(/[&\?]redirect=no/)
          && (getCookie('WiktionaryDisableAutoRedirect') != 'true')
        ) {
      var target = dym.firstChild.title;
      var pagetitle = document.getElementsByTagName('h1')[0].firstChild.nodeValue;

      if( pagetitle != target 
          && pagetitle.toLowerCase().replace(/[^a-z]/g, "") == target.toLowerCase().replace(/[^a-z]/g, "")
          && pagetitle.search(/Editing /g) == -1
          && !(document.getElementById('contentSub') && document.getElementById('contentSub').innerHTML.indexOf("Redirected from")>=0) // does contentSub always exist
        ) {
        document.location = wgArticlePath.replace("$1",encodeURIComponent(target.replace(/\ /g, "_")))
                          + '?rdfrom=' + encodeURIComponent(pagetitle.replace(/ /g,"_"));
      }
    }
  }

// Random page in a given language
  if( window.location.href.indexOf('rndLang=')!=-1 ) {
    var newloc = window.location.href;
    if (newloc.indexOf("#") != -1) {
      document.location = newloc.substring(0, newloc.indexOf('?rndLang=') );
    }
    var insertPosition= document.getElementById("siteSub");
    var div=document.createElement("div");
    if(insertPosition){
      div.setAttribute("id","contentSub");
      var tt = document.createElement('tt');
      var lnk = document.createElement('a');
      lnk.href = "http://connelm.homelinux.com/cgi-bin/randompage?lang=" + wiktRndLang ;
      lnk.appendChild( document.createTextNode(wiktRndLang) );
      tt.appendChild(lnk);
      var tt2=document.createElement('tt');
      var lnk2 =document.createElement('a');
      lnk2.href = "http://tools.wikimedia.de/~cmackenzie/rnd-wikt.html" ;
      lnk2.appendChild(document.createTextNode("Random"));
      tt2.appendChild(lnk2);
      div.appendChild( document.createTextNode("(") );
      div.appendChild(tt2);
      div.appendChild( document.createTextNode(" term in ") );
      div.appendChild(tt);
      div.appendChild(document.createTextNode(", described in English)"));
      insertPosition.parentNode.insertBefore(div,insertPosition.nextSibling);
      } else {
        alert('No insertposition');
      }
  }
}

addOnloadHook(doRedirect);

/*</pre>

===Fix Wikified section titles===
<pre>*/
addOnloadHook(function () {
  //[[Link]]
  if (/\.5B/.test(window.location.href)) {
    var url=window.location.href.replace(/.5B.5B:/g,"").replace(/.5B/g, "").replace(/.5D/g, "");
    window.location = url;
  }

  // {temp|template}
  if (/\.7B\.7Btemp\.7C(.*?)\.7D\.7D/.test(window.location.href)) {
    var url=window.location.href.replace(/\.7B\.7Btemp.7C/g, ".7B.7B");
    window.location = url;
  }
});

/** Change Special:Search to use a radio menu *******************************************************
   *
   *  Description: Change Special:Search to use a radio menu, with the default being
   *               the internal MediaWiki engine
   *  Created and maintained by: [[:fr:User:Pmartin]]
   */
 
if ((wgNamespaceNumber == -1) && (wgCanonicalSpecialPageName == "Search")) {
	var searchEngines = {
	  mediawiki: {
	    ShortName: "MediaWiki search",
	    Template: "/w/index.php?search={searchTerms}"
	  },
	  google: {
	    ShortName: "Google",
	    Template: "http://www.google.fr/search?hl=" + wgUserLanguage + "&q={searchTerms}&as_sitesearch=" + wgServer.substr(7, wgServer.length - 1 )
	  },
	  wikiwix: {
	    ShortName: "Wikiwix",
            Template: "http://www.wikiwix.com/index.php?action={searchTerms}&disp=dict"
	  },
          live: {
            ShortName: "Windows live",
	    Template: "http://search.live.com/results.aspx?q={searchTerms}&q1=site:" + wgServer
          },
	  yahoo: {
	    ShortName: "Yahoo",
	    Template: "http://search.yahoo.com/search?p={searchTerms}&vs=" + wgServer
	  }
	};
	addOnloadHook(externalSearchEngines);
}
 
 
function externalSearchEngines() {
 
  if (typeof SpecialSearchEnhanced2Disabled != 'undefined') return;
 
  var mainNode;
  if (document.forms["search"]) { 
    mainNode = document.forms["search"];
  } else {
    mainNode = document.getElementById("powersearch");
    if (!mainNode) return;
    var mainNode = mainNode.lastChild;
    if (!mainNode) return;
 
    while(mainNode.nodeType == 3) {
      mainNode = mainNode.previousSibling;
    }
  }
 
  var firstEngine = "mediawiki";
 
  var choices = document.createElement("div");
  choices.setAttribute("id","searchengineChoices");
  choices.style.textAlign = "center";
 
  var lsearchbox = document.getElementById("powerSearchText");
  var initValue = lsearchbox.value;
 
  var space = "";
 
  for (var id in searchEngines) {
    var engine = searchEngines[id];
	if(engine.ShortName)
	   {
	    if (space) choices.appendChild(space);
	    space = document.createTextNode(" ");
 
	    var attr = { 
	      type: "radio", 
	      name: "searchengineselect",
	      value: id,
	      onFocus: "changeSearchEngine(this.value)",
	      id: "searchengineRadio-"+id
	    };
 
	    var html = "<input";
	    for (var a in attr) html += " " + a + "='" + attr[a] + "'";
	    html += " />";
	    var span = document.createElement("span");
	    span.innerHTML = html;
 
	    choices.appendChild( span );
	    var label = document.createElement("label");
	    label.htmlFor = "searchengineRadio-"+id;
 
	    label.appendChild( document.createTextNode( engine.ShortName ) );
	    choices.appendChild( label );
	  }
	 }
	  mainNode.appendChild(choices);
 
	  var input = document.createElement("input");
	  input.id = "searchengineextraparam";
	  input.type = "hidden";
 
	  mainNode.appendChild(input);
 
	  changeSearchEngine(firstEngine, initValue);
}
 
function changeSearchEngine(selectedId, searchTerms) {
 
	  var currentId = document.getElementById("searchengineChoices").currentChoice;
	  if (selectedId == currentId) return;
 
	  document.getElementById("searchengineChoices").currentChoice = selectedId;
	  var radio = document.getElementById('searchengineRadio-'  + selectedId);
	  radio.checked = "checked";
 
	  var engine = searchEngines[selectedId];
	  var p = engine.Template.indexOf('?');
	  var params = engine.Template.substr(p+1);
 
	  var form;
	  if (document.forms["search"]) {
	    form = document.forms["search"];
	  } else {
	    form = document.getElementById("powersearch");
	  }
	  form.setAttribute("action", engine.Template.substr(0,p));
 
	  var l = ("" + params).split("&");
	  for (var i in l) {
	    var p = l[i].split("=");
	    var pValue = p[1];
 
	    if (pValue == "{language}") {
	    } else if (pValue == "{searchTerms}") {
	      var input;
	      if (document.forms["search"]) {
	        input = document.getElementById("searchText");
	      } else {
	        input = document.getElementById("powerSearchText");
	      } 
 
	      input.name = p[0];
	    } else {
	      var input = document.getElementById("searchengineextraparam");
 
	      input.name = p[0];
	      input.value = pValue;
	    }
	  }
}