Jump to content

User:Horologium/vector.js

From Wikipedia, the free encyclopedia
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.
/*
 * Script to add namespace selector to Special:LinkSearch
 * By MastCell
 * Leverages code from a variety of sources, including ^demon's old CSD-rationale script
 * ------
 * TO DO:
 *   - Add comments
 *   - Namespace scoping/protection
 *   - Fix resulting wikilinks for secure server
 */
 
importScript('User:MastCell/api.js');
 
function addSelectAfter() {
	var obj = document.getElementById('target');
 
	// create select using included array
	var sel = fillSelect();
 
	sel.name = "nsOptions";
	sel.id = "nsOptions";
	sel.style.marginLeft = "10px";
 
	// check for next sibling and insert before it or at the end
	if (obj.nextSibling) {
		obj.parentNode.insertBefore(sel, obj.nextSibling);
	} else {
		obj.parentNode.appendChild(sel);
	}
}
 
function fillSelect() {
	var namespaceList = [ {
		"value" : "-99",
		"display" : "All namespaces"
	}, {
		"value" : "0",
		"display" : "Article"
	}, {
		"value" : "1",
		"display" : "Talk"
	}, {
		"value" : "2",
		"display" : "User"
	}, {
		"value" : "3",
		"display" : "User Talk"
	}, {
		"value" : "4",
		"display" : "Wikipedia"
	}, {
		"value" : "5",
		"display" : "Wikipedia Talk"
	}, {
		"value" : "6",
		"display" : "Image"
	}, {
		"value" : "7",
		"display" : "Image Talk"
	}, {
		"value" : "8",
		"display" : "MediaWiki"
	}, {
		"value" : "9",
		"display" : "MediaWiki Talk"
	}, {
		"value" : "10",
		"display" : "Template"
	}, {
		"value" : "11",
		"display" : "Template Talk"
	}, {
		"value" : "12",
		"display" : "Help"
	}, {
		"value" : "13",
		"display" : "Help Talk"
	}, {
		"value" : "14",
		"display" : "Category"
	}, {
		"value" : "15",
		"display" : "Category Talk"
	} ];
	var sel = document.createElement("select");
	sel.disabled = false;
	for (var i = 0; i < namespaceList.length; i++) {
		var opt = new Option(namespaceList[i].display, namespaceList[i].value);
		// catches stupid IE error
		if (opt.innerHTML != namespaceList[i].display) {
			opt.innerHTML = namespaceList[i].display;
		}
		sel.appendChild(opt);
	}
        return sel;
}
 
function addEvent(obj, evType, fn, useCapture) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent("on" + evType, fn);
		return r;
	} else {
		alert("Handler could not be attached");
	}
}
 
function addSearchEventHandler() {
  var linksearchForm = document.getElementById("mw-linksearch-form");
  addEvent(linksearchForm, "submit", handleFormSubmission, true);
}
 
function handleFormSubmission(event) {
  // Prevent default form submission (cross-browser)
  if (event.preventDefault){
    event.preventDefault();
  } else {
    event.returnValue = false;
  }
 
  // Disable the search button; will be re-enabled when AJAX query completes
  document.getElementById("linksearch-submit-button").disabled = true;
 
  var targetLink = document.getElementById("target").value;
  var localAPI = JsMwApi();
  var namespaceOpt = document.getElementById("nsOptions").value;
  if (namespaceOpt == -99) {
    localAPI({action: "query", list: "exturlusage", euquery: targetLink, eulimit: "1000"}, processELresults);
  } else {
    localAPI({action: "query", list: "exturlusage", euquery: targetLink, eulimit: "1000", eunamespace: namespaceOpt}, processELresults);
  }
}
 
function processELresults(result) {
  // Create a list for the results
  var resultList = document.createElement("OL");
  resultList.setAttribute("name", "result-list");
  resultList.setAttribute("id", "result-list");
  resultList.setAttribute("start", "1");
  resultList.setAttribute("class", "special");
 
  // Clear out the old list, if one exists
  if (document.getElementById("result-list")) {
    document.getElementById("result-list").parentNode.removeChild(document.getElementById("result-list"));
  }
 
  // Put the new list into the DOM
  var elForm = document.getElementById("mw-linksearch-form");
  if (elForm.nextSibling) {
    elForm.parentNode.insertBefore(resultList, elForm.nextSibling);
  } else {
    elForm.parentNode.appendChild(resultList);
  }
 
  // If there are no links in the given namespace, say so
  if (result.query.exturlusage.length == 0) {
    var noneFound = "No links to ";
    noneFound += document.getElementById("target").value;
    noneFound += " were found in this namespace.";
    resultList.innerHTML = noneFound;
  } else {
    // Fill up the list of links
    for (var i = 0; i < result.query.exturlusage.length; i++) {
      var nextListElem = document.createElement("LI");
      var listItemContent = "<a href=\"";
      listItemContent += result.query.exturlusage[i].url;
      listItemContent += "\" class=\"external\">";
      listItemContent += result.query.exturlusage[i].url;
      listItemContent += "</a> is linked from <a href=\"/wiki/";
      listItemContent += encodeURI(result.query.exturlusage[i].title);
      listItemContent += "\" title=\"";
      listItemContent += result.query.exturlusage[i].title;
      listItemContent += "\">";
      listItemContent += result.query.exturlusage[i].title;
      listItemContent += "</a>";
      nextListElem.innerHTML = listItemContent;
      resultList.appendChild(nextListElem);
    }
  }
 
  // Re-enable the search button
  document.getElementById("linksearch-submit-button").disabled = false;
}
 
function attachIdToSubmitButton() {
  // Will need to be able to access the submit button quickly, so attach an id
  var formVar = document.getElementById("mw-linksearch-form");
  for (var i = 0; i < formVar.elements.length; i++) {
    if (formVar.elements[i].type == "submit") {
      formVar.elements[i].setAttribute("id", "linksearch-submit-button");
      formVar.elements[i].disabled = false;
    }
  }
}
 
$(function() {
  if (mw.config.get('wgPageName') == "Special:LinkSearch") {
    attachIdToSubmitButton();
    addSelectAfter();
    addSearchEventHandler();
  }
});
 //<pre>
//This function adds a link to the toolbox which, when clicked, displays the size of the page
//and the size of the prose. See the talk page for more details.
//
//To use this function add {{subst:js|User:Dr pda/prosesize.js}} to your monobook.js
//
function loadXMLDocPassingTemplate(url,handler, page)
{
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        var req = new XMLHttpRequest();
    }
    // branch for IE/Windows ActiveX version
    else if (window.ActiveXObject) {
        var req = new ActiveXObject("Microsoft.XMLHTTP");
   }
   if (req) {
     req.onreadystatechange = function () {handler(req, page)};
     req.open("GET", url, true);
     req.send("");
   }
}
 
function getWikiText(req, page) {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
	 response = req.responseXML.documentElement;
         var rev = response.getElementsByTagName('rev');
	 if(rev.length > 0){
	   result = rev[0].getAttribute('size');
           if(result > 10240){
             result = (result/1024).toFixed(0)+'&nbsp;kB';
           }
           else{
             result = result+'&nbsp;B';
           }
           wiki_value = document.createElement("li");
	   wiki_value.id = "wiki-size";
	   wiki_value.innerHTML = '<b>Wiki text: </b>'+result;
	   var output = document.getElementById("document-size-stats");
	   prose_value = document.getElementById("prose-size");
	   output.insertBefore(wiki_value,prose_value);
	 }
	 else{
	  //alert("There was a problem using the Wikipedia Search to find the wiki text size\nEither the search is not working or the correct article did not appear on the first page of results");
           wiki_value = document.createElement("li");
	   wiki_value.id = "wiki-size";
	   wiki_value.innerHTML = '<b>Wiki text: </b>Problem getting wiki text size';
	   var output = document.getElementById("document-size-stats");
	   prose_value = document.getElementById("prose-size");
	   output.insertBefore(wiki_value,prose_value);
	 }
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
        }
    }
}
 
function getFileSize(req, page) {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
	  var fsize = req.responseText.length;
	  window.status = fsize;
	  var total_value = document.createElement("li");
	  total_value.id = "total-size";
	  total_value.innerHTML='<b>File size: </b>'+(fsize/1024).toFixed(0)+'&nbsp;kB';
	  var output = document.getElementById("document-size-stats");
	  var prose_html_value = document.getElementById("prose-size-html");
	  output.insertBefore(total_value,prose_html_value);
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText + "\n(" + url + ")");
        }
    }
}
 
function getLength(id){
 var textLength = 0;
 for(var i=0;i<id.childNodes.length; i++){
  if(id.childNodes[i].nodeName == '#text'){
   textLength += id.childNodes[i].nodeValue.length;
  }
  else if(id.childNodes[i].id == 'coordinates' || id.childNodes[i].className.indexOf('emplate') != -1){
    //special case for {{coord}} and {{fact}}-like templates
    //Exclude from length, and don't set background yellow
    id.childNodes[i].style.cssText = 'background-color:white';
  }
  else{
    textLength += getLength(id.childNodes[i]);
  }
 }
 return textLength;
}
 
function getRefMarkLength(id,html){
 var textLength = 0;
 for(var i=0;i<id.childNodes.length; i++){
  if(id.childNodes[i].className == 'reference'){
   textLength += (html)? id.childNodes[i].innerHTML.length : getLength(id.childNodes[i]);
  }
 }
 return textLength;
}
 
function getDocumentSize(){
 contentDivName = '';
 if(skin == 'vector' || skin == 'monobook' || skin == 'chick' || skin == 'myskin' || skin == 'simple'){
   contentDivName = 'bodyContent';
 }
 else if (skin == 'modern'){
   contentDivName = 'mw_contentholder';
 }
 else if (skin == 'standard' || skin == 'cologneblue' || skin == 'nostalgia'){
   contentDivName = 'article';
 }
 else{
   //fallback case; the above covers all currently existing skins
   contentDivName = 'bodyContent';
 }
 //Same for all skins if previewing page
 if(mw.config.get('wgAction') == 'submit') contentDivName = 'wikiPreview';
 
 var bodyContent = document.getElementById(contentDivName);
 if(document.getElementById("document-size-stats")){
   //if statistics already exist, turn them off and remove highlighting
   var output = document.getElementById("document-size-stats");
   var oldStyle = output.className;
   var pList = bodyContent.getElementsByTagName("p");
   for(var i=0;i<pList.length; i++){
     if(pList[i].parentNode.id == contentDivName) pList[i].style.cssText = oldStyle;
   }
   output.parentNode.removeChild(output);
   var header = document.getElementById("document-size-header");
   header.parentNode.removeChild(header);
 }
 else{
 var output = document.createElement("ul");
 output.id = "document-size-stats";
 
 var prose_html_value = document.createElement("li");
 prose_html_value.id = "prose-size-html";
 output.appendChild(prose_html_value);
 
 var ref_html_value = document.createElement("li");
 ref_html_value.id = "ref-size-html";
 output.appendChild(ref_html_value);
 
 var prose_value = document.createElement("li");
 prose_value.id = "prose-size";
 output.appendChild(prose_value);
 output.className = bodyContent.getElementsByTagName("p").item(0).style.cssText;
 
 var ref_value = document.createElement("li");
 ref_value.id = "ref-size";
 output.appendChild(ref_value);
 
 var dummy = document.getElementById("siteSub");
 dummy.parentNode.insertBefore(output, dummy.nextSibling);
 
 var header = document.createElement("span");
 header.id = "document-size-header";
 header.innerHTML = '<br/>Document statistics: <small><i>(See <a href="http://en.wikipedia.org/wiki/User_talk:Dr_pda/prosesize.js">here</a> for details.)<i></small>';
 dummy.parentNode.insertBefore(header,output);
 
 //File size not well defined for preview mode or section edit
 if(mw.config.get('wgAction') != 'submit'){
   //If browser supports document.fileSize property (IE)
   if(document.fileSize){
     var total_value = document.createElement("li");
     total_value.id = "total-size";
     total_value.innerHTML='<b>File size: </b>'+(document.fileSize/1024).toFixed(0)+'&nbsp;kB';
     output.insertBefore(total_value,prose_html_value);
   }
   else{
    loadXMLDocPassingTemplate(location.pathname,getFileSize,'')
   }
 }
 
 //Get size of images only if browser supports filesize property (IE)
 var iList = bodyContent.getElementsByTagName("img");
 if(iList.length >0 && iList[0].fileSize){
 //Get size of images included in document
   var image_size = 0;
   var first_magnify = true;
 
   for (var i=0;i<iList.length; i++){
    var im = iList[i];
    if(im.getAttribute("src").indexOf("magnify-clip.png") != -1){
      if(first_magnify){
        image_size += im.fileSize*1;
        first_magnify = false;
      }
    }
    else{
      image_size += im.fileSize*1;
    }
   }
   var image_value = document.createElement("li");
   image_value.id = "image-size";
   image_value.innerHTML='<b>Images: </b>'+(image_size/1024).toFixed(0)+'&nbsp;kB';
   output.appendChild(image_value);
 
  }
 //Calculate prose size and size of reference markers ([1] etc)
 var pList = bodyContent.getElementsByTagName("p");
 
 prose_size = 0;
 prose_size_html = 0;
 refmark_size = 0;
 refmark_size_html = 0;
 word_count = 0;
 for(var i=0;i<pList.length; i++){
   var para = pList[i];
   if(para.parentNode.id == contentDivName){
    prose_size += getLength(para);
    prose_size_html += para.innerHTML.length;
    refmark_size += getRefMarkLength(para,false);
    refmark_size_html += getRefMarkLength(para,true);
    word_count += para.innerHTML.replace(/(<([^>]+)>)/ig,"").split(' ').length
    para.style.cssText = "background-color:yellow";
   }
 }
 
 if((prose_size-refmark_size)>10240){
   prose_value.innerHTML='<b>Prose size (text only): </b>'+((prose_size-refmark_size)/1024).toFixed(0)+'&nbsp;kB ('+word_count+' words) "readable prose size"';
 }
 else{
   prose_value.innerHTML='<b>Prose size (text only): </b>'+(prose_size-refmark_size)+'&nbsp;B ('+word_count+' words) "readable prose size"';
 }
 
 if((prose_size_html-refmark_size_html)>10240){
   prose_html_value.innerHTML='<b>Prose size (including all HTML code): </b>'+((prose_size_html-refmark_size_html)/1024).toFixed(0)+'&nbsp;kB';
 }
 else{
   prose_html_value.innerHTML='<b>Prose size (including all HTML code): </b>'+(prose_size_html-refmark_size_html)+'&nbsp;B';
 }
 
 //Calculate size of references (i.e. output of <references/>)
 var rList = bodyContent.getElementsByTagName("ol");
 var ref_size = 0;
 var ref_size_html = 0;
 for (var i=0; i<rList.length; i++){
   if(rList[i].className == "references"){
     ref_size = getLength(rList[i]);
     ref_size_html = rList[i].innerHTML.length;
   }
 }
 
 if((ref_size+refmark_size)>10240){
   ref_value.innerHTML='<b>References (text only): </b>'+((ref_size+refmark_size)/1024).toFixed(0)+'&nbsp;kB';
 }
 else{
   ref_value.innerHTML='<b>References (text only): </b>'+(ref_size+refmark_size)+'&nbsp;B';
 }
 
 if((ref_size_html+refmark_size_html)>10240){
   ref_html_value.innerHTML='<b>References (including all HTML code): </b>'+((ref_size_html+refmark_size_html)/1024).toFixed(0)+'&nbsp;kB';
 }
 else{
   ref_html_value.innerHTML='<b>References (including all HTML code): </b>'+(ref_size_html+refmark_size_html)+'&nbsp;B';
 }
 
 //get correct name of article from wikipedia-defined global variables
 var pageNameUnderscores = mw.config.get('wgPageName');
 var pageNameSpaces = pageNameUnderscores.replace(/_/g,' ')
 
 //if page is a permalink, diff, etc don't try to search
 if(!location.pathname.match('/w/index.php')){ 
  //Get revision size from API
  var searchURL = mw.config.get('wgScriptPath') + '/api.php?action=query&prop=revisions&rvprop=size&format=xml&revids=' + mw.config.get('wgCurRevisionId');
  loadXMLDocPassingTemplate(searchURL,getWikiText,pageNameSpaces);
 }
 else if(mw.config.get('wgAction') == 'submit'){
   //Get size of text in edit box
   result = document.getElementById('wpTextbox1').value.length;
   if(result > 10240){
     result = (result/1024).toFixed(0)+'&nbsp;kB';
   }
   else{
     result = result+'&nbsp;B';
   }
   wiki_value = document.createElement("li");
   wiki_value.id = "wiki-size";
   wiki_value.innerHTML = '<b>Wiki text: </b>'+result;
   var output = document.getElementById("document-size-stats");
   prose_value = document.getElementById("prose-size");
   output.insertBefore(wiki_value,prose_value);
 }
}
}
 
$(function () {
  if(mw.config.get('wgAction') == 'edit' || (mw.config.get('wgAction') == 'submit' && document.getElementById('wikiDiff')) ){
    mw.util.addPortletLink('p-tb', 'javascript:alert("You need to preview the text for the prose size script to work in edit mode.")', 'Page size', 't-page-size', 'Calculate page and prose size', '', '');
    document.getElementById("t-page-size").firstChild.style.cssText = "color:black;"
  }
  else if(mw.config.get('wgAction') == 'view' || mw.config.get('wgAction') == 'submit' || mw.config.get('wgAction') == 'purge'){
    mw.util.addPortletLink('p-tb', 'javascript:getDocumentSize()', 'Page size', 't-page-size', 'Calculate page and prose size', '', '');
  }
});
 
 //</pre>
importScript('User:AzaToth/twinkle.js');
importScript('User:Smith609/toolbox.js');
importScript('User:Writ Keeper/Scripts/orangeBar.js'); //Linkback: [[User:Writ Keeper/Scripts/orangeBar.js]]