User:Tqbf/monobook.js

From Wikipedia, the free encyclopedia

If a message on your talk page led you here, please be wary of who left it. The code below could contain malicious content capable of compromising your account; if your account appears to be compromised, it will be blocked. If you are unsure whether the code is safe, you can ask at the appropriate village pump.
Note: After saving, you have to bypass your browser's cache to see the changes. In Internet Explorer and Firefox, hold down the Ctrl key and click the Refresh or Reload button. Opera users have to clear their caches through Tools→Preferences, see the instructions for Opera. Konqueror and Safari users can just click the Reload button.
// Simplified edit section 0 ([[User:ais523/editsection0tab.js]])
// Loosely based on [[Wikipedia:WikiProject User scripts/Scripts/Add edit section 0]]
// <source lang="javascript">
addOnloadHook(function()
{
  var x=document.getElementById('ca-history');
  if(x!=null)
    addPortletLink('p-cactions', wgServer+wgScript+"?title="+encodeURIComponent(wgPageName)+
                                 "&action=edit&section=0", '0', 'ca-edit-0',
                                 'Edit the lead section of this page', '0', x);
});
// </source>
// [[Category:Wikipedia scripts]]
 
// This will add an [edit] link at the top of all pages except preview pages and the main page
// by User:Pile0nades
 
// Add an [edit] link to pages
addOnloadHook(function () {
 // if this is preview page or generated page, stop
 if(
 document.getElementById("wikiPreview") ||
 document.getElementById("histlegend‎") ||
 document.getElementById("difference‎") ||
 document.getElementById("watchdetails") ||
 document.getElementById("ca-viewsource") ||
 window.location.href.indexOf("/wiki/Special:") != -1
 ) {
 if(window.location.href.indexOf("&action=edit&section=0") != -1) {
 document.getElementById("wpSummary").value = "/* Intro */ ";
 }
 return;
 };
 
 // get the page title
 var pageTitle = wgPageName;
 
 // create div and set innerHTML to link
 var divContainer = document.createElement("div");
 divContainer.innerHTML = '<div class="editsection">[<a href="/w/index.php?title='+pageTitle+'&action=edit&section=0" title="Edit section: '+pageTitle+'">edit intro</a>]</div>';
 
 // insert divContainer into the DOM below the h1
 if(window.location.href.indexOf("&action=edit") == -1) {
 document.getElementById("content").insertBefore(divContainer, document.getElementsByTagName("h1")[0]);
 }
 
});
 
/////////////////////////////////////////
// By Alek Storm
// Please see talk page for instructions
/////////////////////////////////////////
 
var body; // shortcut for body node
var xmlhttp; // XMLHTTPRequest object
var startNode; // div that includes section header and edit link
var editSec; // edit link
var editForm; // spliced edit form
var preview; // spliced preview or diff content
var oldContent; // original content of section
var xmlhttpDone = false; // kludge to prevent multiple calls to callback
 
importScript("User:Supadawg/util.js");
 
function inc(path) {
  var lt = String.fromCharCode(60);
  var gt = String.fromCharCode(62);
  document.writeln(lt+'script type="text/javascript" src="/w/index.php?title='+path+'&action=raw&ctype=text/javascript&dontcountme=s"'+gt+lt+'/script'+gt);
}
 
function initSecEdit()
{
  body = document.getElementsByTagName("body")[0];
 
  // apply to all divs of class "editsection"
  var editSecs = document.getElementsByTagName("span");
  var secCount = 1;
  var pagetitleRe=/\/(wiki\/|w\/index\.php\?title=)([^&?]*)/; // from [Wikipedia:WikiProject User scripts/Techniques]
  for ( var i = 0; i < editSecs.length; i++ ) {
    if ( editSecs[i].getAttribute("class") == "editsection" ) {
      for ( var k = 0; k < editSecs[i].childNodes.length; k++ ) {
        if ( editSecs[i].childNodes[k].nodeName == "A" ) {
          // grab editing uri, escape it, then put it back in
          var editURI = "http://en.wikipedia.org/w/index.php?title="+encodeURIComponent2(pagetitleRe.exec(decodeURI(editSecs[i].childNodes[k].getAttribute("href")))[2]).replace(/\"/gi, "%22").replace(/\'/gi, "%27")+"&action=edit&section="+secCount;
          // give it a unique id
          editSecs[i].childNodes[k].setAttribute( "id", "editSection"+secCount );
          // swap the href with a function call, passing the original href as the second parameter
          editSecs[i].childNodes[k].setAttribute( "href", "javascript:editSection( document.getElementById('editSection" + secCount + "'), '"+editURI+"' );" );
          secCount++;
        }
      }
    }
  }
}
 
// called on click of section edit link
function editSection( elem, editURI )
{
  cancelEdit(); // get rid of any other sections being edited
  editSec = elem;
  startNode = elem.parentNode.parentNode;
 
  // initiate xmlhttprequest for section edit page
  xmlhttpDone = false;
  xmlhttp = null // kludge
  xmlhttp = createXMLHTTP( "GET", editURI, stateChange );
}
 
// put raw input returned from XMLHTTPRequest into a div so we can grab specific elements
function makeDiv( rawHTML )
{
  var div = createNode( body, "div", {style: "visibility: hidden; position: absolute;"} );
  div.innerHTML = rawHTML.replace(/<script[^>]*><\/script>/gi, ""); // if script tags are placed into the DOM, they force reload of files, and nasty things happen
  return div;
}
 
function isHTag( node )
{
  return node.nodeName.charAt(0) == 'H' && !isNaN( parseInt( node.nodeName.charAt(1) ) );
}
 
// callback for onclick of an edit link
function stateChange()
{
  if ( xmlhttp && xmlhttp.readyState == 4 ) {
    if ( xmlhttp.status == 200 ) {
      if ( xmlhttpDone )
        return;
      xmlhttpDone = true;
 
      // store old content of section - loop until we hit header of same spot in hierarchy
      if ( !oldContent ) {
        oldContent = makeDiv("");
        var curElem = startNode.nextSibling;
        while ( curElem ) {
          var hitSiblingSection = false;
          if ( isHTag( curElem ) ) {
            for ( var i = 0; i < curElem.childNodes.length; i++ ) {
              if ( curElem.childNodes[i].nodeName == "SPAN"
                   && curElem.childNodes[i].getAttribute("class") == "editsection"
                   && parseInt( curElem.nodeName.charAt(1) ) <= parseInt( startNode.nodeName.charAt(1) ) )
                  hitSiblingSection = true;
            }
          }
          else if ( curElem.nodeName == "DIV" && curElem.getAttribute("class") == "printfooter" )
            break;
 
          if ( hitSiblingSection )
            break;
          var nextElem = curElem.nextSibling;
          oldContent.appendChild( curElem );
          curElem = nextElem;
        }
      }
      else
        removeNode( oldContent );
 
      var div = makeDiv( xmlhttp.responseText );
      editForm = $("editform");
      // change onclick of preview and diff buttons to our function
      $("wpPreview").setAttribute( "type", "button" );
      $("wpPreview").setAttribute( "onclick", "javascript:getEditData( previewChanged, $('wpPreview') );" );
      $("wpDiff").setAttribute( "type", "button" );
      $("wpDiff").setAttribute( "onclick", "javascript:getEditData( diffChanged, $('wpDiff') );" );
      insertAfter( editForm, startNode );
      removeNode( div );
 
      editSec.setAttribute( "oldHref", editSec.getAttribute("href") );
      editSec.setAttribute( "href", "javascript:cancelEdit();" );
      editSec.innerHTML = "cancel";
    }
    else
      alert("Problem retrieving data - status: "+xmlhttp.status);
  }
}
 
// firefox hack, not sure if this is a problem in other browsers
function encodeURIComponent2( content )
{
  // from [http://en.wikipedia.org/wiki/User:Topaz/wputil.js]
  content = content.replace(/\&lt\;/gi, "<");
  content = content.replace(/\&gt\;/gi, ">");
  content = content.replace(/\&quot\;/gi, "\"");
  content = content.replace(/\&amp\;/gi, "&");
  return encodeURIComponent( content );
}
 
// encode differently based on type of form element
function field2Post( node, allowButton )
{
  var reqBody = "";
  switch ( node.nodeName ) {
    case "TEXTAREA":
      reqBody += "&"+node.getAttribute("name")+"="+encodeURIComponent2( node.value );
      break;
    case "INPUT":
      var inputType = node.getAttribute("type");
      if ( inputType == "checkbox" ) {
        if ( node.checked )
          reqBody += "&"+node.getAttribute("name")+"=on"
      }
      else if ( allowButton || (inputType != "submit" && inputType != "button") )
        reqBody += "&"+node.getAttribute("name")+"="+encodeURIComponent2( node.value );
      break;
    case "DIV":
      reqBody += form2Post( node, false );
      break;
  }
  return reqBody;
}
 
// manually encodes a form element for XMLHTTPRequest
function form2Post( node )
{
  var reqBody = "";
  for ( var i = 0; i < node.childNodes.length; i++ )
    reqBody += field2Post( node.childNodes[i], false );
  return reqBody;
}
 
// get preview or diff data
function getEditData( callback, clickedBut )
{
  xmlhttpDone = false;
  xmlhttp = null; // kludge
  var action = editForm.getAttribute("action");
  xmlhttp = createXMLHTTP( "POST", "http://en.wikipedia.org"+action, callback, {
    body: form2Post( editForm ) + field2Post( clickedBut, true ),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Referer": "http://en.wikipedia.org" + action.substring( 0, action.indexOf('&') ) + "&action=edit&section="+(parseInt(editSec.getAttribute("id").substring(11))+1)
    }
  } );
}
 
// callback for preview data
function previewChanged()
{
  if ( xmlhttp && xmlhttp.readyState == 4 ) {
    if ( xmlhttp.status == 200 ) {
      if ( xmlhttpDone )
        return;
      xmlhttpDone = true;
      var div = makeDiv( xmlhttp.responseText );
      if ( preview )
        removeNode( preview );
      preview = $("wikiPreview");
      insertAfter( preview, startNode );
      removeNode( div );
    }
    else
      alert("Problem retrieving data - status: "+xmlhttp.status);
  }
}
 
// callback for diff data
function diffChanged()
{
  if ( xmlhttp && xmlhttp.readyState == 4 ) {
    if ( xmlhttp.status == 200 ) {
      if ( xmlhttpDone )
        return;
      xmlhttpDone = true;
      var div = makeDiv( xmlhttp.responseText );
      if ( preview )
        removeNode( preview );
      preview = $("wikiDiff");
      insertAfter( preview, startNode );
      removeNode( div );
    }
    else
      alert("Problem retrieving data - status: "+xmlhttp.status);
  }
}
 
// remove form and preview or diff data
function cancelEdit()
{
  if ( preview )
    removeNode( preview );
  preview = null;
  if ( editForm )
    removeNode( editForm );
  editForm = null;
  if ( oldContent ) {
    oldContent.setAttribute( "style", "position: static; visibility: visible;" );
    insertAfter( oldContent, startNode );
  }
  oldContent = null;
  if ( editSec ) {
    editSec.setAttribute( "href", editSec.getAttribute("oldHref") );
    editSec.innerHTML = "edit";
  }
}
 
addEventListener( "load", initSecEdit, false );
 
// CHECK THAT I'VE REMEMBERED TO SIGN TALK PAGES AND IF SURE DO IT AUTOMATIC:
// *** aut. signing / (automatische Unterschrift) *** [[User:Olliminatore/signing.js]]
// created 23.04.2006 by [[User:Olliminatore]]
// updated 23.04.2006 by [[:en:User:Ilmari Karonen]]
// current version 1.56 13.03.2007
// Interwiki <noinclude>[[de:User:Olliminatore/signing.js]]</noinclude>
//<pre><nowiki>
 
String.prototype.trim = function(){return this.replace(/^\s*|\s*$/g,"")};
 
if (typeof usersignature == 'undefined') usersignature = ' --\~\~\~\~\n';
 
if (typeof regpages == 'undefined') { // list of all none talk pages
    var regpages = [
    ':Village pump',
    ':Articles for deletion',
    ':Requests for ',
    ':Reference desk',
    ':Deletion review',
    ':Templates for deletion',
    '.*noticeboard.*',
    ':checkuser',
    ':arbitration',
    ':feedback',
    ':page protection',
    'mediation)',
    ':Bot requests',
    ':Help desk',
    ':Editor review',
    ':Adminship survey',
    ':Cleanup',
    ':Miscellany for deletion',
    ':New contributors\' help page',
    ':Media copyright questions'
    ];
} 
 
    // regarded pages type encoded
if (wgCanonicalNamespace.match(/talk$/i)) var regpages = "";
for (p in regpages) if (wgPageName.indexOf(regpages[p]) != -1){regpages=false; break}
 
if (!regpages) 
addOnloadHook(function(){
    if (!(window.editform = document.forms['editform'])) return;
    // Add a new checkbox to the Wiki editOptions.
    sigBox = document.createElement("input");
    sigBox.setAttribute('type','checkbox');
    sigBox.setAttribute('name','wpSigning');
    sigBox.setAttribute('id','wpSigning');
    sigBox.setAttribute('checked','checked');
    sigBox.defaultChecked=true;
    neuB = document.createElement("label");
    neuB.appendChild(sigBox);
    neuB.appendChild(document.createTextNode("Sign"));
    neuB.setAttribute('for','wpSigning');
    neuB.setAttribute('title','Sign this edit automatic.');
 
    function setSigBox() { // switch enable box
        if (editform.wpMinoredit.checked) sigBox.setAttribute('disabled','disabled');
        else sigBox.removeAttribute('disabled');
    };
 
    var txtarea=editform.elements['wpTextbox1'];
    var txtOld=txtarea.value.trim();
    // txtOld_l=txtOld.length
    var txtOldEnd=txtOld.slice(-24);
    var sig = /~{3}/g;
 
    if (!tNode){
        //editform.insertBefore(neuB, editform.elements['wpWatchthis']); // maybe FIXME: raised an NS_DOM_ERR!
        var tNode = editform.elements['wpMinoredit'].parentNode;  // DOM workaround!?
        tNode.divs = tNode.getElementsByTagName("DIV");
        tNode.divs = tNode.divs.item(tNode.divs.length-1); // last div
        tNode.insertBefore(neuB, tNode.divs);
        setSigBox();
    }
 
    function doSign(event){
        if(editform.onsubmit==''){ // only once!
            removeEvent(editform.wpSave,"click",doSign);
            removeEvent(editform.wpPreview,"click",doSign);
        }
        if(editform.onsubmit=='') removeEvent(editform.wpSave,"click",doSign); // only once!
        if(editform.wpMinoredit.checked || !sigBox.checked) return;
        txtarea.focus();
        var cOld = txtOld.match(/<nowiki>.*?~{3}.*?<\/nowiki>/g); // exception for nowiki
        if (cOld) cOld = cOld.length;
        cNew = txtarea.value.match(sig); if (cNew) cNew = cNew.length;
        if (cNew > cOld){ // if there are a sign, check for true
            var cNew2 = txtarea.value.match(/\{\{subst\:unsig.*?~{3}\}\}/); // exception for Template:unsigned
            cNew -= (cNew2)?cNew2.length:0;
        }
        if(cNew <= cOld){ // if nothing then search a set position
            txt=txtarea.value.trim();
            txtEnd=txt.slice(-24);
            if(txtOldEnd!=txtEnd) return txtarea.value = txt + usersignature;  // aut. underwrite
            else { // post between
                pos = getCaretPos(txtarea);
                pos = txt.indexOf('\n', pos); // go to the post-end
                txtEnds = txt.substr(pos,24).replace(/(^\s*)/,""); // after
                txtpEnds = txt.slice(pos-18,pos); // before
                oldp = txtOld.indexOf(txtEnds);
                if(oldp!=-1 && oldp < pos - 3 && txtOld.indexOf(txtpEnds+RegExp.$1+txtEnds)==-1) // if some added
                    return txtarea.value = txt.slice(0,pos).trim() + usersignature + txt.slice(pos+1);
            }
         // FIXME: then the edit-end is not found!?
        }
        else if(!sig.test(txtOld) || cOld < cNew) return;
        if (event) event=(window.Event)? event.target: event.srcElement;
        if (event.name == 'wpPreview') return; // not for preview
        return editform.onsubmit=new Function("editform.onsubmit='';"
          +"return confirm('No signing was found. Continue anyway?')"); //warn if saving without signature
    };
    addEvent(editform.wpSave,"click", doSign);
    addEvent(editform.wpPreview,"click", doSign);
    addEvent(editform.wpMinoredit,"click", setSigBox);
});
 
function getCaretPos(txtObj){
    if (txtObj.setSelectionRange) return txtObj.selectionStart; // NS like
    else if(!document.selection) return 0;  // not IE like
    var c="\001", pos=0;
    var range=document.selection.createRange();
    var txt=range.text, dul=range.duplicate();
    dul.moveToElementText(txtObj);
    range.text=txt+c;
    pos=(dul.text.indexOf(c));
    range.moveStart('character',-1);
    range.text="";
    return pos;
};
 
/* add/removeEvent Original idea by John Resig
 Tweaked by Scott Andrew LePera, Dean Edwards and Peter-Paul Koch
 Fixed for IE by Tino Zijdel (crisp) @date 2005-10 */
function addEvent(obj,type,fn){if(obj.addEventListener){obj.addEventListener(type,fn,false)}else if(obj.attachEvent){var eProp=type+fn;obj["e"+eProp]=fn;obj[eProp]=function(){obj["e"+eProp](window.event)};obj.attachEvent("on"+type,obj[eProp])}else{obj['on'+type]=fn}};
function removeEvent(obj,type,fn){if(obj.removeEventListener){obj.removeEventListener(type,fn,false)}else if(obj.detachEvent){var eProp=type+fn;obj.detachEvent("on"+type,obj[eProp]);obj['e'+eProp]=null;obj[eProp]=null}else{obj['on'+type]=null}};
 
// *** end *** </nowiki></pre>
 
/**** afd helper ****/
document.write('<script type="text/javascript"' +
  'src="http://en.wikipedia.org/w/index.php?title=User:Jnothman/afd_helper/' +
  'script.js&action=raw&ctype=text/javascript&dontcountme=s"></script>');
 
/* This is to keep track of who is using this extension: [[User:Jnothman/afd_helper/script.js]] */
 
importScript('User:AzaToth/twinkle.js');