مدیاویکی:TofawikiHelper.js
ظاهر
نکته: برای دیدن تغییرات، ممکن است نیاز باشد که حافظهٔ نهانی مرورگر خود را پس از انتشار پاکسازی کنید. گوگل کروم، فایرفاکس، مایکروسافت اج و سافاری: کلید ⇧ Shift را نگه دارید و روی دکمهٔ Reload در نوار ابزار مرورگر کلیک کنید. برای آگاهی از جزئیات و نحوهٔ پاکسازی حافظهٔ نهانی سایر مرورگرها، صفحهٔ ویکیپدیا:میانگیر مرورگرتان را خالی کنید را ببینید.
(function () {
'use strict';
function getEnCats(title) {
return new mw.Api({ ajax: { url: '//en.wikipedia.org/w/api.php' } }).get({
action: 'query',
prop: 'categories',
titles: title,
clshow: '!hidden',
cllimit: 500,
format: 'json',
origin: window.location.protocol + '//' + window.location.hostname
}).then(function (data) {
var page = $.map((data.query || {}).pages, function (x) { return x; })[0] || {};
return (page.categories || []).map(function (x) { return x.title; });
});
}
function getFaTitlesFromWikidata(enTitles) {
return $.post('//tofawiki-linkstranslator.wmcloud.org/', {
from: 'en',
to: 'fa',
p: enTitles.join('|')
}).then(function (result) {
return Object.keys(result).map(function (x) { return result[x]; });
});
}
function getEnPage(title) {
return new mw.Api({ ajax: { url: '//en.wikipedia.org/w/api.php' } }).get({
action: 'parse',
format: 'json',
page: title,
prop: 'text',
origin: window.location.protocol + '//' + window.location.hostname
}).then(function (result) { return result.parse.text['*']; });
}
function getResolvedRedirectPages(pages) {
return new mw.Api({ ajax: { url: '//en.wikipedia.org/w/api.php' } }).get({
action: 'query',
format: 'json',
redirects: '',
titles: pages.join('|'),
origin: window.location.protocol + '//' + window.location.hostname
}).then(function (result) {
return Object.keys(result.query.pages).map(function (x) { return result.query.pages[x].title; });
});
}
function getSeeAlsoPages(title) {
return getEnPage(title).then(function (page) {
var pages = $("#See_also", '<div>' + page + '</div>').parent().next().find('a[href^="/wiki/"]').get().map(function (x) { return x.title; });
if (pages.length === 0) { return []; }
return getResolvedRedirectPages(pages).then(getFaTitlesFromWikidata);
});
}
function dePersian(text) {
return text
.replace(/ی/g, 'ي')
.replace(/ک/g, 'ك')
.replace(/گ/g, 'كی')
.replace(/ژ/g, 'زی')
.replace(/چ/g, 'جی')
.replace(/پ/g, 'بی');
}
function setTextInEditor(text) {
if(!window.ve || !ve.init || !ve.init.target) {
$('#wpTextbox1').val(text);
return;
}
if(!ve.init.target.active) {
return;
}
if(ve.init.target.getSurface().getMode() == 'source') {
var startPostion = new ve.Range( 1, getTextInEditor().length );
var surfaceModel = ve.init.target.getSurface().getModel();
var fragment = surfaceModel.getLinearFragment( startPostion );
fragment.insertContent( text );
}
if(ve.init.target.getSurface().getMode() == 'visual') {
var surfaceModel = ve.init.target.getSurface().getModel();
ve.init.target.parseWikitextFragment( text, false, surfaceModel.getDocument() ).then( function ( response ) {
var startPostion = new ve.Range( 1 );
var fragment = surfaceModel.getLinearFragment( startPostion, getTextInEditor().length );
fragment.insertHtml( response.visualeditor.content );
} );
}
}
function getTextInEditor() {
if(!window.ve || !ve.init || !ve.init.target) {
return $('#wpTextbox1').val();
}
if(!ve.init.target.active) {
return '';
}
if(ve.init.target.getSurface().getMode() == 'source') {
var surfaceModel = ve.init.target.getSurface().getModel();
var selection = surfaceModel.getFragment().expandLinearSelection('root');
return selection.getText(true);
}
if(ve.init.target.getSurface().getMode() == 'visual') {
//TODO: It's not the real wikitext
var surfaceModel = ve.init.target.getSurface().getModel();
var selection = surfaceModel.getFragment().expandLinearSelection('root');
return selection.getText(true);
}
}
function generalArticle() {
var query = new mw.Uri().query;
var enName = query.enName.replace(/_/g, ' ');
var enLink = new mw.Uri('//en.wikipedia.org/w/index.php').extend({
title: query.enName,
oldid: query.enOldid
});
var text = '';
text = "'''" + mw.config.get('wgTitle').replace(/\s\(.*\)/, ' ') + "''' {" + "{به انگلیسی|" +
enName.replace(/\s\(.*\)/, '') + '}}\n<ref>{' + '{یادکرد-ویکی|پیوند=' +
enLink + '|عنوان=' + enName +
'|زبان=انگلیسی|بازیابی=}}</ref>\n\n' +
'== جستارهای وابسته ==\n* [[مقالهٔ مرتبط]]\n\n' + '== پانویس ==\n' +
'{' + '{پانویس}}\n\n';
getSeeAlsoPages(enName).then(function (pages) {
pages.length && setTextInEditor(getTextInEditor().replace(
'* [' + '[مقالهٔ مرتبط]]',
'* [' + '[' + pages.join(']]\n* [[') + ']]'
));
});
text = text + '[[رده' + ':رده۱]' + ']\n\n' + '[' + '[en:' + enName + ']]';
setTextInEditor(text);
getEnCats(enName).then(getFaTitlesFromWikidata).then(function (faCats) {
faCats = faCats.sort(function (x, y) {
var keyX = dePersian(x),
keyY = dePersian(y);
if (keyX < keyY) { return -1; }
if (keyX > keyY) { return 1; }
return 0;
});
setTextInEditor(getTextInEditor().replace(
'[[رده' + ':رده۱]' + ']',
'[[' + faCats.join(']]\n[[') + ']]'
));
});
}
var pleaseWait = 'در حال تهیهٔ متن مقاله، کمی صبر کنید';
function inProgressDots() {
setTimeout(function () {
var val = getTextInEditor() || '';
if (0 !== val.indexOf(pleaseWait)) { return; }
setTextInEditor((getTextInEditor() + '. ').replace('. . . . ', ''));
inProgressDots();
}, 1000);
}
function preSavedTransform(content, title) {
return new mw.Api().post({
action: 'parse',
text: content,
contentmodel: 'wikitext',
prop: 'text',
onlypst: '',
title: title || 'API'
}).then(function (data) { return data.parse.text['*']; });
}
function botContentMaker(requestTool, bot, botLink, enName) {
setTextInEditor(pleaseWait);
var uri = new mw.Uri(requestTool);
uri.query = {
enwiki: enName,
fawiki: mw.config.get('wgTitle')
};
if (
requestTool === '//dexbot.toolforge.org/c.php' ||
requestTool === '//dexbot.toolforge.org/a.php' ||
requestTool === '//dexbot.toolforge.org/b.php'
) {
uri = '//tofawiki.wmcloud.org/translate/enwiki/' +
encodeURI(new mw.Uri().query.enName.replace(/\//g, '%2F').replace('?', '%3F')) + '/' +
encodeURI(mw.config.get('wgTitle').replace(/\//g, '%2F').replace('?', '%3F'));
}
inProgressDots();
$.ajax({
dataType: "json",
url: uri.toString(),
timeout: 60000
}).then(function (x) {
return ((x === null) || x.error)
? x
: preSavedTransform(x.page_content, mw.config.get('wgTitle')).then(function (x) {
return { page_content: x };
});
}, function (e) {
console.error(e);
return { error: e.statusText };
}).then(function (x) {
if ((x === null) || x.error) {
console.error(x);
mw.notify(bot + ': ' + (x === null ? 'خطای اساسی' : x.error));
if (botLink === "ویکیپدیا:مقالههای درخواستی") {
generalArticle();
} else {
botContentMaker('//dexbot.toolforge.org/c.php', 'Dexbot', 'ویکیپدیا:مقالههای درخواستی', enName);
}
return;
}
var summary = 'ایجادشده به کمک [[راهنما:ابزار/به ویکیفا|به ویکیفا]] و ' + bot, content = x.page_content;
if (window.persianWikiTools) {
summary = summary + '، ابرابزار';
content = persianWikiTools.superTool(content);
}
// https://fa.wikipedia.org/w/?diff=21503233
content = content.replace(/([^\n])\{\{دادههای کتابخانهای\}\}/, '$1\n{{دادههای کتابخانهای}}');
$('input#wpSummary, #wpSummary > input').val(summary);
mw.hook( 've.saveDialog.stateChanged' ).add( function () {
$( '.ve-ui-mwSaveDialog-summary textarea' ).text( $( '.ve-ui-mwSaveDialog-summary textarea' ).text() + summary );
} );
setTextInEditor(content);
importScript('MediaWiki:YandexTranslatorHelper.js');
if (window.wikEd && window.wikEd.useWikEd) { wikEd.UpdateFrame(); }
}, function (e) {
mw.notify(e);
if (botLink === 'ویکیپدیا:مقالههای درخواستی') {
generalArticle();
} else {
botContentMaker('//dexbot.toolforge.org/c.php', 'Dexbot', 'ویکیپدیا:مقالههای درخواستی', enName);
}
if (window.wikEd && window.wikEd.useWikEd) { wikEd.UpdateFrame(); }
});
}
function getRawEnPage(title) {
return new mw.Api({ ajax: { url: '//en.wikipedia.org/w/api.php' } }).get({
action: 'query',
prop: 'revisions',
titles: title.replace(/_/g, ' '),
rvprop: 'content',
format: 'json',
rvslots: 'main',
origin: window.location.protocol + '//' + window.location.hostname
}).then(function (result) {
return result && result.query && result.query.pages && !result.query.pages[-1]
? $.map(result.query.pages, function (x) { return x; })[0].revisions[0].slots.main['*']
: '';
});
}
function setTextboxContent(content) {
// TODO: Add support for new text editors
setTextInEditor(content);
if (window.wikEd && window.wikEd.useWikEd) { wikEd.UpdateFrame(); }
var context = $('#wpTextbox1').data('wikiEditor-context');
if (context && context.codeEditor && context.codeEditor.getSession) {
var session = context.codeEditor.getSession();
if (session) {
session.setValue(content);
}
}
}
function templateBookModuleTranslator() {
setTextboxContent(pleaseWait);
var query = new mw.Uri().query;
getRawEnPage(query.enName).then(function (raw) {
if (mw.config.get('wgNamespaceNumber') === 828) {
setTextboxContent(raw);
return; // This is enough for Module:
}
var links = (raw.match(/\[\[.*?\]\]/g) || []).map(function (x) { return x.split('[[')[1].split(/[\|\]]/)[0]; });
$.post('//tofawiki-linkstranslator.wmcloud.org/', {
p: links.join('|'),
from: 'en',
to: 'fa'
}).then(function (result) {
if (raw.match(/\{\{(Navbox|Sidebar|Campaignbox)/)) {
raw = raw.replace(/(\|\s*name\s*=\s*)([^\n\|\}]*)/, '$1' + mw.config.get('wgTitle'));
}
if (mw.config.get('wgNamespaceNumber') === 102) {
raw = raw.replace(/(\|\s*title\s*=\s*)([^\n\|\}]*)/, '$1' + mw.config.get('wgTitle'));
raw = raw.replace(/;Chapter (\d+)/g, function (_, x) { return ";فصل " + (+x).toLocaleString('fa'); })
raw = raw.replace(/{{Saved book/i, '{{کتاب ذخیرهشده');
}
Object.keys(result).forEach(function (from) {
raw = raw.replace(
new RegExp('(\\[\\[:?)' + mw.util.escapeRegExp(from) + '((?:\\|[^\\]]*)?)(\\]\\])', 'g'),
'$1' + result[from] + '$3'
);
});
setTextboxContent(raw);
}, function (e) {
console.error(e);
setTextboxContent(raw);
});
});
$('input#wpSummary, #wpSummary > input').val(
$('input#wpSummary, #wpSummary > input').val() + '، از ' +
new mw.Uri('https://en.wikipedia.org/w/index.php').extend({
title: query.enName,
oldid: query.enOldid
})
);
}
$(function () {
document.documentElement.classList.remove('vector-feature-limited-width-clientpref-1');
document.documentElement.classList.add('vector-feature-limited-width-clientpref-0');
document.documentElement.classList.remove('vector-feature-page-tools-pinned-enabled');
document.documentElement.classList.add('vector-feature-page-tools-pinned-disabled');
$('.vector-page-toolbar').remove();
window.dispatchEvent( new Event( 'resize' ) );
var query = new mw.Uri().query;
$('input#wpSummary, #wpSummary > input').val('ایجادشده به کمک [[راهنما:ابزار/به ویکیفا|به ویکیفا]]');
if (query.requestingPage === "ویکیپدیا:ویکیپروژه ایجاد مقالههای شهرها با ربات/درخواست ساخت رباتیک") {
botContentMaker('//rezabot.toolforge.org/a.php', 'Rezabot', query.requestingPage, query.enName);
} else if (query.requestingPage === "ویکیپدیا:درخواست ایجاد مقاله (رباتیک)/انسان") {
botContentMaker('//dexbot.toolforge.org/a.php', 'Dexbot', query.requestingPage, query.enName);
} else if (query.requestingPage === "صفحهٔ ابهامزدایی") {
botContentMaker('//rezabot.toolforge.org/disambig.php', 'Rezabot', 'ویکیپدیا:ابهامزدایی', query.enName);
} else if (query.requestingPage === "ویکیپدیا:درخواست ایجاد مقاله (رباتیک)") {
botContentMaker('//dexbot.toolforge.org/b.php', 'Dexbot', query.requestingPage, query.enName);
} else if ([10, 102, 828].includes(mw.config.get('wgNamespaceNumber'))) {
templateBookModuleTranslator();
} else if (mw.config.get('wgNamespaceNumber') === 14) {
botContentMaker('//dexbot.toolforge.org/b.php', 'Dexbot', query.requestingPage, query.enName);
} else if (mw.config.get('wgNamespaceNumber') === 4) {
generalArticle();
importScript('MediaWiki:YandexTranslatorHelper.js');
} else {
botContentMaker('//dexbot.toolforge.org/c.php', 'Dexbot', query.requestingPage, query.enName);
}
});
$(function () {
// نمایش پررنگتر دکمهٔ پیشنمایش
$('<p>', {
style: 'width: 100%; background-color: #fef6e7; border: 2px solid #fc3; font-size: 90%; padding: 2px;',
text: 'پیشنهاد میشود پیش از ذخیرهٔ نهایی صفحه از گزینهٔ پیشنمایش استفاده کنید'
}).appendTo('#editpage-copywarn');
//$('#wpSave').prop('disabled', true);
$('#wpSave').css('font-weight', 'normal');
$('#wpPreview').css('font-weight', 'bold');
});
mw.loader.load( '/w/index.php?title=MediaWiki:TofawikiPass.js&action=raw&ctype=text/javascript' );
}());