مستخدم:Bawolff/leadGen.js
ملاحظة: بعد النشر، أنت قد تحتاج إلى إفراغ الكاش الخاص بمتصفحك لرؤية التغييرات.
- فايرفوكس / سافاري: أمسك Shift أثناء ضغط Reload، أو اضغط على إما Ctrl-F5 أو Ctrl-R (⌘-R على ماك)
- جوجل كروم: اضغط Ctrl-Shift-R (⌘-Shift-R على ماك)
- إنترنت إكسبلورر/إيدج: أمسك Ctrl أثناء ضغط Refresh، أو اضغط Ctrl-F5
- أوبرا: اضغط Ctrl-F5.
/*<source lang="javascript" line="1">
This javascript deals with stuff specific to [[User:Bawolff/sandbox/makeLead]]. Functions
specific to lead generation are at User:Bawolff/sanbox/leadGenerator.js
functions relating to api access are at User:Bawolff/mwapilib2.js
*/
mw.loader.load('//en.wikinews.org/w/index.php?title=user:Bawolff/mwapilib2.js&action=raw&ctype=text/javascript');
/*importScriptURI('//en.wikinews.org/w/index.php?title=user:Bawolff/mwapilib2.js&action=raw&ctype=text/javascript');*/
if (!window.Bawolff) {
window.Bawolff = {};
}
// http://en.wikinews.org/w/api.php?action=query&prop=revisions&titles=template:Lead%20article%201|template:Lead%20article%202|template:Lead%20article%203|template:Lead%20article%204|template:Lead%20article%205&rvprop=timestamp|content
//Call as Bawolff.leadGen(pageName, 1, alert)
//replacing 1 with which lead (1-5), alert with your callback
//optionally takes summary method (as numeric) argument. choose 0-4
Bawolff.leadGen = function (title, leadNumb, callback, summaryMethod) {
api(title).getPage().lift(Bawolff.leadGen.extract, title, summaryMethod).lift(Bawolff.leadGen.create, leadNumb).lift(callback, title).exec();
}
/********
This is a list that maps categories/infboxes to generic images
Note: the category map only works with categories explicity included. it does not count categories included by templates
Note: this does not consider templates with parameters
*****/
Bawolff.leadGen.imgMap = { "تركيا": "Flag of Turkey.svg",
"كندا": "Flag of Canada.svg",
"الولايات المتحدة الأمريكية": "Flag of the United States.svg",
"فرنسا": "Flag of France.svg",
"حاسوب": "Computer-aj aj ashton 01.svg",
"المكسيك": "Flag of Mexico.svg",
"وفيات": "Wikinews tag obituary.png",
"مصر": "Flag of Egypt.svg",
"الأردن": "Flag of Jordan.svg",
"الكويت": "Flag of Kuwait.svg",
"الجزائر": "Flag of Algeria.svg",
"ليبيا": "Flag of Libya.svg",
"سوريا": "Flag of Syria.svg",
"الصومال": "Flag of Somalia.svg",
"لبنان": "Flag of Lebanon.svg",
"العراق": "Flag of Iraq.svg",
"جورجيا": "Flag of Georgia.svg",
"المملكة المتحدة": "Flag of the United Kingdom.svg",
"علوم وتقنية": "Science-symbol-2.svg",
"الاتحاد الأوروبي": "Flag of Europe.svg",
"الأمم المتحدة": "Flag of the United Nations.svg",
"برنامج الأغذية العالمي": "WFP Flag.PNG",
"ميركوسور": "Flag of Mercosur.svg"
}
//takes the source of a wikipage, extracts the first image name without the leading namespace
Bawolff.leadGen.extractImg = function (page) {
var imgRegex = /\[\[(?:[iI][mM][aA][gG][eE]\:|[fF][Ii][lL][eE]\:|\u0645\u0644\u0641\:|\u0635\u0648\u0631\u0629\:)((?:[^\|\]])*?\.[pPsSjJgG][nNvVpPiI][gGeEfF][gG]?)[\|\]]?/;
var img = imgRegex.exec(page);
if (img && img.length >= 2) {
return img[1];
}
else {
var infoboxRegex = /\{\{([^|}]*)\}\}/g;
var categoryRegex = /\[\[تصنيف:([^|\]]*)(?:\|[^\]]*)?\]\]/g;
//js seems to reuse these objects from prev calls without reseting lastIndex. reset lastIndex.
infoboxRegex.lastIndex = categoryRegex.lastIndex = 0;
var item; //note doesn't match infoboxes w/params
while (item = infoboxRegex.exec(page)) {
item = item[1];
item = item[0].toUpperCase() + item.substring(1, item.length);
if (Bawolff.leadGen.imgMap[item]) return Bawolff.leadGen.imgMap[item];
}
while (item = categoryRegex.exec(page)) {
item = item[1];
item = item[0].toUpperCase() + item.substring(1, item.length);
if (Bawolff.leadGen.imgMap[item]) return Bawolff.leadGen.imgMap[item];
}
return "Wikinews-logo.png"; //default
// return "";
}
}
Bawolff.leadGen.extractAudio = function (page) {
//Version audio|Ares I-X lancement réussi.ogg
var res = page.match(/\{\{[vV]ersion audio\|([^|}]*)\|?[^}]*\}\}/);
if (res) return res[1];
return "";
}
Bawolff.leadGen.extractType = function (page) {
//valid types are: breaking, special, original, exclusive, urgent or none.
//this currently does not detect special or urget.
if (page.match(/\{\{[eE]n(?: cours)?\}\}/)) {
return "breaking";
}
else if (page.match(/\{\{[iI]nterview(?:\|[^}]*)?\}\}/i)) {
return "exclusive";
}
else if (page.match(/\{\{[rR]eportage(?: original)?(?:\|[^}]*)?\}\}/i)) {
return "original";
}
else {
//default
return "none";
}
}
Bawolff.leadGen.takeIntro = function (pageText, method) {
//first test for redirects.
var isRedirect = pageText.match(/^#redirect\s?\[\[([^\]]*)\]\]/i)
if (isRedirect) {
alert("هذه صفحة تحويل. الرجاء عدم استخدام صفحات التحويل [[" + isRedirect[1] + "]].");
throw new Error("La page est une redirection. Merci de résoudre manuellement à : " + isRedirect[1] );
}
//doesn't handle links that make [1].
//intentionally doesn't strip ' chars (bold or italic)
//as this often marks thigs with periods (E. coli)
//method is a number (must be a number. no type conversion preformed).
// 0: 1st sentence
// 1: 1st two senetences
// 2: 1st paragraph
// 3: 1st 250 characters (+ a couple so we don't end in middle of word), or paragraph
// 4: 1st 500 characters-ish, or paragraph
var stripTemplates = /\{\{[^\}\{]*(?:\{\{[^\}\{]*(?:\{\{[^\}\{]*(?:\{\{[^\}\{]*\}\})?\}\})?\}\})?\}\}/g;
var stripRefs = /\<ref[^>]*\>[\s\S]*?\<\/ref>/g;
//the img regex, looks for a start of the image, than checks for nested internal links, external links, and for ending ]] in caption
//templates shold already be stripped at this point. (fr image = Fichier)
var img = /\[\[[IifF\u0645\u0635][mMIi\u0644\u0648][aALlcC\u0641\u0631][GgEehH\u0629]?[eEiI]?[eE]?[rR]?\:(?:\[\[(?:[^\]]*)\]\]|[^\]]|\](?!\]))*]]/g
//note, these are run multiple times to deal with nesting.
pageText = pageText.replace(stripTemplates, '');
pageText = pageText.replace(stripTemplates, '');
pageText = pageText.replace(stripTemplates, '');
pageText = pageText.replace(stripTemplates, '');
pageText = pageText.replace(stripRefs, '');
pageText = pageText.replace(img, '');
var pipedLink = /\[\[[^\]\|]*\|([^\]\|]*)\]\]/g;
pageText = pageText.replace(pipedLink, '$1');
var normLink = /\[\[([^\]\|]*)\]\]/g;
pageText = pageText.replace(normLink, '$1');
var extLink = /\[(?:http|ftp|gopher|irc|https)\:[^\]\s]*\s?([^\]]*)]/g
pageText = pageText.replace(extLink, '$1');
var firstPar;
switch (method) {
case 1: //1st 2 sentence or 1st paragraph
firstPar = /[^\n]+?\s[^\s\.]*\.(?=\s)(?:[^\n]+?\s[^\s\.]*\.(?=\s)|(?=\s))/;
pageText = pageText.match(firstPar)[0];
break;
case 2: //1st paragraph
firstPar = /[^\n]+?(?=\n)/;
pageText = pageText.match(firstPar)[0];
break;
case 3: // 1st 250 characters-ish
firstPar = /[^\n]{2,250}.*?\b/;
pageText = pageText.match(firstPar)[0] + "...";
break;
case 4: //1st 500 characters-ish
firstPar = /[^\n]{2,500}.*?\b/;
pageText = pageText.match(firstPar)[0] + "...";
break;
default: //aka case 0. 1st sentence
firstPar = /[^\n]+?\s[^\s\.]*\.(?=\s)/;
pageText = pageText.match(firstPar)[0];
break;
}
return pageText;
}
Bawolff.leadGen.extract = function(pageText, pageName, summaryMethod) {
//editlink is overriden later.
return { width:'150x150',
image: Bawolff.leadGen.extractImg(pageText),
title: pageName,
synopsis: Bawolff.leadGen.takeIntro(pageText, summaryMethod),
'edit_this': '',
audio: Bawolff.leadGen.extractAudio(pageText)
};
}
Bawolff.leadGen.create = function (leadObj, leadNumb) {
var res = '{' + '{New_lead_article';
res += "\n |edit this=" + "قالب:خبر رئيسي" + '/' + leadNumb ;
res += "\n |image=" + leadObj.image;
res += "\n |width=" + leadObj.width;
//Type not internationlized for now. res += "\n |type=" + leadObj.type;
res += "\n |title=" + leadObj.title;
res += "\n |link=" + leadObj.title;
res += "\n |short_title=";
res += "\n |synopsis=\'\'\'<small>{{subst:CURRENTDAY}} {{subst:CURRENTMONTHNAME}} ({{subst:#time:D}}) –</small>\'\'\' " + leadObj.synopsis;
res += "\n |order=left";
res += "\n}}\n __NOTOC__ __NOEDITSECTION__<noinclude>[[تصنيف:قوالب الصفحة الرئيسية]]\n\n[[project:Make lead]]</noinclude>";
return res;
}
//calls its argument giving it an object with meta info about the current leads.
//probably want to use Bawolff.leadGen.makeLeadTable instead.
Bawolff.leadGen.makeLeadMetaObject = function (callback) {
var leadObj = function (doc) {
var exTitle = function (text) {
text = text.replace(/[\s\S]*?\|title=([^\|]*)[\s\S]*/, '$1');
text = text.replace(/\s*$/, '');
return text;
}
var pages = doc.getElementsByTagName('page');
var obj = {}, time, time2 = Infinity;
for (var i = 0; i < pages.length; i++) {
pages[i].getElementsByTagName('rev')[0].normalize();
time = Bawolff.mwapi.parseAPIDate(pages[i].getElementsByTagName('rev')[0].getAttribute('timestamp'));
//This is really ugly...
//put the oldest lead in a global variable.
if (time < time2) { //this compares miliseconds after epoch
Bawolff.leadGen.oldestLead = pages[i].getAttribute('title');
time2 = time;
}
obj[pages[i].getAttribute('title')] = {timestamp: time,
title: exTitle(pages[i].getElementsByTagName('rev')[0].firstChild.data)};
}
return obj;
}
api().makeRequest({action: 'query', prop: 'revisions', titles: 'قالب:خبر رئيسي/1|قالب:خبر رئيسي/2|قالب:خبر رئيسي/3|قالب:خبر رئيسي/4', prop: 'revisions', rvprop: 'timestamp|content', redirects: true}, leadObj).lift(callback).exec();
}
Bawolff.leadGen.oldestLead = null;
Bawolff.leadGen.makeLeadTable = function (callback) {
var wrapper = function(leadObj) {
var html = '<table class="wikitable"><caption>الأخبار الرئيسية الحالية</caption>';
html += '<thead><tr><th>#</th><th>الموقع</th><th>المقالة</th><th>عمرها</th></tr></thead><tbody>';
for (var i in leadObj) {
if (leadObj.hasOwnProperty(i)) {
var numb = i.charAt(i.length - 1);
html += '<tr><th>';
html += numb; //last character
html += '</th><td>';
html += Bawolff.leadGen.leadToPosition(numb);
html += '</td><td>';
html += leadObj[i].title;
html += '</td><td>';
var time = leadObj[i].timestamp.getTime(); //convert to miliseconds
var d = (new Date).getTime();
var delta = Math.round((d - time) / (1000*60*60));
var timeStr;
if (delta === 0) {
timeStr = 'أقل من ساعة';
}
else if (delta === 1) {
timeStr = 'ساعة واحدة';
}
else if (delta === 2) {
timeStr = 'ساعتان';
}
else if (((delta % 100) >2) && ((delta % 100) <11)) {
timeStr = delta + ' ساعات';
}
else {
timeStr = delta + ' ساعة';
}
html += timeStr;
html += "</td></tr>";
}
}
html += '</tbody></table>';
callback(html);
}
Bawolff.leadGen.makeLeadMetaObject(wrapper);
}
Bawolff.leadGen.leadToPosition = function (numb) {
//double equal sign intentional to convert from string.
switch (+(numb)) {
case 1:
return "أعلى اليمين";
case 2:
return "أعلى اليسار";
case 3:
return "أسفل اليمين";
case 4:
return "أسفل اليسار";
default:
return numb.charAt(numb.length - 1);
}
/*else {
throw new Error("Chiffre de l\'article principal invalide (" + numb +") trasmis à Bawolff.leadGen.leadToPosition");
}*/
}
/*******************
End LeadGenerator
******************/
var showPreview = function (html) {
//We assume that the mediawiki api is not malicious...
document.getElementById('LeadPreview').innerHTML = html;
}
var showLead = function (leadText, leadTitle) {
var lsp = document.getElementById('leadSourcePrev');
if (!lsp) {
var src = document.createElement('textarea');
src.id = 'leadSourcePrev';
src.dir = 'ltr'; //? is this good idea?
src.style.width = '48%';
src.rows = 40;
src.appendChild(document.createTextNode(leadText));
document.getElementById('LeadBox').appendChild(src);
document.getElementById('LeadPreview').style.visibility = 'visible';
}
else {
lsp.value = leadText;
}
leadTitle = leadTitle.replace(/(\\|')/g, "\\$1").replace(/"/g, """).replace(/>/g, '>'); //prevent xss
var leadNumb = document.getElementById('leadNum').selectedIndex + 1;
document.getElementById('LeadControls').innerHTML = '<button onclick="syncToServer(' + leadNumb + ', \'' + leadTitle + '\')">احفظ الخبر الرئيسي ' + leadNumb + '</button> <button onclick="regeneratePreview()">معاينة مجدداً</button>';
api(leadText).replace(/<noinclude>[\d\D]*?<\/noinclude>/, '').parse('Main Page').lift(showPreview).exec();
//this will strip out anything after a noinculde (this is kind of dirty)
}
var regeneratePreview = function() {
var wikiText = document.getElementById('leadSourcePrev').value;
api(wikiText).replace(/<noinclude>[\d\D]*?<\/noinclude>/, '').parse('Main Page').lift(showPreview).exec();
}
var syncToServer = function(leadNum, page) {
if (leadNum === undefined || !confirm('هل أنت متأكد أنك تريد حفظ هذا الخبر الرئيسي بالرقم '+ leadNum +'؟' )) {
return false;
}
api(document.getElementById('leadSourcePrev').value).setDefaultSummary('حفظ الخبر الرئيسي رقم ' + leadNum + '(راجع [[Wikinews:Make lead|AP JS]])').savePage('قالب:خبر رئيسي/' + leadNum).inject('تم تحديث قالب الخبر الرئيسي').lift(alert).lift(function() {location = mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', wgPageName) + '?js-good-update=' + encodeURIComponent(page);}).exec();
}
var startLeadMaker = function () {
if (wgAction !== 'view' && wgAction !== 'purge') {
return false;
}
if (!window.api || !window.Bawolff || !window.Bawolff.leadGen) {
alert('Javascript ne s\'est pas chargé correctement, comme résultat que cette page peut ou ne peut fonctionner. Si ça ne fonctionne pas, essayer d\'actualiser la page.');
}
if (!wgUserGroups || wgUserGroups.join(' ').indexOf("autoconfirmed") === -1) {
jsMsg("<div style='border:solid red medium;font-weight: bold'>لا يحق لك تعديل الأخبار في الصفحة الرئيسية. هذه الميزة محصورة بالمستخدمين المسجلين المؤكدين تلقائياً.</div>");
}
var lastUpdate = location.search.match(/[?&]js-good-update=([^&]*).*/);
if (lastUpdate) {
//this is all properly escaped since its in a text node.
window.setTimeout(function () {jsMsg(document.createTextNode('تم حفظ الخبر الرئيسي بنجاح"' + decodeURIComponent(lastUpdate[1]) + '".'));}, 400); //to get arround other things using jsMSg
}
var setupContainer = document.getElementById('lSetup');
setupContainer.innerHTML += "<form id='leadForm' action='javascript:doMakeLead();void 0;'><input type='text' id='pageNameField' size='50'><br/><label for='leadNum'>الخبر الرئيسي رقم</label> <select id='leadNum' onchange='doMakeLead(true);'><option selected value='1'>1 (أعلى اليمين)</option><option value='2'>2 (أعلى اليسار)</option><option value='3'>3 (أسفل اليمين) </option><option value='4'>4 (أسفل اليسار) </option> </select> <label for='sumMethod'>محتوى الملخص</label> <select id='sumMethod'><option value='0'>الجملة الأولى</option><option selected value='1' >أول جملتين</option><option value='2'>الفقرة الأولى</option><option>أول 250 حرفاً</option> <option>أول 500 حرفاً</option> </select> <input type='submit' value='إنشاء الخبر الرئيسي'></form>";
var dpl = document.getElementById('lDPL').getElementsByTagName('a');
for (var i = 0; i < dpl.length; i++) {
linkVal = encodeURIComponent(dpl[i].firstChild.data.replace(/(\\|")/g, "\\$1"));
// %22 = "
dpl[i].href = 'javascript:document.getElementById(%22pageNameField%22).value=%22' + linkVal + '%22;doMakeLead();void%200';
}
// autosuggest
mw.loader.using( 'jquery.ui', function () { $( "#pageNameField" ).autocomplete({
minLength: 2,
source: function( request, response ) {
$.getJSON(
mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php?format=json&action=opensearch&search=' +
mw.util.rawurlencode( request.term ) + '&callback=?',
function( obj ) {
if ( obj && obj.length > 1 ) {
response( obj[1] );
} else {
response( [] );
}
}
);
}
})});
var handleAfterLeadInfoTableLoads = function (table) {
document.getElementById('lMetaTable').innerHTML = table;
var pageName = location.search.replace(/.*?[?&]use-page=([^&]*).*/, '$1');
if (Bawolff.leadGen.oldestLead) {
var oldLeadNum = parseInt(Bawolff.leadGen.oldestLead.charAt(Bawolff.leadGen.oldestLead.length - 1));
document.getElementById('leadNum').selectedIndex = oldLeadNum - 1;
/*
if (oldLeadNum === 1) {
document.getElementById('sumMethod').selectedIndex = 1; //use 2 sentences for longer lead.
}
*/
}
if (pageName !== location.search) { //if it matched
document.getElementById('pageNameField').value = decodeURIComponent(pageName.replace(/\+/g, ' '));
location.href = '#leadForm'; //since already filled out.
doMakeLead();
}
}
Bawolff.leadGen.makeLeadTable(handleAfterLeadInfoTableLoads);
}
function doMakeLead (fromLeadNumChange) {
var pageName = document.getElementById('pageNameField').value;
var leadNum = document.getElementById('leadNum').selectedIndex + 1;
if (fromLeadNumChange && leadNum === 1) {
document.getElementById('sumMethod').selectedIndex = 1; //use 2 sentences for longer lead.
}
var sumMethod = document.getElementById('sumMethod').selectedIndex;
Bawolff.leadGen(pageName, leadNum, showLead, sumMethod);
}
waitAWhileThanLoadLead.times = 0;
function waitAWhileThanLoadLead () {
//since we're already from an onload event, and importScript is async. wait a while
if ((!window.api || !window.Bawolff || !window.Bawolff.leadGen) && waitAWhileThanLoadLead.times < 10) {
waitAWhileThanLoadLead.times++;
setTimeout(waitAWhileThanLoadLead, 200);
} else {
startLeadMaker();
}
}
$(waitAWhileThanLoadLead);
/*</source>*/