کاربر:MohandesWiki/common.js: تفاوت میان نسخه‌ها

محتوای حذف‌شده محتوای افزوده‌شده
MohandesWiki (بحث | مشارکت‌ها)
بدون خلاصۀ ویرایش
MohandesWiki (بحث | مشارکت‌ها)
بدون خلاصۀ ویرایش
خط ۱:
function UserinfoJsFormatQty(qty, singular, plural) {
/* This script will classify as many links as possible and assign CSS classes
return String(qty).replace(/\d{1,3}(?=(\d{3})+(?!\d))/g, "$&,") + "\u00a0" + (qty == 1 ? singular : plural);
accordingly. See the complete script documentation for usage and more details.
}
 
function UserinfoJsFormatDateRel(old) {
Key acknowledgement goes to User:Anomie whose script (User:Anomie/linkclassifier.js)
// The code below requires the computer's clock to be set correctly.
was used as an initial template structure to get up an running quickly with MW api. Go
var age = new Date().getTime() - old.getTime();
check it out if you're interested in a lot more ways to classify and color various MW links.
var ageNumber, ageRemainder, ageWords;
*/
if(age < 60000) {
 
// less than one minute old
var AQFetcher={
ageNumber = Math.floor(age / 1000);
ageWords = UserinfoJsFormatQty(ageNumber, "second", "seconds");
} else if(age < 3600000) {
// less than one hour old
ageNumber = Math.floor(age / 60000);
ageWords = UserinfoJsFormatQty(ageNumber, "minute", "minutes");
} else if(age < 86400000) {
// less than one day old
ageNumber = Math.floor(age / 3600000);
ageWords = UserinfoJsFormatQty(ageNumber, "hour", "hours");
ageRemainder = Math.floor((age - ageNumber * 3600000) / 60000);
} else if(age < 604800000) {
// less than one week old
ageNumber = Math.floor(age / 86400000);
ageWords = UserinfoJsFormatQty(ageNumber, "day", "days");
} else if(age < 2592000000) {
// less than one month old
ageNumber = Math.floor(age / 604800000);
ageWords = UserinfoJsFormatQty(ageNumber, "week", "weeks");
} else if(age < 31536000000) {
// less than one year old
ageNumber = Math.floor(age / 2592000000);
ageWords = UserinfoJsFormatQty(ageNumber, "month", "months");
} else {
// one year or older
ageNumber = Math.floor(age / 31536000000);
ageWords = UserinfoJsFormatQty(ageNumber, "year", "years");
ageRemainder =
Math.floor((age - ageNumber * 31536000000) / 2592000000);
if(ageRemainder) {
ageWords += " " +
UserinfoJsFormatQty(ageRemainder, "month", "months");
}
}
return ageWords;
}
 
// If on a user or user talk page, and not a subpage...
articleClasses: { 'FA':[], 'GA':[], 'A':[], 'B':[], 'C':[], 'Start':[], 'Stub':[], 'Unclassified':[] },
if((mw.config.get("wgNamespaceNumber") == 2 || mw.config.get("wgNamespaceNumber") == 3) && !(/\//.test(mw.config.get("wgTitle")))) {
// add a hook to...
callback:function(r, sts, xhr){
mw.loader.using( ['es5-shim', 'mediawiki.util'], function() { $(function(){
if(!r.query) {
// Request the user's information from the API.
if(typeof(window.console)=='undefined' || typeof(window.console.error)!='function')
// Note that this is allowed to be throwup newto Error('Bad5 response');minutes old.
var et = windowencodeURIComponent(mw.consoleconfig.errorget("Bad responsewgTitle", r));
return;
$.getJSON(mw.config.get("wgScriptPath") + "/api.php?format=json&action=query&list=users|usercontribs&usprop=blockinfo|editcount|gender|registration|groups&uclimit=1&ucprop=timestamp&ususers=" + et + "&ucuser=" + et + "&meta=allmessages&amprefix=grouppage-&amincludelocal=1")
}
if.done(function(r['query-continue']) {
// When response arrives extract the information we need.
var cc=this.rawdata;
if(!query.query) { return; } // Suggested by Gary King to avoid JS errors --PS 2010-08-25
for(var k in r['query-continue']){
query = for(var k2 in r['query-continue'][k]){.query;
var user, invalid, missing, groups, groupPages={}, editcount, registration, blocked, gender, lastEdited;
cc[k2]=r['query-continue'][k][k2];
try {
user = query.users[0];
invalid = typeof user.invalid != "undefined";
missing = typeof user.missing != "undefined";
groups = (typeof user.groups == "object") ? user.groups : [];
editcount = (typeof user.editcount == "number") ? user.editcount : null;
registration = (typeof user.registration == "string") ?
new Date(user.registration) : null;
blocked = typeof user.blockedby != "undefined";
gender = (typeof user.gender == "string") ? user.gender : null;
lastEdited = (typeof query.usercontribs[0] == "object") &&
(typeof query.usercontribs[0].timestamp == "string") ?
new Date(query.usercontribs[0].timestamp) : null;
for (var am=0; am<query.allmessages.length; am++) {
groupPages[query.allmessages[am]["name"].replace("grouppage-","")] = query.allmessages[am]["*"].replace("{{ns:project}}:","Project:");
}
} catch(e) {
return; // Not much to do if the server is returning an error (e.g. if the username is malformed).
}
$.ajax({
url:mw.util.wikiScript('api'),
dataType:'json',
type:'POST',
data:cc,
rawdata:cc,
success:arguments.callee,
error:function(xhr,textStatus,errorThrown){
throw new Error('AJAX error: '+textStatus+' '+errorThrown);
}
});
}
r=r.query;
 
// Format the information for on-screen display
var a=document.getElementById('wikiPreview');
if(!a) a=document.getElementById('bodyContent');
if(!a) throw new Error('Huh? Novar bodystatusText content?')= "";
var ipUser = false;
a=a.getElementsByTagName('A');
if(a.length= var ipv4User =0) returnfalse;
var ipv6User = false;
 
// HandyUser shortcutstatus
var AQF = AQFetcher; if(blocked) {
statusText += "<a href=\"" + mw.config.get("wgScriptPath") +
 
"/index.php?title=Special:Log&amp;page=" +
if(r.pages) for(var i in r.pages){
encodeURIComponent(mw.config.get("wgFormattedNamespaces")[2] + ":" + user.name) +
if(typeof(r.pages[i].categories)!='undefined'){
"&amp;type=block\">blocked</a> ";
}
if (missing) {
statusText += "username not registered";
} else if (invalid) {
ipv4User = mw.util.isIPv4Address(user.name);
ipv6User = mw.util.isIPv6Address(user.name);
ipUser = ipv4User || ipv6User;
if (ipv4User) {
statusText += "anonymous IPv4 user";
} else if (ipv6User) {
statusText += "anonymous IPv6 user";
} else {
statusText += "invalid username";
}
} else {
// User is registered and may be in a privileged group. Below we have a list of user groups.
// Only need the ones different from the software's name (or ones to exclude), though.
var friendlyGroupNames = {
// Exclude implicit user group information provided by MW 1.17 --PS 2010-02-17
'*': false,
'user': false,
'autoconfirmed': false,
sysop: "administrator",
accountcreator: "account creator",
'import': "importer",
transwiki: "transwiki importer",
'ipblock-exempt': "IP block exemption",
oversight: "oversighter",
confirmed: "confirmed user",
abusefilter: "edit filter manager",
autoreviewer: "autopatrolled user", // Group has been renamed --PS 2010-07-06
epcoordinator: "Education Program course coordinator",
epcampus: "Education Program campus volunteer",
eponline: "Education Program online volunteer",
filemover: "file mover",
'massmessage-sender': "mass message sender",
templateeditor: "template editor",
extendedconfirmed: "extended confirmed user",
extendedmover: "page mover",
'flow-bot': "Flow bot",
reviewer: "pending changes reviewer",
suppress: "suppressor"
};
var friendlyGroups = [];
// If the corresponding Talk: page has appropriately-named categories we can
//for(var matchi each= article0; pagei to< it'sgroups.length; classification++i) {
var s = groups[i];
 
unClassified var t = truefriendlyGroupNames.hasOwnProperty(s) ? friendlyGroupNames[s] : s;
iCat = 0; if (t) {
while (unClassified && iCat < if r(groupPages.pages[i].categories.lengthhasOwnProperty(s)) {
friendlyGroups.push("<a href=\"/wiki/" + encodeURIComponent( groupPages[s] ) + "\">" + t + "</a>");
if (r.pages[i].categories[iCat].title!='undefined') {
} if (r.pages[i].categories[iCat].title.indexOf('FA-Class') >= 0)else {
AQF.articleClasses['FA'] friendlyGroups.push(AQF.getPageNameFromTalkPage(r.pages[i].title)t);
unClassified = false; }
} else if (r.pages[i].categories[iCat].title.indexOf('A-Class') >= 0) {
}
AQF.articleClasses['A'].push(AQF.getPageNameFromTalkPage(r.pages[i].title));
switch(friendlyGroups.length) unClassified = false;{
} else if (r.pages[i].categories[iCat].title.indexOf('GA-Class') >=case 0) {:
// AQF.articleClasses['GA'].push(AQF.getPageNameFromTalkPage(r.pages[i].title));User not in a privileged group
// unClassifiedChanged =to false;"registered user" by request of [[User:Svanslyck]]
} else// if (r.pages[i].categories[iCat].title.indexOf('B-Class')-PS >= 0) {2010-05-16
AQF.articleClasses['B'].push(AQF.getPageNameFromTalkPage(r.pages[i].title));
// unClassifiedstatusText += false"user";
} else if (r.pages[i].categories[iCat].title.indexOf('C-Class') >= 0blocked) {
AQF.articleClasses['C'].push(AQF.getPageNameFromTalkPage(r.pages[i].title)) statusText += "user";
} unClassifiedelse = false;{
} else if (r.pages[i].categories[iCat].title.indexOf('Start-Class') > statusText += 0)"registered {user";
AQF.articleClasses['Start'].push(AQF.getPageNameFromTalkPage(r.pages[i].title));}
unClassified = falsebreak;
case } else if (r.pages[i].categories[iCat].title.indexOf('Stub-Class') >= 0) {1:
statusText AQF.articleClasses['Stub'].push(AQF.getPageNameFromTalkPage(r.pages+= friendlyGroups[i0].title));
unClassified = falsebreak;
case } 2:
} statusText += friendlyGroups[0] + " and " + friendlyGroups[1];
iCat+=1 break;
default:
statusText += friendlyGroups.slice(0, -1).join(", ") +
", and " + friendlyGroups[friendlyGroups.length - 1];
break;
}
if (unClassified) AQF.articleClasses['Unclassified'].push(AQF.getPageNameFromTalkPage(r.pages[i].title));
}
}
// Registration date
 
if(registration) {
Array.prototype.forEach.call(a, function(a){
var firstLoggedUser = new Date("22:16, 7 September 2005"); // When the [[Special:Log/newusers]] was first activated
if(typeof(a.wikipage)=='undefined') return;
if (AQF.articleClasses['FA'].indexOf(a.wikipage)registration >= 0firstLoggedUser) {
statusText += ", $(<a) href='" + mw.addClassconfig.get('AQ-FA'"wgScriptPath"); +
"/index.php?title=Special:Log&amp;type=newusers&amp;dir=prev&amp;limit=1&amp;user=" +
} else if (AQF.articleClasses['GA'].indexOf(a.wikipage) >= 0) {
et + "'>" + UserinfoJsFormatDateRel(registration) + "</a> old";
$(a).addClass('AQ-GA');
} else if (AQF.articleClasses['A'].indexOf(a.wikipage) >= 0) {
statusText += ", $(<a) href='" + mw.addClassconfig.get('AQ-A'"wgScriptPath"); +
"/index.php?title=Special:ListUsers&amp;limit=1&amp;username=" +
} else if (AQF.articleClasses['B'].indexOf(a.wikipage) >= 0) {
et + "'>" + UserinfoJsFormatDateRel(registration) + "</a> old";
$(a).addClass('AQ-B');
}
} else if (AQF.articleClasses['C'].indexOf(a.wikipage) >= 0) {
$(a).addClass('AQ-C');}
} else if (AQF.articleClasses['Start'].indexOf(a.wikipage) >= 0) {
// Edit $(a).addClass('AQ-Start');count
} else if (AQF.articleClasses['Stub'].indexOf(a.wikipage)editcount >!== 0null) {
$(a).addClass('AQ-Stub');statusText += ", with " +
"<a href=\"//tools.wmflabs.org/xtools-ec/?user=" +
} else if (AQF.articleClasses['Unclassified'].indexOf(a.wikipage) >= 0) {
$ encodeURIComponent(a)user.addClass('AQ-Unclassified'name); +
"&amp;project=en.wikipedia.org&amp;uselang=en\">" +
UserinfoJsFormatQty(editcount, "edit", "edits") + "</a>";
}
// Prefix status text with correct article
if("AEIOaeio".indexOf(statusText.charAt(statusText.indexOf('>')+1)) >= 0) {
statusText = "An " + statusText;
} else {
//$(a).addClass('AQ-Unknown');statusText = //"A Having" some+ trouble with this at the moment.statusText;
}
});
},
 
/* Extract the name of the WP article from the URL */
getPageName:function(url){
var m=url.match(/\/wiki\/([^?#]+)/);
if(!m) m=url.match(/\/w\/index.php\?(?:.*&)?title=([^&#]+)/);
if(!m) return '';
var t=decodeURIComponent(m[1]).replace(/_/g,' ');
if(t.substr(0,6)=='Image:') t='File:'+t.substr(6);
if(t.substr(0,11)=='Image talk:') t='File talk:'+t.substr(6);
if(t.substr(0,8)=='Special:') t='';
return t;
},
 
/* If given a pagename which is not in the 'Talk:' namespace, adds 'Talk:'
* and returns the name of the page in the talk namespace. Returns
* unaltered input if the provided name is already in the "Talk:" namespace */
getTalkPageFromPageName:function(name){
return (name.substr(0,5)=='Talk:') ? name : 'Talk:'+name;
},
 
// Add full stop to status text
/* If given a pagename in "Talk:" namespace, removes the namespace to return the page name
statusText += ".";
* returns unaltered input if the provided name is not in the "Talk:" namespace */
getPageNameFromTalkPage:function(name){
return (name.substr(0,5)=='Talk:') ? name.substr(5,name.length) : name;
},
 
// Last edited --PS 2010-06-27
classifyChildren:function(node){
// Added link to contributions page --PS 2010-07-03
mw.loader.using(['mediawiki.util','mediawiki.user'], function(){
var a=node.getElementsByTagNameif('A'lastEdited); {
statusText += " Last edited <a href=\"" + mw.config.get("wgArticlePath").replace("$1", "Special:Contributions/" + encodeURIComponent(user.name)) + "\">" + UserinfoJsFormatDateRel(lastEdited) + " ago</a>.";
if(a.length==0) return;
var self=AQFetcher.getPageName(location.href);
a=Array.prototype.map.call(a, function(a){
a.wikipage='';
if(/(^|\s)(external|extiw)(\s|$)/.test(a.className)) return '';
a.wikipage=AQFetcher.getPageName(a.href);
if(a.wikipage==self) a.wikipage='';
if(a.wikipage.indexOf(':')>0) a.wikipage=''; //filter out anything not in main namespace
a.origwikipage=a.wikipage;
return AQFetcher.getTalkPageFromPageName(a.wikipage);
}).sort().filter(function(e,i,a){
return e!=='' && (i==0 || a[i-1]!==e) && e!=='Talk:';
});
// a is now a sorted array of links with wikipage attributes holding the title of talk pages
 
function processLinks(limit){
while(a.length>0){
var q={
format:'json',
action:'query',
titles:a.splice(0,limit).join('|'),
prop:'categories', // Only interested in Talk page categories
cllimit:'max',
rawcontinue:1
};
$.ajax({
url:mw.util.wikiScript('api'),
dataType:'json',
type:'POST',
data:q,
rawdata:q,
success:AQFetcher.callback,
error:function(xhr,textStatus,errorThrown){
throw new Error('AJAX error: '+textStatus+' '+errorThrown);
}
});
}
}
 
if(a.length<=100){// Show the correct gender symbol
var fh = document.getElementById("firstHeading") ||
// Not worth querying the API to see if the user has apihighlimits
processLinksdocument.getElementById(50"section-0");
// Add classes for blocked, registered, and anonymous users
var newClasses = [];
if(blocked) {
newClasses.push("ps-blocked");
}
if(ipUser) {
newClasses.push("ps-anonymous");
} else if(invalid) {
newClasses.push("ps-invalid");
} else {
// Note mwnewClasses.user.getRights queries the APIpush("ps-registered");
mw.user.getRights(function(rights){}
fh.className += (fh.className.length ? " " : "") + groups.map(function(s) {
processLinks( (rights.indexOf('apihighlimits')>=0) ? 500 : 50 );
})return "ps-group-" + s;
}).concat(newClasses).join(" ");
var genderSpan = document.createElement("span");
});
genderSpan.id = "ps-gender-" + (gender || "unknown");
},
genderSpan.style.paddingLeft = "0.25em";
genderSpan.style.fontFamily = '"Lucida Grande", "Lucida Sans Unicode", "sans-serif"';
onLoad:function(){
genderSpan.style.fontSize = "75%";
if (mw.config.get( 'wgCanonicalNamespace' ) != "") {
var genderSymbol;
console.log("Browsing in " + mw.config.get( 'wgCanonicalNamespace' )
switch(gender) {
+ " namespace so article link styles will not be applied by quality.");
return case "male": genderSymbol = "\u2642"; break;
case "female": genderSymbol = "\u2640"; break;
}
default: genderSymbol = ""; break;
}
genderSpan.appendChild(document.createTextNode(genderSymbol));
fh.appendChild(genderSpan);
 
// Now show the other information. Non-standard? Yes, but it gets the job done.
// Figure out where the article content is...
// Add a period after the tagline when doing so. --PS 2010-07-03
var node=document.getElementById('wikiPreview');
if(!node) node=document.getElementById('bodyContent');
 
var ss = document.getElementById("siteSub");
if(node) AQFetcher.classifyChildren(node);
} if(!ss) {
ss = document.createElement("div");
};
ss.id = "siteSub";
 
ss.innerHTML = "From Wikipedia, the free encyclopedia";
$(document).ready(AQFetcher.onLoad);
var bc = document.getElementById("bodyContent");
 
bc.insertBefore(ss, bc.firstChild);
// [[Category:Wikipedia scripts]]
}
ss.innerHTML = '<span id="ps-userinfo">' + statusText + '</span> ' + ss.innerHTML + '.';
ss.style.display = "block";
});
}); });
}