Jump to content

User:PC78/monobook.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by PC78 (talk | contribs) at 17:16, 13 September 2009. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// [[User:Dschwen/highlightredirects.js]] - please include this line 
document.write('<script type="text/javascript" src="' 
             + 'http://en.wikipedia.org/w/index.php?title=User:Dschwen/highlightredirects.js' 
             + '&action=raw&ctype=text/javascript&dontcountme=s"></script>');

//Add a 'null edit' tab
if(wgNamespaceNumber != -1 && wgArticleId != 0) { 
    addOnloadHook( function() {
        addPortletLink('p-cactions', 
                       wgScript + '?title=' + encodeURIComponent(wgPageName) + '&action=edit&nulledit=true',
                       'null',
                       'p-null',
                       'Null edit this page');
    }
)}
if( wgAction == 'edit' && inurl('nulledit') == 'true') {
    addOnloadHook( function() {
        document.getElementById('wpSave').click();
    }
)}
 
function inurl(p) {
    var re = RegExp('[&?]' + p + '=([^&]*)');
    var matches;
    if (matches = re.exec(document.location)) {
        try { 
            return decodeURI(matches[1]);
        } catch (e) { }
    }
    return null;
}

// [[User:ais523/bracketmatch.js]] - Colour matching brackets in a copy of the edit box.
// By [[User:ais523]], on a suggestion by [[User:Absidy]].
 
addOnloadHook(function(){
  var p=document.getElementById('wikiPreview');
  if(p==null) p=document.getElementById('viewsourcetext');
  if(p)
    p.innerHTML+="<div id='bm_parseres'><a href='javascript:bm_parsebrackets();'>Parse</a></div>";
  try
  {
    var edh=document.getElementsByClassName('editHelp')[0];
    if(bm_useparsebutton)
      edh.innerHTML='<input id="bm_parsebutton" name="bm_parsebutton"'+
        ' type="button" tabindex="6" value="Show parsed" title="Show how braces parse in this text" '+
        ' onclick="bm_showparsed()"/>&nbsp;&nbsp;'+edh.innerHTML;
  } catch(x) {}
});
 
function bm_parsebrackets()
{
  var t=document.getElementById('wpTextbox1').value;
  var a=sajax_init_object();
  var p='action=expandtemplates&generatexml=1&format=json&callback=bm_callback&text='+encodeURIComponent(t);
  a.open('POST', wgServer+wgScriptPath+'/api.php');
  a.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  a.setRequestHeader("Content-length", p.length);
  a.setRequestHeader("Connection", "close");
  a.onreadystatechange=function(){bm_apirespond(a)};
  a.send(p);
}
 
function bm_showparsed()
{
  bm_parsebrackets();
  return 0;
}
 
function bm_apirespond(a)
{
  try
  {
    if(a.readyState==4)
      eval(a.responseText);
  }
  catch(e)
  {
    document.getElementById('bm_parseres').innerHTML=
      "Could not parse due to a server error. <a href='javascript:bm_parsebrackets();'>Parse</a>";
  }
}
 
var colang;
 
function bm_hexdigit(n)
{
  var i=Math.floor(n);
  if(i<10) return i+'';
  if(i==10) return 'A';
  if(i==11) return 'B';
  if(i==12) return 'C';
  if(i==13) return 'D';
  if(i==14) return 'E';
  if(i==15) return 'F';
}
 
function bm_tohex(n)
{
  var i=Math.floor(n);
  return bm_hexdigit(i/16)+bm_hexdigit(i%16);
}
 
function bm_gencol(ang)
{
  var r=Math.sin(ang)+1;
  var g=Math.sin(ang+3.14159*2/3)+1;
  var b=Math.sin(ang-3.14159*2/3)+1;
  return bm_tohex(r*127.5)+bm_tohex(g*127.5)+bm_tohex(b*127.5);
}
 
function bm_callback(o)
{
  var subs={"tplarg":"{{{",
            "/tplarg":"}}}",
            "template":"{{",
            "/template":"}}",
            "part":"|",
            "ext":"&"+"lt;",
            "/attr":"&"+"gt;",
            "attr/":"&"+"gt;"};
  var h=o.parsetree["*"].split("<");
  var i=h.length;
  var r;
  var n;
  var sp=0;
  var st=new Array();
  var col;
  colang=0;
  while(--i)
  {
    col="";
    n=1;
    h[i]=h[i].split(">");
    h[i][0]=h[i][0].split(" ");
    r=subs[h[i][0][0]];
    if(r==undefined) r="";
    if(r=='}}}'||r=='}}')
    {
      st[sp]=bm_gencol(colang);
      col=st[sp];
      sp++;
      colang+=2.4; //golden angle in radians, approx
    }
    else if(r=='{{{'||r=='{{')
    {
      sp--;
      col=st[sp];
      n=2;
    }
    if(col!="")
      r="<font color='#"+col+"' id='bm_f"+col+n+"' onclick='bm_highlight(\""+col+"\",\"black\")'>"+r+"</font>";
    h[i][0]=r;
    h[i]=h[i].join("");
  }
  document.getElementById('bm_parseres').innerHTML=
    "<div style='border:1px solid blue'><tt>"+h.join("").split("\n").join("<br />")+
    "</tt></div><div><a href='javascript:bm_parsebrackets();'>Parse</a></div>";
}
 
function bm_highlight(x,c)
{
  document.getElementById('bm_f'+x+'1').style.backgroundColor=c;
  document.getElementById('bm_f'+x+'2').style.backgroundColor=c;
  if(c=="black")
    window.setTimeout("bm_highlight('"+x+"','transparent')",3000);
}
 
//test: {{{a|b}}} {{a|b}} {{c|{{e|a=b|3=c}}|f}}<imagemap type=c>abc</imagemap>
//test: <i>f</i><nowiki>g</nowiki><includeonly>h</includeonly>
//test: <noinclude>i</noinclude> {{{{{{{{j}}}}}}}}
/* test:
{{startofline}}
*/

importScript('User:Dr pda/persondata.js'); //[[User:Dr pda/persondata.js]]

/* Disambiguation lookup script, version [0.2.8]
Originally from: http://en.wikipedia.org/wiki/User:Splarka/dabfinder.js
 
Notes:
* Uses the API using head/appendchild(script) and callback to avoid ajax.
* Alt command finds and hilights redirects with simple CSS append (class="mw-redirect").
* Per http://svn.wikimedia.org/viewvc/mediawiki?view=rev&revision=37270 we are limited to 500 subtemplates
** The query-continue seems to work fine even as a generator. Built a re-query system to do this automatically.
 
Operation:
* Adds portlet button (or works with URI parameter &finddab=true)
** Makes call to MediaWiki:Disambiguationspage links, generates array of these.
*** Makes call to generator=links / prop=templates on page title.
**** Builds array of registered links that link to disambiguation pages (that contain a disambiguation template).
***** Iterates over all <a> link objects on page, matching any that link to disambiguation, and applies green border.
***** .dablink descendant links are given a dashed border, all other found links are given a solid border.
*** Repeats call with tlcontinue if more than 500 templates have been returned in previous query.
 
This is a bit messy but at the time was the easiest and most thorough way to do it I could think of.
Of course, a bot might be much more efficient, but this is handy for quick on-the-fly live checking.
 
To do:
* test it
* centralized link list in contentSub?
* test unicode support
*/
 
var dabnames = new Array();
var dabfound = 0;
if(wgNamespaceNumber != -1) addOnloadHook(findDABsButton)
function findDABsButton() {
  if(!queryString('oldid') && !queryString('diff') && (wgAction == 'view' || wgAction == 'purge')) {
    addPortletLink('p-tb','javascript:findDABs()','Find disambiguations','t-dab');
    if(queryString('finddab')=='true') findDABs();
  }
  addPortletLink('p-tb','javascript:findRDRs()','Find redirects','t-rdr');
  if(queryString('findrdr')=='true') findRDRs();
}
 
function findRDRs() {
  appendCSS('.mw-redirect {background-color: #ffff00;}\n#t-rdr {background-color:#ffff00;}');
  document.getElementById('t-rdr').appendChild(document.createTextNode('\nRedirects hilighted, but don\'t '));
 
  if(wgServer != 'http://en.wikipedia.org' && wgScriptPath != '/wikipedia/en/w') return //en.wp policy
  var a = document.createElement('a');
  a.setAttribute('href','http://en.wikipedia.org/wiki/Wikipedia:Redirect#Do_not_.22fix.22_links_to_redirects_that_are_not_broken');
  a.appendChild(document.createTextNode('fix them.'));
  document.getElementById('t-rdr').appendChild(a);
}
 
function findDABs() {
  var dab = document.getElementById('t-dab');
  if(dab) injectSpinner(dab,'dab');
  var url = wgScriptPath + '/api.php?maxage=86400&smaxage=86400&action=query&prop=links&pllimit=500&tlnamespace=10&indexpageids&format=json&callback=findDABsCB&titles=MediaWiki:Disambiguationspage';
  importScriptURI(url);
}
 
function findDABsCB(obj) {
  if(!obj['query'] || !obj['query']['pages'] || !obj['query']['pageids']) return
  var links = obj['query']['pages'][obj['query']['pageids'][0]]['links']
  if(!links) return
  for(var i=0;i<links.length;i++) {
    dabnames.push(links[i]['title']);
  }
  findDABsQuery();
}
 
function findDABsQuery(qcont) {
  var url = wgScriptPath + '/api.php?maxage=300&smaxage=300&action=query&redirects&generator=links&gpllimit=500&prop=templates&tllimit=500&indexpageids&format=json&callback=findDABlinksCB&titles=' + encodeURIComponent(wgPageName);
  if(qcont) url += '&tlcontinue=' + encodeURIComponent(qcont)
  importScriptURI(url);
}
 
function findDABlinksCB(obj) {
  var dablinks = new Array();
  if(!obj['query'] || !obj['query']['pages'] || !obj['query']['pageids']) return
  appendCSS('.dablink-found {border: 2px solid #00ff00}\n .dablink .dablink-found {border:2px dashed #00ff00}');
 
  var ids = obj['query']['pageids'];
  var links = new Array()
  for(var i=0;i<ids.length;i++) {
    var templates = obj['query']['pages'][ids[i]]['templates'];
    if(!templates) continue
    for(var j=0;j<templates.length;j++) {
      var tpl = templates[j]['title'];
      for(var k=0;k<dabnames.length;k++) {
        if(tpl == dabnames[k]) {
          dablinks.push(obj['query']['pages'][ids[i]]['title']);
          continue;
        }
      }
    }
  }
  if(obj['query']['redirects']) {
    var dablen = dablinks.length;   //don't iterate over additions.
    var redirects = obj['query']['redirects'];
    if(redirects) {
      for(var i=0;i<redirects.length;i++) {
        for(var j=0;j<dablen;j++) {
          if(obj['query']['redirects'][i]['to'] == dablinks[j]) {
            dablinks.push(obj['query']['redirects'][i]['from']);
            continue;
          }
        }
      }
    }
  }
  var docobj = document.getElementById('bodyContent') || document.getElementById('content') || document.body;
  var links = docobj.getElementsByTagName('a')
  for(var i=0;i<links.length;i++) {
    for(var j=0;j<dablinks.length;j++) {
      //to match API: "Foo (bar)" with href: "/wiki/Foo_%28bar%29", have to do some hacky string manipulation
      //should now work with parenthesis, unicode?
      var dablink = dablinks[j].replace(/ /g,'_');
      var chklink = (links[i].hasAttribute('href')) ? links[i].getAttribute('href', 2).replace(/\#.*/,'') : ''
      chklink = chklink.replace(wgArticlePath.replace(/\$1/,''),'');
      chklink = decodeURIComponent(chklink);
      if(chklink == dablink && links[i].className.indexOf('dablink-found') == -1) {
        links[i].className += ' dablink-found';
        dabfound++;
      }
    }
  }
 
  var dab = document.getElementById('t-dab');
  if(obj['query-continue'] && obj['query-continue']['templates']) {
    if(dab) {
      dab.appendChild(document.createElement('br'));
      dab.appendChild(document.createTextNode('more...'));
    }
    findDABsQuery(obj['query-continue']['templates']['tlcontinue']);
  } else {
    if(dab) {
      removeSpinner('dab');
      dab.appendChild(document.createElement('br'));
      if(dabfound > 0) {
        var span = document.createElement('span');
        span.appendChild(document.createTextNode(dabfound + ' links to disambiguation pages found.'));
        span.className = 'dablink-found';
        dab.appendChild(span);
      } else {
        dab.appendChild(document.createTextNode('No disambiguation links found.'));
      }
    } else {
      alert(dabfound + ' links to disambiguation pages found.');
    }
  }
}
 
function queryString(p) {
  var re = RegExp('[&?]' + p + '=([^&]*)');
  var matches;
  if (matches = re.exec(document.location)) {
    try { 
      return decodeURI(matches[1]);
    } catch (e) {
    }
  }
  return null;
}