User:Mohammad/ArticleTranslator.js

// A copy of w:User:Ebrahim/ArticleTranslator.js // DO NOT COPY IT FOR TRANSLATION, READ THE DOCUMENTATION en:User talk:Ebraminio/ArticleTranslator.js /*global jQuery, mediaWiki*/ (function ($, mw) {	'use strict';

// prevent double execution of the tool if (window.isArticletranslatorInitialized && location.hash === '#tofawikiframe') { return; } window.isArticletranslatorInitialized = true;

var action = mw.config.get('wgAction'); if (action === 'history') { return; }

var conf = { homeWiki: 'fa', fromLang: mw.config.get('wgPageContentLanguage'), translatorBarFormat: '$1translate$2 links from $3 to $4 ($5)', templateTranslatorText: 'Template translation', removeLinksAliasesText: 'Remove Links Aliases', enableTemplateTranslation: true, removeLinksAliases: true, name: 'Name', interwikiCount: 'Language links count', linkedTo: 'Linked to', listOfUnavailablePagesOn: 'List of not present pages on', definedTemplates: ["Flag icon", "flagicon", "Flag", "Portal", "About", "ADB", "Alsoknown", "Alternateuses", "Cat main", "Cat main article", "Category disambiguation", "Category main", "Catmain", "Consider disambiguation", "Contrast", "Dabprefixes", "Detail", "Details", "Disambiguation needed", "Distinguish", "Distinguish2", "For", "For other uses", "For2", "In title", "Introductory article", "Look from", "Main", "Main cat", "Main category", "Maincat", "More", "Moredetails", "Navbox hatnote *Templates", "Other", "Other hurricanes", "Other meanings", "Other people", "Other people2", "Other people3", "Other people5", "Other places", "Other places3", "Other ships", "Other use", "Other uses", "Other uses of", "Other uses1", "Other uses2", "Other uses-section", "Othermeanings", "Otheruse", "OtherUses", "Otheruses1", "Otheruses3", "OtherusesSubtopic", "Othervalues", "Outline", "Previously", "Redirect", "Redirect10", "Redirect2", "Redirect3", "Redirect4", "Redirect6", "Redirect-distinguish2", "Redirect-synonym", "See introduction", "See Wiktionary", "Seesubarticle", "Selfref", "Srlink", "Surname links", "Technical reasons", "Template ambiguous", "Template shortcut", "This user talk", "Three other uses", "Two other uses", "WikiProject Disambiguation"], blacklistedTemplatePattern: /Template:(cite|citation|infobox) [a-z]+/i, };

$.extend(conf, window.articleTranslatorConf);

// getting the last translator preference from the cookie if ($.cookie && $.cookie('homeWiki') !== null) { conf.homeWiki = $.cookie('homeWiki'); } if ($.cookie && $.cookie('fromLang') !== null) { conf.fromLang = $.cookie('fromLang'); }

// from: http://80.68.89.23/2006/Jan/20/escape/ function escape(text) { return text.replace(/[\-\[\]{}*+?.,\\\^$|#\s]/g, '\\$&'); }	function translate(links, showMissings) { var request = { from: conf.fromLang, to: conf.homeWiki, missings: !!showMissings, p: links.join('|') };		// https://github.com/ebraminio/linkstranslator return $.post('https://tools.wmflabs.org/linkstranslator/', request).then(null, function {			return $.post('https://fa-tts.wmflabs.org/linkstranslator/', request);		}); }	function hasNotPersianCharacter(x) { return !/[كﮑﮐﮏﮎﻜﻛﻚﻙىﻯيہەھﻰ-ﻴً-ِْٰء-ٕپچژگکكڪﻙﻚیﻱﻲٔ۱۲۳۴۵۶۷۸۹۰]/.test(x); }

function editboxTranslator { var translationTextArea;

if (conf.fromLang === mw.config.get('wgPageContentLanguage')) { $('#wpTextbox2').remove; translationTextArea = $('#wpTextbox1').clone.attr({				'id': 'wpTextbox2'			}).css({				'background-color': '#CCCEFF'			}).val($('#wpTextbox1').val); $('#wpTextbox1').before(translationTextArea); } else { translationTextArea = $('#wpTextbox1'); }		var raw = translationTextArea.val; if (raw.match(/\{\{(Navbox|Sidebar|Campaignbox)/)) { raw = raw.replace(/(\|\s*name\s*=\s*)([^\n\|\}]*)/, '$1' + mw.config.get('wgTitle')); }		$.Deferred.resolve.then(function {			var links = (raw.match(/\[\[.*?[|\]]/g) || []).map(function (x) { return x.split(/\[\[:?/)[1].split(/[|\]]/)[0]; });

if (links.length === 0) { return; }

if (conf.homeWiki === 'fa') { links = links.filter(hasNotPersianCharacter); }

return translate(links).then(function (result) {				Object.keys(result).forEach(function (from) { raw = raw.replace(						new RegExp('(\\[\\[:?)' + escape(from) + '((?:\\|[^\\]]*)?)(\\]\\])', 'g'),						'$1' + result[from] + (conf.removeLinksAliases ? '' : '$2') + '$3'					);				});			});		}).then(function { var templateLinksRegexp = new RegExp('(\\{\\{\\s*(?:Template:)?(?:' + conf.definedTemplates.join('|') + ')\\|)([^\n|]+?)((?:\\|[^\n\}]*?)?\\}\\})', 'ig'); var links = (raw.match(templateLinksRegexp) || []).map(function (x) { return x.split('|')[1].split('}')[0]; });

if (links.length === 0) { return; }

return translate(links).then(function (result) {				raw = raw.replace(templateLinksRegexp, function ($0, $1, $2, $3) { return $1 + (result[$2] || $2) + $3; });			});

}).then(function { if (!conf.enableTemplateTranslation) { return; } var templatesRegexp = /((?:[^{]|^)\{\{\s*(?:Template:|))([^\n|{]+?)([|}\n])/ig; var links = (raw.match(templatesRegexp) || []) .map(function (x) { return 'Template:' + x.split(/\{\{/)[1].split(/[|}\n]/)[0]; }) .filter(function (x) { return !conf.blacklistedTemplatePattern.test(x); });

if (links.length === 0) { return; }

if (conf.homeWiki === 'fa') { links = links.filter(hasNotPersianCharacter); }

return translate(links).then(function (result) {				raw = raw.replace(templatesRegexp, function ($0, $1, $2, $3) { return result['Template:' + $2] ? ($1 + result['Template:' + $2].replace(/[^:]*:/, '') + $3) : $0; });			});

}).then(function { // Persian specific cleanings, disabled: https://fa.wikipedia.org/؟diff=18668571 //if (conf.homeWiki === 'fa') //	raw = raw.replace(/\]\]s/g, ']]').replace(/, /g, '، '); translationTextArea.val(raw); });	}	function showMissingsTable(missings) {		// Red nodes inserted after the missing pages		Object.keys(missings).map(function (page) { if (!missings[page].langlinks) return; $('a[title="' + page + '"]').after(				' ( ' + missings[page].langlinks + ' ) '			);		});

// Missings table var links = Object.keys(missings).map(function (page) {			return [page, missings[page].langlinks, missings[page].links === 500 ? '500+' : missings[page].links];		}).filter(function (x) { return x[1]; }); links = links.sort(function (x, y) { return y[1] - x[1]; }); var missingsTable = ' '; $(' ' + conf.listOfUnavailablePagesOn + ' ' + conf.homeWiki + '.wiki:\n ' + missingsTable + ' ').insertAfter('#translatorBar'); }

function viewTranslator(showMissings) { $('.linkstranslator-added-content, #linkstranslator-missings-wrapper').remove; $('#translator-button').css('color', 'lightgray'); var titles = {}; $('#bodyContent a').get.forEach(function (x) {			var href = x.getAttribute('href');			if (!href || x.getAttribute('href').indexOf('#') === 0) { return; }			var title = x.title;			if (!title && href.indexOf('/wiki/') === 0) {				title = decodeURI(href.replace(/\/wiki\//, )).replace(/_/g, ' ');			}			title = title.replace(/#.*$/g, );			if (title) {				titles[title] = true;			}		}); titles = Object.keys(titles); translate(titles, showMissings).then(function (result) {			$('.linkstranslator-added-content, #linkstranslator-missings-wrapper').remove;

$('#translator-button').css('color', '#808b96');

Object.keys(result).forEach(function (from) {				if (from.indexOf('#') === 0) return;				var to = result[from];				$('#bodyContent a[title="' + from + '"], #bodyContent a[href="/wiki/' + encodeURI(from.replace(/ /g, '_')) + '"]').after( ' ( ' + to + ' ) ' );			});

if (showMissings) showMissingsTable(result['#missings']); });	}	function saveLanguageConfigs {		if ($('#translator-from').text.trim === ) {			$('#translator-from').text(conf.fromLang || 'fa');		}		conf.fromLang = $('#translator-from').text;		$.cookie("fromLang", conf.fromLang);		if ($('#translator-to').text.trim === ) {			$('#translator-to').text(conf.homeWiki || 'en');		}		conf.homeWiki = $('#translator-to').text;		$.cookie("homeWiki", conf.homeWiki);	}

$(function {		$('#translatorBar').remove;

var hb = []; // HTML Builder hb.push(' ');

var bar = conf.translatorBarFormat; bar = bar.replace('$1', '' + (action === 'view' ? '= ▶️ ' : '') + ''); bar = bar.replace('$2', '' + (action === 'view' ? '+' : '')); bar = bar.replace('$3', ' ' + conf.fromLang + ' '); bar = bar.replace('$4', ' ' + conf.homeWiki + ' '); bar = bar.replace('$5', '-');

hb.push(bar);

if (action === "edit" || action === "submit") { hb.push(' ' + conf.templateTranslatorText + ' '); hb.push(' ' + conf.removeLinksAliasesText + ' '); }

$('h1.firstHeading:first').append(hb.join(''));

$('#translator-button').click(function (event) {			event.preventDefault;			saveLanguageConfigs;			if (action === 'edit' || action === 'submit') {				editboxTranslator;			} else {				viewTranslator(false);			}		}); // run translator if is in tofawiki context if (window.self !== window.top && location.hash === '#tofawikiframe') { viewTranslator(false); $('#mw-page-base, #mw-head-base, #mw-navigation, #firstHeading, #siteSub, #footer, .read-more-container').remove; $('#content').css('margin-left', 0).css('padding-top', 0); }

$('#translator-equ').click(function (event) {			event.preventDefault;			var title = mw.config.get('wgTitle');			$('#translator-equ-links').html( '<a target="_blank" href="//translate.google.com/translatew_t?sl=' + conf.fromLang + '&tl=' + conf.homeWiki + '&q=' + title + '">Translator</a> / ' + '<a target="_blank" href=\'//www.google.com/search?q="' + encodeURI(title) + '"&lr=lang_' + conf.homeWiki + '\'>Specific Language Search</a> / ' + '<a target="_blank" href=\'https://www.bing.com/translator\'>Bing Translator</a>');		});

$('#translator-equ-play').click(function (e) {			e.preventDefault;			new Audio('https://fa-tts.wmflabs.org/?text=' + encodeURI(mw.config.get('wgTitle'))).play;		}); // hide play button on non-English wiki mw.config.get('wgContentLanguage') !== 'en' && $('#translator-equ-play').hide;

$('#translator-plus').click(function (event) {			event.preventDefault;			saveLanguageConfigs;			viewTranslator(true);		}); $('#translator-switch').click(function (event) {			event.preventDefault;

var t = conf.homeWiki;

conf.homeWiki = conf.fromLang; $.cookie("homeWiki", conf.fromLang); $('#translator-to').text(conf.fromLang);

conf.fromLang = t;			$.cookie("fromLang", t); $('#translator-from').text(t); });		// disable enter on them		$('#translator-from, #translator-to').keypress(function (e) { if (e.which !== 13) return; $(this).blur; e.preventDefault; });		$('#translator-from, #translator-to').focusout(saveLanguageConfigs);

$('#enableTemplateTranslation').attr('checked', conf.enableTemplateTranslation).click(function {			conf.enableTemplateTranslation = this.checked;		});

$('#removeLinksAliases').attr('checked', conf.removeLinksAliases).click(function {			conf.removeLinksAliases = this.checked;		}); }); }(jQuery, mediaWiki));