From StrategyWiki, the video game walkthrough and strategy guide wiki
Jump to navigation Jump to search
m (trying to get date to format how I want)
(modifying for scope, adding documentation, fixing date format I hope)
Line 1: Line 1:
/***********************************************************************************/
/* Edit counter script                                                            */
/*  author:        User:Najzere @ strategywiki.org                                */
/*  source:        http://strategywiki.org/wiki/User:Najzere/edit counter.js      */
/*  documentation: http://strategywiki.org/wiki/User talk:Najzere/edit counter.js */
/*  contact:      http://strategywiki.org/wiki/User talk:Najzere                */
/*  license:      CC-BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/)  */
/***********************************************************************************/
// Only add edit count button on user pages
if (wgTitle == wgUserName && wgNamespaceNumber == 2) {
if (wgTitle == wgUserName && wgNamespaceNumber == 2) {
   addOnloadHook(makeEditCountButton);
   addOnloadHook(makeEditCountButton);
}
}


// Add a new link after "User contributions" in the toolbox
function makeEditCountButton() {
function makeEditCountButton() {
  if (!document.getElementById('t-contributions')) {
    alert('Expected element not found. Please see http://strategywiki.org/wiki/User talk:Najzere to have your wiki added.');
    return false;
  };
   var newlist = document.createElement('li');
   var newlist = document.createElement('li');
   newlist.id = "t-editcounter";
   newlist.id = "t-editcounter";
   var newlink = document.createElement('a');
   var newlink = document.createElement('a');
   newlink.href = 'javascript:countEdits()';
   newlink.href = 'javascript:countEdits()';
   var linkname = document.createTextNode('Edit counts');
   var linkname = document.createTextNode('Edit counter');
   newlink.appendChild(linkname);
   newlink.appendChild(linkname);
   newlist.appendChild(newlink);
   newlist.appendChild(newlink);
   document.getElementById('nav_right').getElementsByTagName('ul')[0].insertBefore(newlist, document.getElementById('t-contributions').nextSibling);
   document.getElementById('t-contributions').parentNode.insertBefore(newlist, document.getElementById('t-contributions').nextSibling);
}
}


function countEdits() {
function countEdits() {
// Change edit counter link to let the user know it's thinking
   document.getElementById('t-editcounter').getElementsByTagName('a')[0].innerHTML = 'Calculating...';
   document.getElementById('t-editcounter').getElementsByTagName('a')[0].innerHTML = 'Calculating...';


   var editSummary = 'Edited with [[User:Najzere/edit counter.js]]';
// Set up variables
   var editSummary = 'Edited with [http://strategywiki.org/wiki/User:Najzere/edit counter.js edit counter script]';
   if (typeof editPage == "undefined") {var editPage = 'Edit count'};
   if (typeof editPage == "undefined") {var editPage = 'Edit count'};
   if (typeof tableClass == "undefined") {var tableClass = ''};
   if (typeof tableClass == "undefined") {var tableClass = ''};
  if (typeof tableFloat == "undefined") {var tableFloat = ''};
   if (typeof tableStyle == "undefined") {var tableStyle = ''};
   if (typeof tableStyle == "undefined") {var tableStyle = ''};
   if (tableClass != '') {
   if (editPage == '') {editPage = 'Edit count'};
    tableClass = '|class='+tableClass;
  };
  if (tableFloat == 'left' || tableFloat == 'right') {
    tableFloat = '|float='+tableFloat;
  } else {
    tableFloat = '';
  };
  if (tableStyle != '') {
    tableStyle = '|style='+tableStyle;
  };
   var skipcaptcha = false;
   var skipcaptcha = false;
   var oldpage = false;
   var oldpage = false;
Line 42: Line 48:
   var edittoken;
   var edittoken;
   var brace = '{';
   var brace = '{';
   var table = '{|'+brace+brace+'prettytable'+tableClass+tableFloat+tableStyle+'}}\n!colspan="2"| [[User talk:Najzere/edit counter.js|Edit count]]: '+brace+brace+'subst:formatnum:';
   var table = '{| class="wikitable '+tableClass+'" style="'+tableStyle+'"\n!colspan="2"| <class="plainlinks">[http://strategywiki.org/wiki/User_talk:Najzere/edit_counter.js Edit count]</class>: '+brace+brace+'subst:formatnum:';


   queryApi('action=query&meta=userinfo&uiprop=editcount|rights', function(uiResponse) {
// Check if the user is autoconfirmed
    for (var r in uiResponse.query.userinfo.rights) {
  for (var right in wgUserGroups)
      if (uiResponse.query.userinfo.rights[r] == "autoconfirmed") {
    if (wgUserGroups[right] == 'autoconfirmed') {skipcaptcha = true};
        skipcaptcha = true;
 
      };
// Get full edit count, as tracked by MW, add it to table
    };
   queryApi('action=query&meta=userinfo&uiprop=editcount', function(uiResponse) {
     table += uiResponse.query.userinfo.editcount+'}}';
     table += uiResponse.query.userinfo.editcount+'}}';
   });
   });


// Initialize namespace, move log and patrol log arrays
   queryApi('action=query&meta=siteinfo&siprop=namespaces', function(siResponse) {
   queryApi('action=query&meta=siteinfo&siprop=namespaces', function(siResponse) {
     for (var ns in siResponse.query.namespaces) {
     for (var ns in siResponse.query.namespaces) {
Line 67: Line 74:
   });
   });


// Fill move log array
   next = '';
   next = '';
   while (next != 'stop') {
   while (next != 'stop') {
Line 81: Line 89:
   }
   }


// Fill patrol log array
   next = '';
   next = '';
   while (next != 'stop') {
   while (next != 'stop') {
Line 95: Line 104:
   }
   }


// Loop through namespaces counting edits and subtracting page moves and patrols
   for (var i = 0; i < namespaces.length; i++) {
   for (var i = 0; i < namespaces.length; i++) {
     next = '';
     next = '';
Line 113: Line 123:
     };
     };
   };
   };
   table += '\n|-\n|colspan="2" align="center"| <small>Last run: '+brace+brace+'subst:#dateformat:'+rightnow()+'|mdy}}</small>\n|}';
   table += '\n|-\n|colspan="2" align="center"| <small>Last run: '+brace+brace+'subst:#time:F j, Y}}</small>\n|}';


// Get edit token and check if we'll be creating a new page (in the case of non-autoconfirmed users)
   queryApi('action=query&prop=info|revisions&intoken=edit&titles=User:'+wgUserName+'/'+editPage, function(propResponse) {
   queryApi('action=query&prop=info|revisions&intoken=edit&titles=User:'+wgUserName+'/'+editPage, function(propResponse) {
     for (var page in propResponse.query.pages) {
     for (var page in propResponse.query.pages) {
Line 124: Line 135:
   });
   });


// If the user is not autoconfirmed and we're creating a new page, kick out of the script
   if (!skipcaptcha && !oldpage) {
   if (!skipcaptcha && !oldpage) {
     alert("Sorry, you're not autoconfirmed yet, so captcha is required to make new pages. Go create the page at: User:"+wgUserName+"/"+editPage+", then try again.");
     alert("Sorry, you're not autoconfirmed yet, so captcha is required to make new pages. Go create the page at: User:"+wgUserName+"/"+editPage+", then try again.");
Line 129: Line 141:
   };
   };


   queryApi('action=edit&title=User:'+wgUserName+'/'+editPage+'&summary='+editSummary+'&minor=1&recreate&text='+table+'&token='+edittoken, function(actionResponse) {
// Edit the target page with the table, change edit count link to reflect the status of the page save
   queryApi('action=edit&title=User:'+wgUserName+'/'+editPage+'&summary='+editSummary+'&minor=1&recreate=1&bot=1&text='+table+'&token='+edittoken, function(actionResponse) {
     if (actionResponse.edit.result == "Success") {
     if (actionResponse.edit.result == "Success") {
       document.getElementById('t-editcounter').getElementsByTagName('a')[0].innerHTML = 'Done!';
       document.getElementById('t-editcounter').getElementsByTagName('a')[0].innerHTML = 'Done!';
Line 138: Line 151:
}
}


function rightnow() {
// Accepts an API query and callback function for handling queries from the main function
  var thedate = new Date();
  var combine = thedate.getFullYear()+'-';
  if (thedate.getMonth()+1 < 10) {combine+= '0'};
  combine += (thedate.getMonth()+1)+'-';
  if (thedate.getDate() < 10) {combine+= '0'};
  combine += thedate.getDate();
  return combine;
};
 
function queryApi(query, callback) {
function queryApi(query, callback) {
   try {
   try {

Revision as of 18:49, 16 February 2010

/***********************************************************************************/
/* Edit counter script                                                             */
/*   author:        User:Najzere @ strategywiki.org                                */
/*   source:        http://strategywiki.org/wiki/User:Najzere/edit counter.js      */
/*   documentation: http://strategywiki.org/wiki/User talk:Najzere/edit counter.js */
/*   contact:       http://strategywiki.org/wiki/User talk:Najzere                 */
/*   license:       CC-BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/)  */
/***********************************************************************************/

// Only add edit count button on user pages
if (wgTitle == wgUserName && wgNamespaceNumber == 2) {
  addOnloadHook(makeEditCountButton);
}

// Add a new link after "User contributions" in the toolbox
function makeEditCountButton() {
  if (!document.getElementById('t-contributions')) {
    alert('Expected element not found. Please see http://strategywiki.org/wiki/User talk:Najzere to have your wiki added.');
    return false;
  };
  var newlist = document.createElement('li');
  newlist.id = "t-editcounter";
  var newlink = document.createElement('a');
  newlink.href = 'javascript:countEdits()';
  var linkname = document.createTextNode('Edit counter');
  newlink.appendChild(linkname);
  newlist.appendChild(newlink);
  document.getElementById('t-contributions').parentNode.insertBefore(newlist, document.getElementById('t-contributions').nextSibling);
}

function countEdits() {
// Change edit counter link to let the user know it's thinking
  document.getElementById('t-editcounter').getElementsByTagName('a')[0].innerHTML = 'Calculating...';

// Set up variables
  var editSummary = 'Edited with [http://strategywiki.org/wiki/User:Najzere/edit counter.js edit counter script]';
  if (typeof editPage == "undefined") {var editPage = 'Edit count'};
  if (typeof tableClass == "undefined") {var tableClass = ''};
  if (typeof tableStyle == "undefined") {var tableStyle = ''};
  if (editPage == '') {editPage = 'Edit count'};
  var skipcaptcha = false;
  var oldpage = false;
  var edits;
  var namespaces = new Array();
  var movelog = new Array();
  var protectlog = new Array();
  var next;
  var edittoken;
  var brace = '{';
  var table = '{| class="wikitable '+tableClass+'" style="'+tableStyle+'"\n!colspan="2"| <class="plainlinks">[http://strategywiki.org/wiki/User_talk:Najzere/edit_counter.js Edit count]</class>: '+brace+brace+'subst:formatnum:';

// Check if the user is autoconfirmed
  for (var right in wgUserGroups)
    if (wgUserGroups[right] == 'autoconfirmed') {skipcaptcha = true};

// Get full edit count, as tracked by MW, add it to table
  queryApi('action=query&meta=userinfo&uiprop=editcount', function(uiResponse) {
    table += uiResponse.query.userinfo.editcount+'}}';
  });

// Initialize namespace, move log and patrol log arrays
  queryApi('action=query&meta=siteinfo&siprop=namespaces', function(siResponse) {
    for (var ns in siResponse.query.namespaces) {
      if (siResponse.query.namespaces[ns].id > -1) {
        if (siResponse.query.namespaces[ns].id == 0) {
          namespaces[siResponse.query.namespaces[ns].id] = 'Main';
        } else {
          namespaces[siResponse.query.namespaces[ns].id] = siResponse.query.namespaces[ns].canonical;
        };
        movelog[siResponse.query.namespaces[ns].id] = 0;
        protectlog[siResponse.query.namespaces[ns].id] = 0;
      };
    };
  });

// Fill move log array
  next = '';
  while (next != 'stop') {
    queryApi('action=query&list=logevents&letype=move&leuser='+wgUserName+'&lelimit=max&leprop=title'+next, function(moveResponse) {
      for (var event in moveResponse.query.logevents) {
        movelog[moveResponse.query.logevents[event].ns] += 1;
      }
      if (moveResponse["query-continue"]) {
        next = '&lestart='+moveResponse["query-continue"].logevents.lestart;
      } else {
        next = 'stop';
      };
    });
  }

// Fill patrol log array
  next = '';
  while (next != 'stop') {
    queryApi('action=query&list=logevents&letype=protect&leuser='+wgUserName+'&lelimit=max&leprop=title'+next, function(protectResponse) {
      for (var event in protectResponse.query.logevents) {
        protectlog[protectResponse.query.logevents[event].ns] += 1;
      }
      if (protectResponse["query-continue"]) {
        next = '&lestart='+protectResponse["query-continue"].logevents.lestart;
      } else {
        next = 'stop';
      };
    });
  }

// Loop through namespaces counting edits and subtracting page moves and patrols
  for (var i = 0; i < namespaces.length; i++) {
    next = '';
    edits = 0;
    while (next != 'stop') {
      queryApi('action=query&list=usercontribs&ucuser='+wgUserName+'&uclimit=max&ucdir=newer&ucnamespace='+i+next, function(ucResponse) {
        edits += ucResponse.query.usercontribs.length;
        if (ucResponse["query-continue"]) {
          next = '&ucstart='+ucResponse["query-continue"].usercontribs.ucstart;
        } else {
          next = 'stop';
        };
      });
    };
    edits = edits - movelog[i] - protectlog[i];
    if (edits > 0) {
      table += '\n|-\n| '+namespaces[i]+' || '+brace+brace+'subst:formatnum:'+edits+'}}';
    };
  };
  table += '\n|-\n|colspan="2" align="center"| <small>Last run: '+brace+brace+'subst:#time:F j, Y}}</small>\n|}';

// Get edit token and check if we'll be creating a new page (in the case of non-autoconfirmed users)
  queryApi('action=query&prop=info|revisions&intoken=edit&titles=User:'+wgUserName+'/'+editPage, function(propResponse) {
    for (var page in propResponse.query.pages) {
      edittoken = propResponse.query.pages[page].edittoken.replace(/\+\\$/g,'%2B%5C');
      if (propResponse.query.pages[page]["revisions"]) {
        oldpage = true;
      };
    };
  });

// If the user is not autoconfirmed and we're creating a new page, kick out of the script
  if (!skipcaptcha && !oldpage) {
    alert("Sorry, you're not autoconfirmed yet, so captcha is required to make new pages. Go create the page at: User:"+wgUserName+"/"+editPage+", then try again.");
    return false;
  };

// Edit the target page with the table, change edit count link to reflect the status of the page save
  queryApi('action=edit&title=User:'+wgUserName+'/'+editPage+'&summary='+editSummary+'&minor=1&recreate=1&bot=1&text='+table+'&token='+edittoken, function(actionResponse) {
    if (actionResponse.edit.result == "Success") {
      document.getElementById('t-editcounter').getElementsByTagName('a')[0].innerHTML = 'Done!';
    } else {
      document.getElementById('t-editcounter').getElementsByTagName('a')[0].innerHTML = 'Error!';
    };
  });
}

// Accepts an API query and callback function for handling queries from the main function
function queryApi(query, callback) {
  try {
    var xmlRequest = new XMLHttpRequest();
  } catch(e) {
    try {
      var xmlRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
      var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        throw "Could not create an XmlHttpRequest";
        }
      }
    }

  xmlRequest.open('POST', wgScriptPath+'/api.php', false);
  xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlRequest.send(query+'&format=json');
  var xmlResponse = new Function("return "+xmlRequest.responseText)();
  if (!xmlResponse) {
    alert('Problem retrieving information');
  } else {
    callback(xmlResponse);
  };
}