User:V111P/js/wikiTranslTools.js
Appearance
< User:V111P | js
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | This user script seems to have a documentation page at User:V111P/js/wikiTranslTools. |
/* Wiki Translation Tools v. 1.111 - March 2013 */
window.wikiTranslTools = (function ()
{
"use strict";
var THIS_ARTICLE = mw.config.get('wgPageName').replace(/_/g, ' ');
/*******
* Home-Wiki Constants - need to be set with init()
******/
var homeWiki = {
lang: '',
server: '',
faLinkTemplate: 'Link FA',
gaLinkTemplate: 'Link GA',
translatedPageTemplate: ''
};
var skin = { // values must be CSS/jQuery selectors
outputArea: '#contentSub',
permalink: '#t-permalink a', // leave empty to use the document URL and a built-in MediaWiki variable
interwikiDiv: '#p-lang',
catLinks: '#mw-normal-catlinks' // the <div> with the non-hidden categories
// Leave empty to use the built-in wgCategories array (which includes hidden cats)
};
/*******
* Local-Wiki Constants
******/
var thisWiki = {
lang: mw.config.get('wgContentLanguage'),
// These strings are used to find out which articles have a 'Good' or 'Featured' status
// in this and in the other Wikipedias.
featArticle: {
tagIdBeginning: 'interwiki-',
tagIdEnding: '-fa',
tagClass: '',
catName: 'Featured articles'
},
goodArticle: {
tagIdBeginning: 'interwiki-',
tagIdEnding: '-ga',
tagClass: '',
catName: 'Good articles'
},
catNS: mw.config.get('wgFormattedNamespaces')[14] // The local name of the Category namespace
};
/******
* Other customizable options
******/
var options = {
// number of rows for the output textarea
taRows: 10,
// this has no effect in Monobook and other skins
taCols: 80,
// if the article has that many categories or less, they will be auto-expanded
// when the Category Browser is shown for the first time on the page.
maxCatsToAutoExpand: 5
};
/*******
* Other Constants
******/
// Home wiki links will be added only to these namespaces:
// Namespases: main=0, user=2, wikipedia/wp=4, template=10, help=12, category=14, portal=100
var NamespacesWithInterwikis = [0, 2, 4, 10, 12, 14, 100];
// the messages
var _ = {
error: 'error',
okButtonLabel: 'OK',
interwikis: 'FA, GA templates',
categories: 'Categories',
trCatInterw: 'Cat/Tr/FA/Comm',
trCatInterwTitle: 'Categories, {{Translated page}}, {{Link FA}}, {{Link GA}}, {{Commons}} ',
alreadyListed: 'already listed',
linksTo: 'Links to',
dblRedirect: 'double redirect'
};
var nl = ($.browser.msie ? '\r\n' : '\n'); // new line
/*******
* Private Variables
******/
var allCats; // used for the Category Browser
var catsTranslInterw; // boolean,
// "true" when getting categories, translated page template, and fa/ga templates at the same time
/* A class to hold info about a category */
function Category(name, liElement)
{
this.name = name;
this.liElement = liElement; // the innermost <li> within which the category's name is shown
}
// a shortcut for document.createTextNode()
function textNode(str)
{
return document.createTextNode(str);
}
/*************************
*** TRANSLATED PAGE TEMPLATE
***
*** showTranslatedPageTemplate() - public
*** getTranslatedPageTemplate()
***/
/* PUBLIC */
// called when the user clicks on the {{Translated page}} portlet link.
function showTranslatedPageTemplateCode()
{
if ($('#wikiCodeBox').remove().attr('name') == 'translationTemplate')
return;
catsTranslInterw = false;
displayCode(getTranslatedPageTemplate(), 'translationTemplate');
}
function getTranslatedPageTemplate()
{
var revisionId;
var permalink = [];
if (skin.permalink)
permalink = $(skin.permalink);
if (permalink[0])
revisionId = permalink.attr('href').match(/oldid=(.+)/)[1];
else
{
var regExpResult = location.href.match(/oldid=([^&#]+)/);
revisionId = regExpResult && regExpResult[1];
if (!revisionId)
revisionId = mw.config.get('wgCurRevisionId');
}
return '{{' + homeWiki.translatedPageTemplate + '|'
+ thisWiki.lang + '|' + THIS_ARTICLE + '|' + revisionId + '}}';
}
/*************************
*** INTERWIKIS
***
*** void showInterwikiCode() - public
*** Array getInterwikis()
*** string getInterwikiCode()
***/
/* PUBLIC */
// called when the user clicks on the Interwikis portlet link
function showInterwikiCode()
{
if ($('#wikiCodeBox').remove().attr('name') == 'interwikis')
return;
catsTranslInterw = false;
displayCode(getInterwikiCode(), 'interwikis');
}
function getInterwikis()
{
var links = [], langs = [];
$(skin.interwikiDiv + ' a').each(function (){
var result = $(this).attr('href').match(/\/\/([^\.]+)\.[^\/]+\/wiki\/(.+)/);
if (!result || result[1] == 'www')
return;
var lang = result[1];
var title = decodeURI(result[2]).replace(/_/g, ' ');
if (lang != homeWiki.lang) {
links[lang] = title;
langs.push(lang);
}
});
return {langs: langs, links: links};
}
// reads the interwikis from the element with the specified in SKIN.INTERWIKI_DIV id
// calls goodArticleLinks() to check for 'Good' and 'Featured' articles
function getInterwikiCode()
{
var interwikis = getInterwikis();
var links = interwikis.links;
var langs = interwikis.langs;
/* adding this page's wikilink to the array */
links[thisWiki.lang] = THIS_ARTICLE;
langs.push(thisWiki.lang);
langs.sort();
var interwikisStr = '';
for (var i = 0; i < langs.length; i++)
interwikisStr += '[[' + langs[i] + ':' + links[langs[i]] + ']]' + nl;
return getFaGaTemplateCode(langs) + interwikisStr;
}
/*************************
*** FA/GA templates
***
*** void showFaGaTemplateCode() - public
*** string getFaGaTemplateCode()
*** string goodArticleLinks(langArr, goodArticleStrings, homeGALinkTemplate)
***/
/* PUBLIC */
// called when the user clicks on the Interwikis portlet link
function showFaGaTemplateCode()
{
if ($('#wikiCodeBox').remove().attr('name') == 'faGa')
return;
catsTranslInterw = false;
displayCode(getFaGaTemplateCode(), 'faGa');
}
// reads the interwikis from the element with the specified in skin.interwikiDiv id
// calls goodArticleLinks() to check for 'Good' and 'Featured' articles
function getFaGaTemplateCode(langArr)
{
var langs = langArr || getInterwikis().langs;
var featArticlesStr = goodArticleLinks(langs, thisWiki.featArticle, homeWiki.faLinkTemplate);
var goodArticlesStr = goodArticleLinks(langs, thisWiki.goodArticle, homeWiki.gaLinkTemplate);
return featArticlesStr + goodArticlesStr;
}
// this function is used to get both the "Good Articles" and the "Featured Articles"
function goodArticleLinks(langArr, goodArticleStrings, homeGALinkTemplate)
{
var goodArticleArr = [];
for (var i = 0; i < langArr.length; i++)
{
var goodTag = $('#' + goodArticleStrings.tagIdBeginning
+ langArr[i]
+ goodArticleStrings.tagIdEnding);
if (goodTag[0])
if (goodArticleStrings.tagClass)
goodTag = goodTag.filter('.' + goodArticleStrings.tagClass);
if (goodTag[0])
goodArticleArr.push(langArr[i]);
}
// check and add this article
var cats = mw.config.get('wgCategories');
for (var i = cats.length - 1; i >= 0; i--) {
if (cats[i] == goodArticleStrings.catName) {
goodArticleArr.push(thisWiki.lang);
break;
}
}
goodArticleArr.sort();
var goodArticleStr = '';
for (var i = 0; i < goodArticleArr.length; i++) {
goodArticleStr += '{{' + homeGALinkTemplate + '|' + goodArticleArr[i] + '}}' + nl;
}
if (goodArticleStr) goodArticleStr += nl;
return goodArticleStr;
}
/*************************
*** COMMONS TEMPLATE
***
*** commonsTemplate() - public
*** getCommonsTemplate
***/
/* PUBLIC */
function showCommonsTemplateCode() {
if ($('#wikiCodeBox').remove().attr('name') == 'commons')
return;
catsTranslInterw = false;
displayCode(getCommonsTemplate(), 'commons');
}
function getCommonsTemplate() {
var commonsStr = '', template;
var $commonsLinks = $('a[href*="//commons.wikimedia.org/wiki/"]');
var commonsLinksArr = [];
$commonsLinks.each(function (i, el) {
var href = $(this).attr('href');
if (href.match(/wiki\/(file|image|media):/i) || href.match(/Special:UploadWizard/))
return;
href = href.replace(/_/, ' ').replace(/\?.*$/, '');
var title = decodeURIComponent(href.replace(/.+?\/wiki\//, ''));
var page = title.replace(/^Category:/, '');
if (title != href) {
if (title.match(/^Atlas of/))
template = '* {{wikiatlas|' + title.replace(/^Atlas of./, '') + '}}';
else
template = '{{commons' + (page != title ? 'cat' : '')
+ '|' + page + '}}';
if ($.inArray(template, commonsLinksArr) == -1)
commonsLinksArr.push(template);
}
});
if (commonsStr = commonsLinksArr.join('\n'))
commonsStr += '\n\n';
return commonsStr;
}
/*************************
*** CATEGORIES
***
*** void catsTranslInterw() - public
*** void categories() - public
*** void createTheCategoryBrowser()
*** JQueryObject createExpandCatLink()
*** void expandCat(HTMLElementObject startCatExpandLinkEl)
*** void catInfoReceived(apiResponceJson)
*** void showCatParents(Category cat, String[] parents, String homeWikiCat)
*** void catsOK(HTMLFormElement frm)
*** void afterCats(String catsStr)
***/
/* PUBLIC */
// called when the user clicks on the "Tr/Cat/Interwikis" portlet link
function catsTranslInterwGo()
{
if ($('#wikiCodeBox').remove().attr('name') == 'categories')
return; // remove the text area if it already contains the categories and do nothing else
catsTranslInterw = true;
if (!$('#catBrowserDiv').show()[0])
createTheCategoryBrowser();
}
/* PUBLIC */
// Called when the user clicks on the portlet link
function categories()
{
// if the user previously clicked on the "Tr/Cat/Interwikis" portlet link, cancel that:
catsTranslInterw = false;
if ($('#wikiCodeBox').remove().attr('name') == 'categories')
return; // remove the text area if it already contains the categories and do nothing else
if ($('#catBrowserDiv').toggle()[0]) // if the Category Browser already exists, just show/hide it
return;
createTheCategoryBrowser();
}
// Called from categories() to create the Category Browser
function createTheCategoryBrowser()
{
var catArr = [];
// if possible, fill catArr with the non-hidden cats only,
// otherwise use wgCategories
if (skin.catLinks)
catArr = $(skin.catLinks + ' a').map(function(i) {
if (i == 0) return null; // skip the 'Categories:' link
return getInnerText(this);
}).toArray();
else
catArr = mw.config.get('wgCategories');
if (catArr.length == 0)
{
afterCats('');
return;
}
allCats = {};
// create the main UL and sub li's with the category names
var top_ul = $('<ul/>');
var catBrowserDiv = $('<div/>', {
css: {color: '#000', backgroundColor: '#f4f4f4', fontSize: 'small'},
id: 'catBrowserDiv'
});
var top_li;
for (var i = 0; i < catArr.length; i++)
{
var expandLink = createExpandCatLink();
top_li = $('<li/>').append(expandLink, textNode(' '), '<span>' + catArr[i] + '</span>');
allCats[catArr[i]] = new Category(catArr[i], top_li);
top_ul.append(top_li);
if (catArr.length <= options.maxCatsToAutoExpand)
expandLink.click();
}
var catForm = $('<form/>', {
id: 'catForm',
submit: function() {
catsOK(this);
return false;
}
})
.append('<input type="submit" value="' + _['okButtonLabel'] + '"/>',
top_ul,
'<input type="submit" value="' + _['okButtonLabel'] + '"/>');
catBrowserDiv.append(catForm)
.appendTo($(skin.outputArea)[0] || $('body'));
$('html, body').scrollTop(catBrowserDiv.offset().top);
} // translateCategories()
function createExpandCatLink()
{
return $('<a/>', {
text: '[+]',
href: '#',
click: function() {
expandCat(this);
return false;
},
css: {textDecoration: 'none'}
});
}
// Called when the user clicks on a [+] expand link in the Category Browser
// It makes an AJAX request for the specified category page,
// and calls showCatParents() to display the obtained information
// (the parent cats and (if there is one) the home-wiki cat)
function expandCat(startCatExpandLinkEl)
{
var startCatLink = $(startCatExpandLinkEl);
var catSpan = $('span', startCatLink.parent()); // it contains the name of the cat to be expanded
startCatLink.off('click').text('...'); // replace "[+]" with "..."
startCatLink.attr('class', 'waitingExpandLink');
var cat = allCats[getInnerText(catSpan[0])];
$.ajax({
url: '/w/api.php?action=query&prop=langlinks|categories&titles=' + thisWiki.catNS + ':' + cat.name
+ '&lllang=' + homeWiki.lang + '&cllimit=200&redirects&format=json',
dataType: 'json',
success: catInfoReceived(cat),
error: function (XMLHttpRequest) {
showCatParents(cat);
}
});
}
// creates and returns a function to be called when the requested Category page information is received
function catInfoReceived(cat)
{
return function(data) {
function parentCats(data) {
var pages = data && data.query && data.query.pages;
if (!pages)
return;
var pg;
for (var p in pages) {
if (pages.hasOwnProperty(p))
pg = pages[p];
}
var catObjs = pg && pg.categories;
if (!catObjs)
return;
var cats = [];
for (var i = 0; i < catObjs.length; i++) {
cats.push(catObjs[i].title.replace(/^[^:]+:/, ''));
}
return cats;
}
showCatParents(cat, parentCats(data), getHomewikiFromJson(data));
};
} // catInfoReceived
// called by expandCat() to add the parent categories
// of the specified category to the displayed list.
function showCatParents(cat, parents, homeWikiCat)
{
var top_li = cat.liElement;
var server = mw.config.get('wgServer');
$('.waitingExpandLink', top_li).remove();
if (homeWikiCat)
{
var homeWikiLink = $('<a/>', {
text: homeWikiCat,
href: homeWiki.server + '/wiki/' + homeWikiCat,
target: '_blank'
});
top_li.append(textNode(' – '),
'<input type="checkbox" name="homecats" value="' + homeWikiCat + '"/>',
textNode(' ' + homeWiki.lang + ':'),
homeWikiLink);
}
else if (parents && parents.length > 0)
{
var new_ul = $('<ul/>');
var new_li;
var alreadyListed;
for (var i = 0; i < parents.length; i++)
{
new_li = $('<li/>');
alreadyListed = false;
if (allCats[parents[i]])
alreadyListed = $('<em>(' + _['alreadyListed'] + ')</em>');
else
{
new_li.append(createExpandCatLink(), textNode(' '));
allCats[parents[i]] = new Category(parents[i], new_li);
}
new_li.append('<span>' + parents[i] + '</span>');
if (alreadyListed)
{
new_li.append(textNode(' '), alreadyListed);
}
new_ul.append(new_li);
}
top_li.append(new_ul);
} // if (parents.length > 0)
else // if no home-wiki cat and no parent cats found, create a link to the cat,
// so the user can check manually
{
var catSpan = $('span', top_li).empty();
catSpan.append($('<a/>', {
href: server + '/wiki/'
+ thisWiki.catNS + ':' + cat.name,
target: '_blank',
text: cat.name
}))
.append(textNode(' '),
// no parents arr is passed if the cat doesn't exist (404 or other error received)
$('<em>(' + _['error'] + ')</em>')
);
}
} // showCatParents
// called when the user press the OK button in the "Category Browser"
function catsOK(frm)
{
$('#catBrowserDiv').hide();
var homeCats = $('input:checkbox[name=homecats]:checked', frm).map(function(){
return this.value;
}).toArray();
if (homeCats.length == 0)
{
if (catsTranslInterw)
afterCats('');
return;
}
var catStr = '[[' + homeCats.join(']]'+nl+'[[') + ']]';
if (catsTranslInterw)
afterCats(catStr);
else
displayCode(catStr, 'categories');
}
function afterCats(catsStr)
{
if (!catsTranslInterw)
return;
catsTranslInterw = false;
displayCode(getCommonsTemplate() + getTranslatedPageTemplate() + nl + nl
+ (catsStr ? catsStr + nl + nl : '')
+ getFaGaTemplateCode(), 'categories');
}
/*************************
*** HOME-WIKI LINKS
***
*** homeWikiLinks() - public
*** findHomeWikiLink(HTMLElementObject clickedLinkEl)
*** interwikiReceived(JQueryObject clickedLink)
***/
/* PUBLIC */
// called when the user clicks on the "Links to (language code)" portlet link
function homeWikiLinks()
{
var namespaceIds = mw.config.get('wgNamespaceIds');
var hWLs = $('.homeWikiLink');
if (hWLs.length > 0)
{ // if already shown, hide them and return
hWLs.toggle();
return;
}
$($('#mw-content-text')[0] || $('body')).find('a')
.not('#catBrowserDiv a').not(skin.catLinks + ' a').not('a.external')
.filter('[href^="/wiki/"]').after(function () {
var article = this.href.match(/wiki\/([^#?]+)/);
if (!article)
return null;
article = article[1];
// Check if the namespace is in the array of approved namespaces: NamespacesWithInterwikis
var ns = article.match(/[^:]+(?=:)/);
if (ns)
{
var nsNum = namespaceIds[ns[0].toLowerCase()];
if (nsNum && ($.inArray(nsNum, NamespacesWithInterwikis) == -1))
return null;
}
var span = $('<sup/>', {
text: ' [[',
'class': 'homeWikiLink reference'
}).append($('<a/>', {
text: homeWiki.lang + ':?',
href: '#',
data: {articleName: article},
click: function () {
findHomeWikiLink($(this));
return false;
}
})).append(textNode(']]'));
return span;
});
}
// This function is called when the user clicks on one of the [[lang:?]] links
function findHomeWikiLink($clickedLink)
{
var articleName = $clickedLink.data('articleName');
$.ajax({
url: '/w/api.php?action=query&prop=langlinks&titles=' + articleName
+ '&lllang=' + homeWiki.lang + '&redirects&format=json',
dataType: 'json',
success: function (data) {
interwikiReceived(data, $clickedLink);
}
});
}
// called when the HTML page
// (which is going to be searched for a link to the Home Wiki article) is received
function interwikiReceived(data, $clickedLink)
{
var homeWikiPage = getHomewikiFromJson(data);
if (!homeWikiPage) {
$clickedLink.replaceWith($('<span/>', {
text: homeWiki.lang,
css: {textDecoration: 'line-through'}
}));
return;
}
var newLink = $('<a/>', {
href: homeWiki.server + '/wiki/' + homeWikiPage,
target: '_blank',
text: homeWiki.lang + ':'
});
var input = $('<input type="text" style="vertical-align: bottom; direction: ltr;">').attr({
value: homeWikiPage,
size: Math.floor(homeWikiPage.length * 4/3),
readonly: 'readonly'
});
var redirects = data && data.query && data.query.redirects;
if (redirects)
for (var i = 0; i < redirects.length; i++) {
$clickedLink.before($('<span title="' + redirects[i].to + '">></span>'));
}
$clickedLink.after(input);
$clickedLink.replaceWith(newLink);
input.select();
}
/*************************
*** Other Functions
***
*** string getHomewikiFromJson(jsonObjReturnedByTheAPIcall)
*** void displayCode(String str, String name)
*** void addPortletLinks()
*** void init(attr) - public
***/
function getHomewikiFromJson(data) {
//{"query":{"pages":{"5152":{"pageid":5152,"ns":0,"title":"2007","langlinks":[{"lang":"bg","*":"2007"}]}}}}
var pages = data && data.query && data.query.pages;
if (!pages)
return;
var pg;
for (var p in pages) {
if (pages.hasOwnProperty(p))
pg = pages[p];
}
return pg && pg.langlinks && pg.langlinks[0] && pg.langlinks[0]['*'];
}
function displayCode(str, name)
{
$('#catBrowserDiv').hide();
var wikiCodeBox = $('#wikiCodeBox');
if (wikiCodeBox.show()[0])
wikiCodeBox.text = str;
else
{
wikiCodeBox = $('<textarea/>', {
id: 'wikiCodeBox',
text: str,
name: name,
css: {direction: 'ltr', width: '80%', display: 'block'},
cols: options.taCols,
rows: options.taRows,
readonly: 'readonly'
})
.appendTo($(skin.outputArea)[0] || $('body'))
.select().focus().scrollTop();
}
}
function addPortletLinks()
{
var ns = mw.config.get('wgCanonicalNamespace');
if (ns != 'Special' && ns != 'MediaWiki') {
if (!$('#catTranslInterwLink')[0])
addPortletLink('p-tb', 'javascript:wikiTranslTools.catsTranslInterw(); void(0);',
_['trCatInterw'],
'catTranslInterwLink',
_['trCatInterwTitle']
);
}
if (homeWiki.lang && !$('#homeWikiLinksLink')[0])
addPortletLink('p-tb', 'javascript:wikiTranslTools.homeWikiLinks(); void(0);',
_['linksTo'] + ' ' + homeWiki.lang,
'homeWikiLinksLink',
_['linksTo'] + ' ' + homeWiki.lang
);
}
/* PUBLIC */
// call after updating window.wikiTranslToolsConfig
function init(noPortletLinks)
{
var wttC = window.wikiTranslToolsConfig;
if (wttC) {
$.extend(homeWiki, wttC.homeWiki || {});
$.extend(true, thisWiki, wttC.thisWiki || {});
$.extend(skin, wttC.skin || {});
$.extend(_, wttC.msgs || {});
$.extend(options, wttC.options || {});
}
if (homeWiki.lang && (!wttC || !wttC.homeWiki || !wttC.homeWiki.server))
homeWiki.server = mw.config.get('wgServer').replace(thisWiki.lang, homeWiki.lang);
if (!noPortletLinks && mw.config.get('wgAction') == 'view')
$(addPortletLinks);
}
init();
/* All public member functions */
return {
init: init,
translatedPage: showTranslatedPageTemplateCode,
interwikis: showInterwikiCode,
faGa: showFaGaTemplateCode,
commons: showCommonsTemplateCode,
categories: categories,
catsTranslInterw: catsTranslInterwGo,
homeWikiLinks: homeWikiLinks
};
}());