Jump to content

User:Danger/monobook.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Danger (talk | contribs) at 06:56, 19 January 2011 (+script). 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.
//Please adjust the following variables according to when you want to end your break:
var year = 2007; //YYYY
var month = 10; //MM
var day = 29; //DD
var hour = 01; //HH
var minute = 52; //MM
var second = 30; //SS 

function EnforceWikiBreak() {
    var currentdate = new Date();
    var enforced_break_end = new Date(year,changemonth(),day,hour,minute,second);
    if (currentdate > enforced_break_end) {
      // alert ("Welcome back from your enforced wikibreak!");
    } else {
      alert ("Enforced wikibreak until " + enforced_break_end.toLocaleString() + " (currently " + currentdate.toLocaleString() + "). Bye!");
      window.location.href = ("http://"+document.location.host+"/w/index.php?title=Special:Userlogout&returnto=Main_Page");
    }
}

function changemonth() {
//thing to subtract 1 from the month. you can't use month-1 because it removes the '0' from the front
if(month==01) return 00;
if(month==02) return 01;
if(month==03) return 02;
if(month==04) return 03;
if(month==05) return 04;
if(month==06) return 05;
if(month==07) return 06;
if(month==08) return 07;
if(month==09) return 08;
if(month==10) return 09;
if(month==11) return 10;
if(month==12) return 11;
return 00;
}

addOnloadHook(function() { EnforceWikiBreak(); });

/* </nowiki></pre> */

importScript('User:AzaToth/twinkle.js');

importScript('User:Cameltrader/Advisor.js');

*/
//Wikipedia:WikiProject User scripts | Scripts
 
function format() {
    var txt = document.editform.wpTextbox1;
    txt.value = catFixer(txt.value);
    txt.value = entities(txt.value);
    txt.value = fixheadings(txt.value);
    txt.value = fixsyntax(txt.value);
    txt.value = linkfixer(txt.value, false);
    //txt.value = imagefixer(txt.value);
    txt.value = whitespace(txt.value);
    txt.value = linksimplifyer(txt.value);
    txt.value = trim(txt.value);
}
 
function whitespace(str){
    str = str.replace(/\t/g, " ");
 
    str = str.replace(/^ ? ? \n/gm, "\n");
    str = str.replace(/(\n\n)\n+/g, "$1");
    str = str.replace(/== ? ?\n\n==/g, "==\n==");
    str = str.replace(/\n\n(\* ?\[?http)/g, "\n$1");
 
    str = str.replace(/^ ? ? \n/gm, "\n");
    str = str.replace(/\n\n\*/g, "\n*");
    str = str.replace(/[ \t][ \t]+/g, " ");
    str = str.replace(/([=\n]\n)\n+/g, "$1");
    str = str.replace(/ \n/g, "\n");
 
    //* bullet points
    str = str.replace(/^([\*#]+) /gm, "$1");
    str = str.replace(/^([\*#]+)/gm, "$1 ");
 
    //==Headings==
    str = str.replace(/^(={1,4}) ?(.*?) ?(={1,4})$/gm, "$1$2$3");
 
    //dash — spacing
    str = str.replace(/ ?(–|&#150;|&ndash;|&#8211;|&#x2013;) ?/g, "$1");
    str = str.replace(/ ?(—|&#151;|&mdash;|&#8212;|&#x2014;) ?/g, "$1");
    str = str.replace(/([^1-9])(—|&#151;|&mdash;|&#8212;|&#x2014;|–|&#150;|&ndash;|&#8211;|&#x2013;)([^1-9])/g, "$1 $2 $3");
 
    return trim(str);
}
 
function entities(str){
    //str = str.replace(//g, "");
    str = str.replace(/&#150;|&#8211;|&#x2013;/g, "&ndash;");
    str = str.replace(/&#151;|&#8212;|&#x2014;/g, "&mdash;");
   // str = str.replace(/(cm| m|km|mi)<sup>2</sup>/g, "$1²");
    str = str.replace(/&sup2;/g, "²");
    str = str.replace(/&deg;/g, "°");
 
    return trim(str);
}
 
//Fix ==See also== and similar section common errors.
function fixheadings(str)
{
  if( !str.match(/= ?See also ?=/) )
    str = str.replace(/(== ?)(see also:?|related topics:?|related articles:?|internal links:?|also see:?)( ?==)/gi, "$1See also$3");
 
  str = str.replace(/(== ?)(external links?:?|outside links?|web ?links?:?|exterior links?:?)( ?==)/gi, "$1External links$3");
  str = str.replace(/(== ?)(references?:?)( ?==)/gi, "$1References$3");
  str = str.replace(/(== ?)(sources?:?)( ?==)/gi, "$1Sources$3");
  str = str.replace(/(== ?)(further readings?:?)( ?==)/gi, "$1Further reading$3");
 
  return str;
}
 
function catFixer(str){
    str = str.replace(/\[\[ ?[Cc]ategory ?: ?/g, "[[Category:");
 
    return trim(str);
}
 
//fixes many common syntax problems
function fixsyntax(str)
{
  //replace html with wiki syntax
  if( !str.match(/'<\/?[ib]>|<\/?[ib]>'/gi) )
  {
    str = str.replace(/<i>(.*?)<\/i>/gi, "''$1''");
    str = str.replace(/<b>(.*?)<\/b>/gi, "'''$1'''");
  }
  str = str.replace(/<br\/>/gi, "<br />");
  str = str.replace(/<br>/gi, "<br />");
 
  return trim(str);
}
 
//formats links in standard fashion
function linkfixer(str, checkImages)
{ 
  str = str.replace(/\]\[/g, "] [");
  var m = str.match(/\[?\[[^\]]*?\]\]?/g);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var x = m[i].toString();
      var y = x;
 
      //internal links only
      if ( !y.match(/^\[?\[http:\/\//i) && !y.match(/^\[?\[image:/i) )
      {
        if (y.indexOf(":") == -1 && y.substr(0,3) != "[[_" && y.indexOf("|_") == -1)
        {
          if (y.indexOf("|") == -1)
            y = y.replace(/_/g, " ");
          else
            y = y.replace( y.substr(0, y.indexOf("|")), y.substr(0, y.indexOf("|")).replace(/_/g, " "));
        }  
 
        y = y.replace(/ ?\| ?/, "|").replace("|]]", "| ]]");
 
      }
 
      str = str.replace(x, y);
    }
  }
 
  //repair bad internal links
  str = str.replace(/\[\[ ?([^\]]*?) ?\]\]/g, "[[$1]]");
  str = str.replace(/\[\[([^\]]*?)( |_)#([^\]]*?)\]\]/g, "[[$1#$3]]");
 
  //repair bad external links
  str = str.replace(/\[?\[http:\/\/([^\]]*?)\]\]?/gi, "[http://$1]");
  str = str.replace(/\[http:\/\/([^\]]*?)\|([^\]]*?)\]/gi, "[http://$1 $2]");
 
  return trim(str);
}
 
//fixes images
function imagefixer(str)
{
 
  //remove external images
  str = str.replace(/\[?\[image:http:\/\/([^\]]*?)\]\]?/gi, "[http://$1]");
 
  //fix links within internal images
  var m = str.match(/\[?\[image:[^\[\]]*?(\[?\[[^\]]*?\]*?[^\[\]]*?)*?\]+/gi);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var x = m[i].toString();
      var y = x;
 
      y = y.replace(/^\[\[i/i, "I").replace(/\]\]$/, "");
      y = y.replace(/(\[[^\]]*?)$/, "$1]");
      y = linkfixer(y, true);
      y = "[[" + y + "]]";
 
      str = str.replace(x, y);
    }
  }
 
  return trim(str);
}
 
//simplifies some links e.g. [[Dog|dog]] to [[dog]] and [[Dog|dogs]] to [[dog]]s
function linksimplifyer(str){
  var m = str.match(/\[\[([^[]*?)\|([^[]*?)\]\]/g);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var n_arr = m[i].toString().match(/\[\[([^[]*?)\|([^[]*?)\]\]/);
      var n = n_arr[0];
      var a = n_arr[1];
      var b = n_arr[2];
 
      if (b.indexOf(a) == 0 || b.indexOf(TurnFirstToLower(a)) == 0)
      {
        var k = n.replace(/\[\[([^\]\|]*?)\|(\1)([\w]*?)\]\]/i, "[[$2]]$3");
        str = str.replace(n, k);
      }
    }
  }
 
  str = str.replace(/\[\[([^\]\|]+)\|([^\]\|]+)\]\]([A-Za-z\'][A-Za-z]*)([\.\,\;\:\"\!\?\s\n])/g, "[[$1|$2$3]]$4"); // ' // Help the syntax highlighter...
 
  return str;
}
 
//trim start and end, trim spaces from the end of lines
function trim(str) {
   str = str.replace(/ $/gm, "");
   return str.replace(/^\s*|\s*$/g, "");
}
 
//turns first character to lowercase
function TurnFirstToLower(input) {
  if (input != "")
  {
    var input = trim(input);
    var temp = input.substr(0, 1);
    return temp.toLowerCase() + input.substr(1, input.length);
  }
  else
    return "";
}
 
//entities that should never be unicoded
function noUnicodify(str) {
  str = str.replace(" &amp; ", " & ");
  str = str.replace("&amp;", "&amp;amp;").replace("&amp;lt;", "&amp;amp;lt;").replace("&amp;gt;", "&amp;amp;gt;").replace("&amp;quot;", "&amp;amp;quot;").replace("&amp;apos;", "&amp;amp;apos;");
  str = str.replace("&minus;", "&amp;minus;").replace("&times;", "&amp;times;");
 
  str = str.replace("&nbsp;", "&amp;nbsp;").replace("&thinsp;", "&amp;thinsp;").replace("&shy;", "&amp;shy;");
  str = str.replace("&prime;", "&amp;prime;");
  str = str.replace(/&(#0?9[13];)/, "&amp;$1");
  str = str.replace(/&(#0?12[345];)/, "&amp;$1");
 
  return str;
}
 
addOnloadHook(function () {
  if(document.forms.editform) {
    addPortletLink('p-cactions', 'javascript:format()', 'format', 'ca-format', 'Format article', '', document.getElementById('ca-edit'));
  }
});
 

importScript('Wikipedia:WikiProject User scripts/Scripts/Add LI menu');
importStylesheet('Wikipedia:WikiProject User scripts/Scripts/Add LI menu/css');
importScript('User:Dr_pda/prosesize.js'); //[[User:Dr_pda/prosesize.js]]
importScript('User:AzaToth/twinkle.js');
importScript('Wikipedia:WikiProject Deletion sorting/delsort.js');
importScript('User:Lupin/popups.js'); // see Wikipedia:Tools/Navigation popups

/*

/* If you want to use this script, simply add the following line to your [[Special:Mypage/monobook.js]]:
 
importScript('User:Anomie/util.js');
importScript('User:Anomie/linkclassifier.js'); // Linkback: [[User:Anomie/linkclassifier.js]]
 
* (Please keep the comment so I can see how many people use this). You will also want to
* add some CSS classes, such as those at [[User:Anomie/linkclassifier.css]].
*/
 
/* If you want this to run "on demand" instead of on every page, set "LinkClassifierOnDemand=true" and
 * use addPortletLink() or the like to add a button calling LinkClassifier.onDemand().
 */
 
importScriptURI('http://en.wikipedia.org/w/index.php?title=User:Anomie/util.js&action=raw&ctype=text/javascript');  // for backwards compat
 
 
var LinkClassifier={
    /* This object maps classes to the categories for which to apply them. Values may be an array of strings or a regex. */
    cats:{
        deletion:[
            'Category:All articles proposed for deletion',
            'Category:All books proposed for deletion',
            'Category:All disputed non-free Wikipedia files',
            'Category:All orphaned non-free use Wikipedia files',
            'Category:All replaceable non-free use Wikipedia files',
            'Category:All Wikipedia files with no copyright tag',
            'Category:All Wikipedia files with no non-free use rationale',
            'Category:All Wikipedia files with unknown copyright status',
            'Category:All Wikipedia files with unknown source',
            'Category:Articles for deletion',
            'Category:Articles on deletion review',
            'Category:Candidates for speedy deletion',
            'Category:Candidates for undeletion',
            'Category:Categories for conversion',
            'Category:Categories for deletion',
            'Category:Categories for listifying',
            'Category:Categories for merging',
            'Category:Categories for renaming',
            'Category:Categories for speedy renaming',
            'Category:Categories to be listified then deleted',
            'Category:Miscellaneous pages for deletion',
            'Category:Pending deletions',
            'Category:Redirects for discussion',
            'Category:Stub categories for deletion',
            'Category:Stub template deletion candidates',
            'Category:User categories for discussion',
            'Category:Wikipedia deprecated and orphaned templates',
            'Category:Wikipedia files for deletion',
            'Category:Wikipedia files with unknown source for deletion in dispute',
            'Category:Wikipedia templates for deletion'
        ].sort(),
        disambiguation:[
            'Category:All disambiguation pages'
        ].sort(),
        'set-index':[
            'Category:All set index articles'
        ].sort(),
        'featured-content':[
            'Category:Featured articles',
            'Category:Featured lists',
            'Category:Featured pictures',
            'Category:Featured sounds',
            'Category:Featured videos',
            'Category:Featured portals'
        ].sort(),
        'good-content':[
            'Category:Good articles'
        ].sort(),
        'spoken-articles':[
            'Category:Spoken articles'
        ].sort(),
        stubcls:/^Category:.* stubs$/,
        'nonfree-media':[
            'Category:All non-free media'
        ].sort(),
        unprintworthy:[
            'Category:Unprintworthy redirects',
            'Category:Redirects from other disambiguation',
            'Category:Redirects from unnecessary disambiguation',
            'Category:Redirects from shortcuts',
 
            'Category:Middle-earth redirects from redundant titles', 
            'Category:Hills of Middle-earth', 
            'Category:Lord of the Rings film trilogy', 
            'Category:Middle-earth places', 
            'Category:Mountains of Middle-earth', 
            'Category:Realms of Middle-earth', 
            'Category:Tolkien'
        ].sort(),
        'unprintworthy-shortcut':[
            'Category:Redirects from shortcuts',
        ].sort()
    },
 
    callback:function(r, cc){
        if(!r.query) throw new Error('Bad response');
        if(r['query-continue']){
            for(var k in r['query-continue']){
                for(var k2 in r['query-continue'][k]){
                    cc[k2]=r['query-continue'][k][k2];
                }
            }
            api(cc, arguments.callee);
        }
        r=r.query;
 
        var a=document.getElementById('wikiPreview');
        if(!a) a=document.getElementById('bodyContent');
        if(!a) throw new Error('Huh? No body content?');
        a=a.getElementsByTagName('A');
        if(a.length==0) return;
 
        var redir={};
        var redirlist=[];
        if(r.redirects) for(var i=r.redirects.length-1; i>=0; i--){
            redir[r.redirects[i].from]=r.redirects[i].to;
            redirlist.push(r.redirects[i].from);
        }
        if(redirlist.length>0) api({action:'query', titles:redirlist, prop:'categories', cllimit:'max'}, LinkClassifier.callback);
 
        var cats={};
        var missing={};
        var classes={};
        if(r.pages) for(var i in r.pages){
            missing[r.pages[i].title]=(typeof(r.pages[i].missing)!='undefined');
            if(typeof(r.pages[i].categories)!='undefined'){
                cats[r.pages[i].title]=r.pages[i].categories.map(function(a){ return a.title; }).sort();
            }
            if(typeof(r.pages[i].protection)!='undefined'){
                classes[r.pages[i].title]=[];
                var x={};
                for(var j=r.pages[i].protection.length-1; j>=0; j--){
                    var p='protection-'+r.pages[i].protection[j].type+'-'+r.pages[i].protection[j].level;
                    if(typeof(x[p])=='undefined'){
                        x[p]=1;
                        classes[r.pages[i].title].push(p);
                    }
                    if(r.pages[i].protection[j].expiry=='infinity'){
                        p+='-indef';
                        if(typeof(x[p])=='undefined'){
                            x[p]=1;
                            classes[r.pages[i].title].push(p);
                        }
                    }
                }
            }
            if(typeof(r.pages[i].flagged)!='undefined'){
                if(r.pages[i].lastrevid!=r.pages[i].flagged.stable_revid){
                    classes[r.pages[i].title].push('needs-review');
                }
            }
        }
        Array.forEach(a, function(a){
            if(typeof(a.wikipage)=='undefined') return;
            if(typeof(redir[a.wikipage])!='undefined'){
                addClass(a,'redirect');
                a.wikipage=redir[a.wikipage];
                a.title=a.wikipage;
                if(a.wikipage==(wgCanonicalNamespace?wgCanonicalNamespace+':':'')+wgTitle)
                    addClass(a,'self-redirect');
                if(missing[a.wikipage])
                    addClass(a,'broken-redirect');
            }
            var m=a.href.match(/#.*/);
            if(m){
                a.title=a.title.replace(/#.*/,'')+m[0].replace(/_/g,' ').replace(/\.([0-9A-F][0-9A-F])/gi, function(x,n){ return String.fromCharCode(parseInt(n,16)); });
            }
            if(typeof(classes[a.wikipage])!='undefined'){
                for(var j=classes[a.wikipage].length-1; j>=0; j--)
                    addClass(a,classes[a.wikipage][j]);
            }
            var c1=[];
            if(typeof(cats[a.wikipage])!='undefined'){
                c1=c1.concat(cats[a.wikipage]);
            }
            if(a.wikipage!=a.origwikipage && typeof(cats[a.origwikipage])!='undefined'){
                c1=c1.concat(cats[a.origwikipage]);
            }
            if(c1.length>0){
                c1=c1.sort();
                for(var cls in LinkClassifier.cats){
                    var i1=c1.length-1;
                    var c2=LinkClassifier.cats[cls];
                    if(c2 instanceof RegExp){
                        while(i1>=0){
                            if(c2.test(c1[i1])){
                                addClass(a,cls);
                                break;
                            }
                            i1--;
                        }
                    } else {
                        var i2=c2.length-1;
                        while(i1>=0 && i2>=0){
                            if(c1[i1]==c2[i2]){
                                addClass(a,cls);
                                break;
                            }
                            (c1[i1]>c2[i2])?--i1:--i2;
                        }
                    }
                }
            }
        });
    },
 
    getPageName:function(url){
        var m=url.match(/\/wiki\/([^?#]+)/);
        if(!m) m=url.match(/\/w\/index.php\?(?:.*&)?title=([^&#]+)/);
        if(!m) return '';
        var t=decodeURIComponent(m[1]).replace(/_/g,' ');
        if(t.substr(0,6)=='Image:') t='File:'+t.substr(6);
        if(t.substr(0,11)=='Image talk:') t='File talk:'+t.substr(6);
        if(t.substr(0,8)=='Special:') t='';
        return t;
    },
 
    classifyChildren:function(node){
        var a=node.getElementsByTagName('A');
        if(a.length==0) return;
        var self=LinkClassifier.getPageName(location.href);
        a=Array.map(a, function(a){
            a.wikipage='';
            if(/(^|\s)(external|extiw)(\s|$)/.test(a.className)) return '';
            if(!/(^|\s)(image)(\s|$)/.test(a.className)) a.className+=" nonimage";
            a.wikipage=LinkClassifier.getPageName(a.href);
            if(a.wikipage==self) a.wikipage='';
            a.origwikipage=a.wikipage;
            return a.wikipage;
        }).sort().filter(function(e,i,a){
            return e!=='' && (i==0 || a[i-1]!==e);
        });
        while(a.length>0){
            api({action:'query', titles:a.splice(0,50), prop:'categories|info|flagged', redirects:1, cllimit:'max', inprop:'protection'}, LinkClassifier.callback);
        }
    },
 
    onLoad:function(){
        if(window.AJAXPreview) window.AJAXPreview.AddOnLoadHook(LinkClassifier.classifyChildren);
        LinkClassifier.onDemand();
    },
 
    onDemand:function(){
        var node=document.getElementById('wikiPreview');
        if(!node) node=document.getElementById('bodyContent');
        if(node) LinkClassifier.classifyChildren(node);
    }
};
 
if(!window.LinkClassifierOnDemand){
    if(doneOnloadHook) LinkClassifier.onLoad(); //if imported dynamically
    else addOnloadHook(LinkClassifier.onLoad);
}

importScript('User:Ale_jrb/Scripts/csdhelper.js');  //[[User:Ale_jrb/Scripts]]