Kullanıcı:Headersalreadysent/monobook.js: Revizyonlar arasındaki fark

Ubuntu Türkiye Wiki sitesinden
Gezinti kısmına atla Arama kısmına atla
(Yeni sayfa: /** <nowiki> * A javascript edit counter, using query.php as the backend * * Usage instructions for popups users: add * {{subst:js|User:Lupin/editcount.js}} popupEditCounterTool='c...)
 
Değişiklik özeti yok
1. satır: 1. satır:
/** <nowiki>
// see http://paperlined.org/apps/wikipedia/Tool2/ for instructions on adding this to your monobook.js
* A javascript edit counter, using query.php as the backend
*
* Usage instructions for popups users: add
*
   
   
{{subst:js|User:Lupin/editcount.js}}
// To run this tool on other servers:
popupEditCounterTool='custom';
// 1. copy this script to the target server (this is required because of javascript cross-site security restrictions)
popupEditCounterUrl='http://en.wikipedia.org/wiki/User:$1?ectarget=$1';
   
   
*
// 2. update the following URL
* to your user javascript file (usually monobook.js), hover over a
// for example: "User:Interiot/Tool2/code.js"
* user name and select "edit counter"
var tool2_url = "User:Interiot/Tool2/code.js";
*
*/
   
   
//<pre>
// 3. update this namespace list, extracted from something like http://en.wikiquote.org/wiki/Special:Export//
// These *should not* have colons after them.
var namespaces = [
"Talk",
"User",
"User talk",
"Wikiquote",
"Wikiquote talk",
"Image",
"Image talk",
"MediaWiki",
"MediaWiki talk",
"Template",
"Template talk",
"Help",
"Help talk",
"Category",
"Category talk",
// 3b. these two project project entries are not added by Special:Export, and might or might not need to be updated
"Wikipedia",
"Wikipedia talk"
];
   
   
ec = {
namespaces[100] = "Portal";
namespaces[101] = "Portal talk";
// 4. update this date-parser to match the format and language of your specific wiki.  Feel free to contact Interiot regarding this, if you can't find another
// copy of this script that uses the same language.
// input: a text string from Special:Contributions.    output: a javascript Date object
// documentation:  http://www.quirksmode.org/js/introdate.html#parse, http://www.elated.com/tutorials/programming/javascript/dates/
function date_parse(text) {
var matches = text.match(/^([0-9:]+), +([0-9]+) +([a-z]+) +([0-9]+)$/i);
if (!matches) {
//dump_text("XXX"); // for debugging
return matches;
}
parseme = matches[3] + ", " + matches[2] + " "  + matches[4] + " " + matches[1] + ":00";
//dump_text(parseme); // for debugging
var dt = new Date();
dt.setTime( Date.parse(parseme));
//dump_text(dt.toLocaleString()); // for debugging
return dt;
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ end of server-specific configuration ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   
   
getParamValue: function(paramName) {
var cmdRe=RegExp('[&?]'+paramName+'=([^&]*)');
var h=document.location;
var m;
if (m=cmdRe.exec(h)) {
try {
while(m[1].indexOf('+')!=-1)
{
m[1]=m[1].substr(0,m[1].indexOf('+'))+" "+m[1].substr(m[1].indexOf('+')+1);
}
return decodeURIComponent(m[1]);
} catch (someError) {}
}
return null;
},
   
   
doEditCount: function(user) {
if (!user) { return; }
ec.user=user;
ec.makeEditCountDivs();
ec.getContribs(user);
setTimeout(ec.checkContribs, 1000);
},
makeEditCountDivs: function() {
var d=document.createElement('div');
d.id='editcount_output';
ec.appendDivs(d, [ 'editcount_title', 'editcount_intervalselector',
  'editcount_stats' ]);
var h=document.getElementById('siteSub');
h.parentNode.insertBefore(d, h.nextSibling);
},
appendDivs: function(parent, list) {
for (var i=0; i<list.length; ++i) {
var d=document.createElement('div');
d.id=list[i];
parent.appendChild(d);
}
},
   
   
checkContribs: function() {
// TODO:
if (ec.complete) {
// - the current document.location method doesn't work when the page is accessed sans-mod_rewrite
ec.doOutput();
// - test with non-ASCII characters
} else {
// - non-ascii usernames
ec.doStatus();
// - ??
setTimeout(ec.checkContribs, 1000);
}
},
   
   
doOutput: function(start, end) {
var d=document.getElementById('editcount_stats');
if (!ec.count) {
d.innerHTML='No edits found for ' + ec.user;
return;
}
if (!this.intsel) {
this.intsel = new IntervalSelector({
min: ts2unix(this.editlist.first.next.key),
max: ts2unix(this.editlist.last.prev.key)});
var this2=this;
this.intsel.doneDrag=function() {
//document.title=[this.lo, this.hi];
this2.doOutput.apply(this2, map(unix2ts, [this.lo, this.hi]));
};
this.intsel.dragging=function() {
var start=unix2ts(this2.intsel.lo);
var end=unix2ts(this2.intsel.hi);
document.getElementById('editcount_range').innerHTML=
formatTs(start) + ' - ' + formatTs(end);
};
//this.intsel.dragging=this.intsel.doneDrag; // too slow - pretty cool tho
var intdiv=document.getElementById('editcount_intervalselector');
intdiv.appendChild(this.intsel.box);
this.appendDivs(intdiv, ['editcount_range']);
this.intsel.dragging();
this.intseldebug=document.createElement('div');
this.intsel.box.parentNode.insertBefore(this.intseldebug, this.intsel.box);
}
document.getElementById('editcount_title').innerHTML=ec.outputHeading();
document.getElementById('editcount_stats').innerHTML='<p>Total: ' +
ec.countFigure() + '<br>First edit: ' + ec.firstEdit.replace(/[TZ]/g, ' ') +
'(UTC)' + ec.statsTable(start, end);
},
   
   
outputHeading: function() {
return '<h2>Edit count for ' + ec.user + '</h2>';
},
   
   
doStatus: function() {
var prefix = "";
var d=document.getElementById('editcount_stats');
var params = parse_params();
d.innerHTML=ec.outputHeading() + '<p>Downloaded ' + ec.countFigure() + ' so far' + ec.statsTable();
},
   
   
countFigure: function() {
addOnloadFunction(function() {
return ec.count + ' edits over ' + objSum(ec.namespaces, 'articleCount') + ' pages';
  var path_len = document.location.pathname.length;
},
  // trigger once we view the right page
  if (document.location.pathname.substring(path_len - tool2_url.length, path_len) == tool2_url) {
    // get the prefix (needs to be fixed to work sans-mod_rewrite
    prefix = document.location.protocol + "//" + document.location.host + "/"
            + document.location.pathname.substring(1, path_len - tool2_url.length);
   
   
findEdit: function(timestamp, up) { // this is very broken - FIXME!
    // blank the inner contents of the page
if (up) {
    var bodyContent = document.getElementById("bodyContent");
var e=this.editlist.first;
    while (bodyContent.childNodes.length > 0) bodyContent.removeChild(bodyContent.lastChild);
while(e.key<timestamp && (e=e.next)){};
//console.log('findEdit, up: got '+timestamp+', found '+(e.prev && e.prev.key || null) );
return e.prev;
} else {
var e=this.editlist.last;
while(e.key>timestamp && (e=e.prev)){}
//console.log('findEdit, down: got '+timestamp+', found '+(e.next && e.next.key || null) );
return e.next;
}
},
   
   
statsTable: function(start, end) {
    //if (document.location.search.length == 0) {
//console.log('start: '+start + ', end: '+end);
      //generate_input_form(bodyContent);
var barTotal=400;
    //} else {
var endEdit=this.findEdit(end) || this.editlist.last;
      //generate_main_report(bodyContent);
var startEdit=this.findEdit(start,true);
    //}
if (!startEdit || !startEdit.key) { startEdit=this.editlist.first.next; }
    generate_redirect_notice(bodyContent);
//console.log('endEdit:' + endEdit.key);
  }
//console.log('startEdit:'+ startEdit.key);
});
var sumValue=function(val) {
return objSum(startEdit.stats, val) - objSum(endEdit.stats, val);
}
var total=sumValue('count');
if (!total) { return ''; }
var statValue=function(k, val) {
if (!startEdit.stats[k]) { return 0; }
var r=startEdit.stats[k][val];
//console.log(k + ' ' + val + ': ' + r);
if (!endEdit.stats[k] || !endEdit.stats[k][val]) { return r; }
return r - endEdit.stats[k][val];
};
// FIXME: abstract this away so it's trivial to add new columns
r='<p>Statistics between '+formatTs(startEdit.key) + ' and '+formatTs(endEdit.key);
r+='<table><tr><th>' + ['Namespace',
  'New',
  'Minor',
  'Top',
  'Summaries',
  '(manual)',
  'Pages',
  'Count', '%'].join('</th><th>') + '</th></tr>';
for (var k in ec.namespace_names) {
if (!ec.namespaces[k]) { continue; }
r += '<tr><td>'+[ec.namespace_names[k],
statValue(k, 'newCount'),
statValue(k, 'minorCount'),
statValue(k, 'topCount'),
statValue(k, 'commentCount'),
statValue(k, 'manualCommentCount'),
statValue(k, 'articleCount'),
statValue(k, 'count'),
percent(statValue(k, 'count'), total)].join('</td><td>') + '</td>';
r+=ec.ecBar(barTotal, total, statValue(k, 'count'), statValue(k, 'minorCount') || 0);
r+='</tr>';
}
var totalMinor = sumValue('minorCount');
r+='<tr><td>'+['<b>Total</b>',
      sumValue('newCount'),
      totalMinor,
      sumValue('topCount'),
      sumValue('commentCount'),
      sumValue('manualCommentCount'),
      sumValue('articleCount'),
      sumValue('count'),
      '100'].join('</td><td>') + '</td>';
r+=ec.ecBar(barTotal, total, sumValue('count'), totalMinor);
r+='</table>';
return r;
},
   
   
histogramBar: function(value, scale, colour, hint) {
function generate_redirect_notice(bodyContent) {
var height='2ex';
  bodyContent.innerHTML = "This counter doesn't currently work.  Please use <a href='http://tools.wikimedia.de/~interiot/cgi-bin/Tool1/wannabe_kate'>Tool1</a> or <a href='http://en.wikipedia.org/wiki/Wikipedia:WikiProject_edit_counters'>one of the other edit counters</a>.";
var style='height: '+ height;
}
style += '; background: ' + colour;
style += '; width: ' + value * scale + 'px';
style += '; float: left;';
return '<span style="' + style + '" title="' + hint + '"></span>';
},
   
   
histogramCell: function(scale, values) {
function generate_input_form(bodyContent) {
var r='<td><div style="width: ' + scale + 'px;">';
  if (navigator.userAgent.toLowerCase().indexOf('msie')+1)
for (var i=0; i<values.length; i+=3) { r+=ec.histogramBar(values[i], scale, values[i+1], values[i+2]); }
  {
r+='</div></td>';
  bodyContent.innerHTML = "This counter does not currently work in Internet Explorer.  Please <a href='http://www.getfirefox.com'>get Firefox</a> or use <a href='http://en.wikipedia.org/wiki/Wikipedia:WikiProject_edit_counters/Flcelloguy%27s_Tool'>Flcelloguy's Tool</a> instead.";
return r;
  }
},
  else
  {
  bodyContent.innerHTML =
            "<form><table><tr><td>Username <td><input maxlength=128 name=username value='' id=username title='username'>" +
            "            <tr><td>        <td><input type=submit value='Submit'>" +
            "</table></form>";
   
   
ecBar: function(scale, total, count, minor) {
  var form = bodyContent.getElementsByTagName("form")[0];
var nonMinorColour='blue';
  form.method = "get";
var minorColour='#0A3';
  form.action = document.location;
return ec.histogramCell( scale, [(count-minor)/total, nonMinorColour, "non-minor edits",
minor/total, minorColour, "minor edits"]);
},
   
   
ajax: {
  document.getElementById("username").focus();
download:function(bundle) {
  }
// mandatory: bundle.url
}
// optional:  bundle.onSuccess (xmlhttprequest, bundle)
// optional:  bundle.onFailure (xmlhttprequest, bundle)
// optional:  bundle.otherStuff OK too, passed to onSuccess and onFailure
   
   
var x = window.XMLHttpRequest ? new XMLHttpRequest()
function generate_main_report() {
: window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP")
  fetch_data(params["username"].replace(/\+/g, " "),
: false;
"", output_main_report, 0, []);
}
   
   
if (x) {
x.onreadystatechange=function() {
x.readyState==4 && ec.ajax.downloadComplete(x,bundle);
};
x.open("GET",bundle.url,true);
x.send(null);
}
return x;
},
   
   
downloadComplete:function(x,bundle) {
function add_stats_row(left_col, right_col) {
x.status==200 && ( bundle.onSuccess && bundle.onSuccess(x,bundle) || true )
var row = document.createElement("tr");
|| ( bundle.onFailure && bundle.onFailure(x,bundle) || alert(x.statusText));
var left = document.createElement("td");
}
var right = document.createElement("td");
},
   
   
document.getElementById("basic_stats").appendChild(row);
row.appendChild(left);
row.appendChild(right);
//left.innerHTML = left_col;
left.appendChild( document.createTextNode(left_col) );
right.appendChild( document.createTextNode(right_col) );
return row;
}
   
   
getContribs: function(user, startAt) {
function output_main_report(history) {
var limit=500; // currently maximum allowed per page by query.php
// -- generate summary statistics
var url='http://en.wikipedia.org/w/query.php?what=usercontribs' +
var unique_articles = new Array();
'&uccomments' + // enable for edit comment analysis
var namespace_numedits = new Array();
'&format=json&uclimit=500&titles=User:'+escape(user);
for (var i=0; i<namespaces.length; i++) {
if (startAt) { url += '&ucend=' + startAt.replace(/[^0-9]/g, ''); }
namespace_numedits[ namespaces[i] ] = 0;
ec.ajax.download({ url: url, user: user,
}
  startAt: startAt, onSuccess: ec.readContribs,
namespace_numedits[""] = 0;
  limit: limit});
for (var i=0; i<history.length; i++) {
},
var h = history[i];
unique_articles[  h["title"] ]++;
namespace_numedits[  h["namespace"] ]++;
}
var unique_articles_keys = keys(unique_articles);
   
   
readContribs: function(dl, bundle) {
// -- output report
window.dl=dl;
var table = document.createElement("table");
window.bundle=bundle;
table.id = "basic_stats";
try {
document.getElementById("bodyContent").appendChild(table);
eval('var jsobj=' + dl.responseText);
var pages=jsobj.pages;
var child=ec.anyChild(pages);
var contribs=child.contributions;
} catch (summat) {
throw new Error('Badness happened in readContribs: ' + summat.message);
return;
}
var i=0, j=0;
var minrev=null;
for (var c in contribs) {
++i;
var cc=contribs[c];
if (!minrev || cc.revid < minrev) { minrev = cc.revid; }
if (ec.edits[cc.revid]) { continue; }
++j;
ec.doStats(cc);
ec.edits[cc.revid] = cc;
}
ec.count += j;
if (i == bundle.limit && ec.edits[minrev]) {
ec.getContribs(bundle.user, ec.edits[minrev].timestamp);
} else {
ec.complete=true;
minrev && (ec.firstEdit=ec.edits[minrev].timestamp);
}
},
   
   
doStats: function (c) {
add_stats_row("Username", params["username"].replace(/\+/g, " "));
var k=c.ns || 0;
add_stats_row("Total edits", history.length);
//if (!ec.namespaces[k]) { console.log('New namespace: '+k + ', title=' +c['*'] +
add_stats_row("Distinct pages edited", unique_articles_keys.length);
// ', alleged NS=' + ec.namespace_names[k]); }
add_stats_row("Average edits/page", new Number(history.length / unique_articles_keys.length).toFixed(3));
if (!ec.namespaces[k]) { ec.namespaces[k] = {articles: {}}; }
add_stats_row("First edit", history[ history.length-1 ]["date_text"] );
var n = ec.namespaces[k];
incr(n, 'count');
if (!n.articles[c['*']]) { incr(n, 'articleCount'); }
incr(n.articles, c['*']);
if (typeof c.minor != 'undefined') { incr(n, 'minorCount'); }
if (typeof c.top != 'undefined') { incr(n, 'topCount'); }
if (typeof c['new'] != 'undefined') { incr(n, 'newCount'); }
if (c.comment) {
incr(n, 'commentCount');
if (!RegExp("^/[*].*?[*]/ *$").test(c.comment)) {
incr(n, 'manualCommentCount');
}
}
this.editlist.add({key: parseInt(c.timestamp.replace(/[^0-9]/g, ''), 10),
  edit: c,
  stats: this.saveStats()});
// more stuff here, perhaps
},
   
   
saveStats: function() {
// add a blank row
var r={};
add_stats_row("", "").childNodes[0].style.height = "1em";
var list=['count', 'articleCount', 'minorCount', 'topCount',
  'newCount', 'commentCount', 'manualCommentCount'];
for (var k in ec.namespaces) {
r[k]=getStuff(ec.namespaces[k],list);
}
return r;
},
   
   
anyChild: function(obj) {
add_stats_row("(main)", namespace_numedits[""]);
for (var p in obj) {
for (var i=0; i<namespaces.length; i++) {
return obj[p];
var nmspc = namespaces[i];
if (namespace_numedits[nmspc]) {
add_stats_row(nmspc, namespace_numedits[nmspc]);
}
}
return null;
}
},
}
   
   
edits: {},
count: 0,
complete: false,
namespaces: {},
namespace_names: {0: 'Article', 1: 'Talk',
  2: 'User', 3: 'User talk',
  4: 'Wikipedia', 5: 'Wikipedia talk',
  6: 'Image', 7: 'Image talk',
  8: 'MediaWiki', 9:'MediaWiki talk',
  10: 'Template', 11: 'Template talk',
  12: 'Help', 13: 'Help talk',
  14: 'Category', 15: 'Category talk',
  100: 'Portal', 101: 'Portal talk' // no comma
},
firstEdit: 0,
editlist: new linkedList(
{key: 99990101011200, stats: {}},
{key: 0, stats: {}}),
   
   
dummy: null // no comma
};
   
   
// ===================================== HTML-scraping backend =========================================
   
   
window.incr=function(obj, key) {
function add_loading_notice() {
if (!obj[key]) { obj[key]=1; }
if (document.getElementById("loading_notice"))
else { obj[key]++; }
return;
var loading = document.createElement("div");
loading.id = "loading_notice";
loading.innerHTML = "<br><br>Retrieving data<blink>...</blink>";
document.getElementById("bodyContent").appendChild(loading);
}
function remove_loading_notice() {
var loading = document.getElementById("loading_notice");
if (!loading) return;
loading.parentNode.removeChild(loading);
}
}
   
   
window.objSum=function(obj, x, y) {
var offset_regexp = /href="[^"]+:Contributions[^"]+offset=(\d+)/gi;
var r=0;
function fetch_data(username, end_date, handler, offset, page_list) {
if (x && y) { for (var k in obj) { r+= (obj[k][x][y] ? obj[k][x][y] : 0); } }
add_loading_notice();
else if (x) { for (var k in obj) { r+= (obj[k][x] ? obj[k][x] : 0); } }
var url = prefix + "Special:Contributions/" + username + "?offset=" + offset + "&limit=5000";
else        { for (var k in obj) { r+= (obj[k] ? obj[k] : 0); } }
loadXMLDoc(url,
return r;
function (request) {
}
var next_offset = 0;
if (request.readyState != 4)   return;
if (request.status == 200) {
page_list.push(request.responseText);
//dump_text(request.responseText);
   
   
window.percent=function(n, N) {
// see if there's another pageful to get
return Math.floor(n/N * 1000 + .5)/10;
var matches = map( function(p){
};
return p.match( /(\d+)$/ )[0];
}, request.responseText.match( offset_regexp ) );
for (var i=0; i<matches.length; i++) {
var v = matches[i] * 1;
if (v != 0 && (offset == 0 || v < offset)) {
next_offset = v;
break;
}
}
}
   
   
if((user=ec.getParamValue('ectarget'))!==null) { addOnloadHook(function(){ec.doEditCount(user);}); }
//next_offset = 0; // for testing only, retrieve just the first page of results
   
   
function linkedList(x0,y0) {
if (next_offset == 0) {
this.first=null;
parse_data(page_list, handler);
this.last=null;
} else {
this.hash={};
// tail recurse
this.add=function(x) {
fetch_data(username, end_date, handler, next_offset, page_list);
this.hash[x.key]=x;
if (!this.first) {
this.first=x;
this.last=x;
x.prev=x.next=null;
return;
}
var k=x.key;
if (true || k - this.first.key < this.last.key - k) {
this.pushTop(x);
} else {
this.pushTail(x);
}
};
this.pushTop=function(x) {
if (x.key < this.first.key) {
this.first.prev=x;
x.next=this.first;
this.first=x;
x.prev=null;
return;
}
if (x.key > this.last.key) {
this.last.next=x;
x.prev=this.last;
this.last=x;
x.next=null;
}
for (var y=this.first; y.next; y=y.next) {
if (y.key < x.key && x.key <= y.next.key) {
this.insertAfter(y, x);
return;
}
}
};
this.pushTail=function(x) {
for (var y=this.last; y.prev; y=y.prev) {
if (y.prev.key < x.key && x.key <= y.key) {
this.insertAfter(y.prev, x);
return;
}
}
}
});
this.first.prev=x;
x.next=this.first;
this.first=x;
x.prev=null;
};
this.insertAfter=function(y,x) {
x.next=y.next;
x.prev=y;
y.next.prev=x;
y.next=x;
};
if (x0) { this.add(x0); }
if (y0) { this.add(y0); }
}
}
   
   
window.getStuff=function(obj, list) {
var r={};
for (var i=0; i<list.length; ++i) {
if (typeof obj[list[i]] != 'undefined') { r[list[i]]=obj[list[i]]; }
}
return r;
}
   
   
window.IntervalSelector=function(data) {
// input: a list of strings, each string containing the HTML from a single page
if (!data) { data={}; }
// output: a list, where each individual entry is a specific edit from history
this.min=data.min || 10;
function parse_data(page_list, handler) {
this.max=data.max || 100;
//var total_len = 0;
this.span=this.max-this.min;
//for (var i=0; i<page_list.length; i++) total_len += page_list[i].length;
this.lo=data.lo || this.min;
//alert("parsing " + page_list.length + " pages comprising " + total_len + " total bytes");
this.hi=data.hi || this.max;
this.width=data.width || 400;
this.height=data.height || 20;
this.scale=this.width/this.span;
this.minBarWidth=data.minBarWidth || 10;
this.oldmousemove = null;
this.createDiv();
}
   
   
var last_history_ent = [];
last_history_ent["title"] = "";
last_history_ent["oldid"] = "";
   
   
IntervalSelector.prototype.createDiv=function() {
var edit_history = new Array();
var d=document.createElement('div');
for (var pagecnt=0; pagecnt<page_list.length; pagecnt++) {
d.className='intervalselectorbox';
var matches = page_list[pagecnt].match( /^<li>[^(]+\(<a href="[^"]+action=history.*/gim );
//d.style.position='absolute';
//dump_lines(matches);
d.style.border='1px solid black'; // FIXME
for (var matchcnt=0; matchcnt<matches.length; matchcnt++) {
var s=document.createElement('div');
var history_text = matches[matchcnt];
s.className='intervalselector';
s.style.position='relative';
s.style.background='orange'; // FIXME
//s.style.border='2px solid red'; // FIXME
d.appendChild(s);
this.box=d;
this.bar=s;
var this2=this;
this.bar.onmousedown=function(e){ this2.mouseDown.apply(this2, [e]); }
this.box.onmousedown=function(e){ this2.mouseDown.apply(this2, [e]); }
this.updatePosition();
};
   
   
IntervalSelector.prototype.updatePosition=function() {
var history_entry = new Array();
var d=this.box;
history_entry["date_text"] = history_text.match( /^<li>([^(<]+)/i )[1]
d.style.width=this.width+'px';
.replace( / +$/, "");
d.style.height=this.height+'px';
history_entry["date"] = date_parse( history_entry["date_text"] );
var s=this.bar;
history_entry["title"] = history_text.match( /title="([^"]+)"/i )[1]
s.style.left=(this.lo-this.min)*this.scale+ 'px';
.replace( /&quot;/g, "\"")
s.style.width=(this.hi-this.lo)*this.scale + 'px';
.replace( /&amp;/g, "&");
s.style.height=this.height + 'px';
var find_comment = history_text.replace(/<span class="autocomment">.*?<\/span> ?/, "");
};
history_entry["comment"] = ifmatch(find_comment.match( /<span class='comment'>(.*?)<\/span>/ ))
.replace(/^\((.*)\)$/, "$1");
history_entry["minor"] = /<span class="minor"/.test(history_text);
history_entry["oldid"] = ifmatch(history_text.match(/oldid=([0-9]+)/i));
   
   
IntervalSelector.prototype.mouseDown=function(e) {
history_entry["namespace"] = "";
var endWidth=8;
for (var nmspc_ctr=0; nmspc_ctr<namespaces.length; nmspc_ctr++) {
var pos=this.getMousePos(e);
var nmspc = namespaces[nmspc_ctr] + ":";
var this2=this;
if (history_entry["title"].substring(0, nmspc.length) == nmspc) {
history_entry["namespace"] = namespaces[nmspc_ctr];
break;
}
}
   
   
var dragFunction=null;
//dump_object(history_entry);
var leftPos=findPosX(this.bar);
if (pos.x - leftPos < endWidth) { dragFunction=this2.dragLo; }
if (history_entry["title"] != last_history_ent["title"] || history_entry["oldid"] != last_history_ent["oldid"])
else if ( leftPos + parseInt(this.bar.style.width, 10) - pos.x < endWidth) { dragFunction=this2.dragHi; }
edit_history.push(history_entry);
else { dragFunction = this2.dragBar; }
last_history_ent = history_entry;
var x=pos.x, lo=this.lo;
}
if (document.onmousemove && document.onmousemove.origin != 'IntervalSelector') {
this.oldmousemove = document.onmousemove;
}
}
document.onmousemove=function(e) {
dragFunction.apply(this2, [e, x, lo]);
this2.dragging.apply(this2);
};
document.onmousemove.origin='IntervalSelector';
document.onmouseup=function() {
//console.log(this2.oldmousemove.toString());
document.onmousemove= this2.oldmousemove;
this2.doneDrag.apply(this2);
};
document.onmouseup.origin='IntervalSelector';
//document.title=pos.x;
};
   
   
IntervalSelector.prototype.doneDrag=function(){};
remove_loading_notice();
IntervalSelector.prototype.dragging=function(){};
handler(edit_history);
}
   
   
IntervalSelector.prototype.dragLo=function(e) {
var pos=this.getMousePos(e);
var newLo=this.min + (pos.x - findPosX(this.box))/this.scale;
if (newLo < this.min) { newLo=this.min; }
else if (newLo > this.hi - this.minBarWidth/this.scale) { newLo=this.hi - this.minBarWidth/this.scale; }
this.lo=newLo;
this.updatePosition();
};
   
   
IntervalSelector.prototype.dragHi=function(e) {
var pos=this.getMousePos(e);
var newHi=this.min + (pos.x - findPosX(this.box))/this.scale;
if (newHi > this.max) { newHi=this.max; }
else if (newHi < this.lo + this.minBarWidth/this.scale) { newHi=this.lo + this.minBarWidth/this.scale; }
this.hi=newHi;
this.updatePosition();
};
   
   
IntervalSelector.prototype.dragBar=function(e, x0, l0) {
var pos=this.getMousePos(e);
var delta=pos.x-x0;
var newLo=l0 + delta/this.scale;
var newHi=newLo + this.hi-this.lo;
if (newLo < this.min) { newLo=this.min; newHi=newLo+this.hi-this.lo; }
else if (newHi > this.max) { newHi=this.max; newLo=newHi-(this.hi-this.lo); }
this.hi=newHi; this.lo=newLo;
this.updatePosition();
};
   
   
IntervalSelector.prototype.getMousePos=function(e) {
// ===================================== test/debug functions =========================================
e = e || window.event;
var x, y;
if (e) {
if (e.pageX) { x=e.pageX; y=e.pageY; }
else if (typeof e.clientX!='undefined') {
var left, top, docElt = window.document.documentElement;
   
   
if (docElt) { left=docElt.scrollLeft; }
function dump_text(text) {
left = left || window.document.body.scrollLeft || window.document.scrollLeft || 0;
  //alert("dump_text, with text of size " + text.length);
   
   
if (docElt) { top=docElt.scrollTop; }
  var pre = document.createElement("pre");
top = top || window.document.body.scrollTop || window.document.scrollTop || 0;
   
   
x=e.clientX + left;
  var div = document.createElement("div");
y=e.clientY + top;
  div.style.width = "60em";
} else { throw new Error ('bad mouse wiggle event in getMousePos'); return; }
  div.style.maxHeight = "40em";
}
  div.style.overflow = "auto";
return {x:x, y:y};
};
   
   
window.findPosX=function(obj)
  pre.appendChild(document.createTextNode(text));
{
  div.appendChild(pre);
var curleft = 0;
  document.getElementById("bodyContent").appendChild(div);
if (obj.offsetParent)
{
while (obj.offsetParent)
{
curleft += obj.offsetLeft
obj = obj.offsetParent;
}
}
else if (obj.x)
curleft += obj.x;
return curleft;
}
}
   
   
window.ts2unix=function(ts) {
function dump_lines(ary) {
var t=ts.toString();
  dump_text("--> " + ary.join("\n--> "));
return +(Date.UTC( t.substring(0,4), parseInt(t.substring(4,6),10)-1, t.substring(6,8),
  t.substring(8,10), t.substring(10,12), t.substring(12,14)));
}
}
window.unix2ts=function(u) {
var d=new Date(u);
function dump_object(obj) {
return map(zeroFill, [d.getUTCFullYear(), d.getUTCMonth()+1,
var toString = "";
      d.getUTCDate(), d.getUTCHours(),
for (var prop in obj) {
      d.getUTCMinutes(), d.getUTCSeconds()]).join('');
toString += prop + ": " + obj[prop] + "\n";
}
dump_text(toString);
}
}
   
   
window.zeroFill=function(s, min) {
min = min || 2;
// ===================================== utility functions =========================================
var t=s.toString();
return repeatString('0', min - t.length) + t;
function addOnloadFunction(f) {
  if (window.addEventListener) window.addEventListener("load",f,false);
  else if (window.attachEvent) window.attachEvent("onload",f);
  else {
    var oldOnload='_old_onload_'+addOnloadFunction.uid;
    addOnloadFunction[oldOnload] = window.onload ? window.onload : function () {};
    window.onload = function() { addOnloadFunction[oldOnload]();  f(); }
    ++addOnloadFunction.uid;
  }
}
}
   
   
window.map=function(f, o) {
if (isArray(o)) { return map_array(f,o); }
function parse_params() {
return map_object(f,o);
  var pairs = document.location.search.substring(1).split("&");
  var ret = [];
  for (var i=0; i < pairs.length; i++) {
    var values = pairs[i].split("=");
    ret[values[0]] = unescape(values[1]);
  }
  return ret;  
}
}
window.isArray =function(x) { return x instanceof Array; }
   
   
window.map_array=function(f,o) {
var ret=[];
function loadXMLDoc(url, handler)
for (var i=0; i<o.length; ++i) {
{
ret.push(f(o[i]));
    // branch for native XMLHttpRequest object
}
    if (window.XMLHttpRequest) {
return ret;
        req = new XMLHttpRequest();
req.onreadystatechange = function () {handler(req)};
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function () {handler(req)};
            req.open("GET", url, true);
            req.send();
        }
    }
}
}
   
   
window.map_object=function(f,o) {
var ret={};
// see http://search.cpan.org/dist/perl/pod/perlfunc.pod#map
for (var i in o) { ret[o]=f(o[i]); }
function map (handler, list) {
return ret;
  var ret = new Array();
  for (var i=0; i<list.length; i++) {
    ret[i] = handler( list[i] );
    // ret.push( handler( list[i] ) );
  }
  return ret;
}
}
   
   
window.repeatString=function(s,mult) {
// see http://search.cpan.org/dist/perl/pod/perlfunc.pod#keys
var ret='';
function keys (obj) {
for (var i=0; i<mult; ++i) { ret += s; }
var ret = new Array();
for (var key in obj) {
ret.push(key);
}
return ret;
return ret;
};
}
   
   
window.formatTs=function(ts) {
ts=ts.toString();
if (ts.substring(0,4)=='9999') { return 'now'; }
return [ts.substring(0,4), ts.substring(4,6), ts.substring(6,8)].join('-') +
' ' + [ts.substring(8,10),ts.substring(10,12),ts.substring(12,14)].join(':');
};
   
   
function isMethodOf(klass, fn) {
function ifmatch(ary) {
for (var f in klass.prototype) {
if (ary && ary.length >= 2) {
if (fn===klass.prototype[f]) { return true; }
return ary[1];
} else {
return "";
}
}
return false;
}
}
//</nowiki></pre>
//ec.doEditCount('Amanda77')
// ec.doEditCount('Llama man')

20.11, 3 Mayıs 2009 tarihindeki hâli

// see http://paperlined.org/apps/wikipedia/Tool2/ for instructions on adding this to your monobook.js
 
// To run this tool on other servers:
//	1. copy this script to the target server (this is required because of javascript cross-site security restrictions)
 
//	2. update the following URL
//		for example: "User:Interiot/Tool2/code.js"
var tool2_url = "User:Interiot/Tool2/code.js";
 
//	3. update this namespace list, extracted from something like http://en.wikiquote.org/wiki/Special:Export//
//			These *should not* have colons after them.
var namespaces = [
"Talk",
"User",
"User talk",
"Wikiquote",
"Wikiquote talk",
"Image",
"Image talk",
"MediaWiki",
"MediaWiki talk",
"Template",
"Template talk",
"Help",
"Help talk",
"Category",
"Category talk",
		// 3b. these two project project entries are not added by Special:Export, and might or might not need to be updated
"Wikipedia",
"Wikipedia talk"
];
 
namespaces[100] = "Portal";
namespaces[101] = "Portal talk";
 
//	4. update this date-parser to match the format and language of your specific wiki.  Feel free to contact Interiot regarding this, if you can't find another
//		copy of this script that uses the same language.
// input: a text string from Special:Contributions.    output: a javascript Date object
// documentation:  http://www.quirksmode.org/js/introdate.html#parse, http://www.elated.com/tutorials/programming/javascript/dates/
function date_parse(text) {
	var matches = text.match(/^([0-9:]+), +([0-9]+) +([a-z]+) +([0-9]+)$/i);
	if (!matches) {
		//dump_text("XXX");			// for debugging
		return matches;
	}
 
	parseme = matches[3] + ", " + matches[2] + " "  + matches[4] + " " + matches[1] + ":00";
 
	//dump_text(parseme);				// for debugging
 
	var dt = new Date();
	dt.setTime( Date.parse(parseme));
 
	//dump_text(dt.toLocaleString());		// for debugging
 
	return dt;
}
 
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ end of server-specific configuration ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 
 
// TODO:
//	- the current document.location method doesn't work when the page is accessed sans-mod_rewrite
//	- test with non-ASCII characters
//		- non-ascii usernames
//		- ??
 
 
 
var prefix = "";
var params = parse_params();
 
addOnloadFunction(function() {
  var path_len = document.location.pathname.length;
  // trigger once we view the right page
  if (document.location.pathname.substring(path_len - tool2_url.length, path_len) == tool2_url) {
    // get the prefix (needs to be fixed to work sans-mod_rewrite
    prefix = document.location.protocol + "//" + document.location.host + "/"
            + document.location.pathname.substring(1, path_len - tool2_url.length);
 
    // blank the inner contents of the page
    var bodyContent = document.getElementById("bodyContent");
    while (bodyContent.childNodes.length > 0) bodyContent.removeChild(bodyContent.lastChild);
 
    //if (document.location.search.length == 0) {
      //generate_input_form(bodyContent);
    //} else {
      //generate_main_report(bodyContent);
    //}
    generate_redirect_notice(bodyContent);
  }
});
 
function generate_redirect_notice(bodyContent) {
  bodyContent.innerHTML = "This counter doesn't currently work.  Please use <a href='http://tools.wikimedia.de/~interiot/cgi-bin/Tool1/wannabe_kate'>Tool1</a> or <a href='http://en.wikipedia.org/wiki/Wikipedia:WikiProject_edit_counters'>one of the other edit counters</a>.";
}
 
function generate_input_form(bodyContent) {
  if (navigator.userAgent.toLowerCase().indexOf('msie')+1)
  {
  bodyContent.innerHTML = "This counter does not currently work in Internet Explorer.  Please <a href='http://www.getfirefox.com'>get Firefox</a> or use <a href='http://en.wikipedia.org/wiki/Wikipedia:WikiProject_edit_counters/Flcelloguy%27s_Tool'>Flcelloguy's Tool</a> instead.";
  }
  else
  {
  bodyContent.innerHTML =
            "<form><table><tr><td>Username <td><input maxlength=128 name=username value='' id=username title='username'>" +
            "             <tr><td>         <td><input type=submit value='Submit'>" +
            "</table></form>";
 
  var form = bodyContent.getElementsByTagName("form")[0];
  form.method = "get";
  form.action = document.location;
 
  document.getElementById("username").focus();
  }
}
 
function generate_main_report() {
  fetch_data(params["username"].replace(/\+/g, " "),
		"", output_main_report, 0, []);
}
 
 
	function add_stats_row(left_col, right_col) {
		var row = document.createElement("tr");
		var left = document.createElement("td");
		var right = document.createElement("td");
 
		document.getElementById("basic_stats").appendChild(row);
		row.appendChild(left);
		row.appendChild(right);
		//left.innerHTML = left_col;
		left.appendChild( document.createTextNode(left_col) );
		right.appendChild( document.createTextNode(right_col) );
		return row;
	}
 
function output_main_report(history) {
	// -- generate summary statistics
	var unique_articles = new Array();
	var namespace_numedits = new Array();
	for (var i=0; i<namespaces.length; i++) {
		namespace_numedits[ namespaces[i] ] = 0;
	}
	namespace_numedits[""] = 0;
	for (var i=0; i<history.length; i++) {
		var h = history[i];
		unique_articles[  h["title"] ]++;
		namespace_numedits[  h["namespace"] ]++;
	}
	var unique_articles_keys = keys(unique_articles);
 
	// -- output report
	var table = document.createElement("table");
	table.id = "basic_stats";
	document.getElementById("bodyContent").appendChild(table);
 
	add_stats_row("Username", params["username"].replace(/\+/g, " "));
	add_stats_row("Total edits", history.length);
	add_stats_row("Distinct pages edited", unique_articles_keys.length);
	add_stats_row("Average edits/page", new Number(history.length / unique_articles_keys.length).toFixed(3));
	add_stats_row("First edit", history[ history.length-1 ]["date_text"] );
 
	// add a blank row
	add_stats_row("", "").childNodes[0].style.height = "1em";
 
	add_stats_row("(main)", namespace_numedits[""]);
	for (var i=0; i<namespaces.length; i++) {
		var nmspc = namespaces[i];
		if (namespace_numedits[nmspc]) {
			add_stats_row(nmspc, namespace_numedits[nmspc]);
		}
	}
}
 
 
 
// ===================================== HTML-scraping backend =========================================
 
function add_loading_notice() {
	if (document.getElementById("loading_notice"))
		return;
	var loading = document.createElement("div");
	loading.id = "loading_notice";
	loading.innerHTML = "<br><br>Retrieving data<blink>...</blink>";
	document.getElementById("bodyContent").appendChild(loading);
}
function remove_loading_notice() {
	var loading = document.getElementById("loading_notice");
	if (!loading) return;
	loading.parentNode.removeChild(loading);
}
 
var offset_regexp = /href="[^"]+:Contributions[^"]+offset=(\d+)/gi;
function fetch_data(username, end_date, handler, offset, page_list) {
	add_loading_notice();
	var url = prefix + "Special:Contributions/" + username + "?offset=" + offset + "&limit=5000";
	loadXMLDoc(url, 
		function (request) {
			var next_offset = 0;
			if (request.readyState != 4)   return;
			if (request.status == 200) {
				page_list.push(request.responseText);
				//dump_text(request.responseText);
 
				// see if there's another pageful to get
				var matches = map( function(p){
						return p.match( /(\d+)$/ )[0];
					}, request.responseText.match( offset_regexp ) );
				for (var i=0; i<matches.length; i++) {
					var v = matches[i] * 1;
					if (v != 0 && (offset == 0 || v < offset)) {
						next_offset = v;
						break;
					}
				}
			}
 
			//next_offset = 0;			// for testing only, retrieve just the first page of results
 
			if (next_offset == 0) {
				parse_data(page_list, handler);
			} else {
				// tail recurse
				fetch_data(username, end_date, handler, next_offset, page_list);
			}
		});
}
 
 
// input: a list of strings, each string containing the HTML from a single page
// output: a list, where each individual entry is a specific edit from history
function parse_data(page_list, handler) {
	//var total_len = 0;
	//for (var i=0; i<page_list.length; i++) total_len += page_list[i].length;
	//alert("parsing " + page_list.length + " pages comprising " + total_len + " total bytes");
 
	var last_history_ent = [];
	last_history_ent["title"] = "";
	last_history_ent["oldid"] = "";
 
	var edit_history = new Array();
	for (var pagecnt=0; pagecnt<page_list.length; pagecnt++) {
		var matches = page_list[pagecnt].match( /^<li>[^(]+\(<a href="[^"]+action=history.*/gim );
		//dump_lines(matches);
		for (var matchcnt=0; matchcnt<matches.length; matchcnt++) {
			var history_text = matches[matchcnt];
 
			var history_entry = new Array();
			history_entry["date_text"] = history_text.match( /^<li>([^(<]+)/i )[1]
					.replace( / +$/, "");
			history_entry["date"] = date_parse( history_entry["date_text"] );
			history_entry["title"] = history_text.match( /title="([^"]+)"/i )[1]
					.replace( /&quot;/g, "\"")
					.replace( /&amp;/g, "&");
			var find_comment = history_text.replace(/<span class="autocomment">.*?<\/span> ?/, "");
			history_entry["comment"] = ifmatch(find_comment.match( /<span class='comment'>(.*?)<\/span>/ ))
					.replace(/^\((.*)\)$/, "$1");
			history_entry["minor"] = /<span class="minor"/.test(history_text);
			history_entry["oldid"] = ifmatch(history_text.match(/oldid=([0-9]+)/i));
 
			history_entry["namespace"] = "";
			for (var nmspc_ctr=0; nmspc_ctr<namespaces.length; nmspc_ctr++) {
				var nmspc = namespaces[nmspc_ctr] + ":";
				if (history_entry["title"].substring(0, nmspc.length) == nmspc) {
					history_entry["namespace"] = namespaces[nmspc_ctr];
					break;
				}
			}
 
			//dump_object(history_entry);
 
			if (history_entry["title"] != last_history_ent["title"] || history_entry["oldid"] != last_history_ent["oldid"])
				edit_history.push(history_entry);
			last_history_ent = history_entry;
		}
	}
 
	remove_loading_notice();
 
	handler(edit_history);
}
 
 
 
 
// ===================================== test/debug functions =========================================
 
function dump_text(text) {
  //alert("dump_text, with text of size " + text.length);
 
  var pre = document.createElement("pre");
 
  var div = document.createElement("div");
  div.style.width = "60em";
  div.style.maxHeight = "40em";
  div.style.overflow = "auto";
 
  pre.appendChild(document.createTextNode(text));
  div.appendChild(pre);
  document.getElementById("bodyContent").appendChild(div);
}
 
function dump_lines(ary) {
  dump_text("--> " + ary.join("\n--> "));
}
 
function dump_object(obj) {
	var toString = "";
	for (var prop in obj) {
		toString += prop + ": " + obj[prop] + "\n";
	}
	dump_text(toString);
}
 
 
// ===================================== utility functions =========================================
 
function addOnloadFunction(f) {
  if (window.addEventListener) window.addEventListener("load",f,false);
  else if (window.attachEvent) window.attachEvent("onload",f);
  else {
    var oldOnload='_old_onload_'+addOnloadFunction.uid;
    addOnloadFunction[oldOnload] = window.onload ? window.onload : function () {};
    window.onload = function() { addOnloadFunction[oldOnload]();  f(); }
    ++addOnloadFunction.uid;
  }
}
 
 
function parse_params() {
  var pairs = document.location.search.substring(1).split("&");
  var ret = [];
  for (var i=0; i < pairs.length; i++) {
    var values = pairs[i].split("=");
    ret[values[0]] = unescape(values[1]);
  }
  return ret; 
}
 
 
function loadXMLDoc(url, handler)
{
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
	req.onreadystatechange = function () {handler(req)};
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function () {handler(req)};
            req.open("GET", url, true);
            req.send();
        }
    }
}
 
 
// see http://search.cpan.org/dist/perl/pod/perlfunc.pod#map
function map (handler, list) {
  var ret = new Array();
  for (var i=0; i<list.length; i++) {
    ret[i] = handler( list[i] );
    // ret.push( handler( list[i] ) );
  }
  return ret;
}
 
// see http://search.cpan.org/dist/perl/pod/perlfunc.pod#keys
function keys (obj) {
	var ret = new Array();
	for (var key in obj) {
		ret.push(key);
	}
	return ret;
}
 
 
function ifmatch(ary) {
	if (ary && ary.length >= 2) {
		return ary[1];
	} else {
		return "";
	}
}