Jump to content

User:Wnt/ArticleTranslator.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Wnt (talk | contribs) at 00:23, 3 November 2013 (Arbitrarily deleting everything from getLinkTitle on). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/*!
 * Distributed under the terms of the CC-BY-SA 3.0
 */
// DO NOT COPY IT FOR TRANSLATION, READ THE DOCUMENTATION [[:en:User talk:Ebraminio/ArticleTranslator.js]]
/*jslint browser: true, regexp: true, unparam: true*/
/*global jQuery, mediaWiki*/
(function ($, mw) {
    'use strict';
    var translationTextArea,
        progressCount,
        itemsCount,
        ajaxUrl,
        conf = {
            'homeWiki': 'fa',
            'fromLang': mw.config.get('wgPageContentLanguage'),
            'translatorBarFormat': '$1translate$2 links from $3 to $4 ($5)',
            'templateTranslatorText': 'Template translation',
            'removeLinksAliasesText': 'Remove Links Aliases',
            'doneText': 'Done!',
            'enableTemplateTranslation': true,
            'removeLinksAliases': true,
            'enableNeedingShow': false,
            'name': 'Name',
            'interwikiCount': 'Interwiki Count',
            'linkedTo': 'Linked to',
            'listOfUnavailablePagesOn': 'List of not available pages on',
            'definedTemplates': ["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"]
        },
        definedTemplateList;
 
    $.extend(conf, window.articleTranslatorConf);
 
    // getting the last translator preference from the cookie
    if ($.cookie('homeWiki') !== null) {
        conf.homeWiki = $.cookie('homeWiki');
    }
 
    if ($.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 getOrigin() {
        var result = location.protocol + '//' + location.host;
        if (location.port !== '') {
            result = result + ':' + location.port;
        }
        return result;
    }
 
    function getOriginOfWikiLang(lang) {
        return getOrigin().replace(mw.config.get('wgPageContentLanguage'), lang);
    }
 
    function setAjaxUrl() {
        var tailOfApiUrl = '/api.php?action=query&prop=langlinks&redirects=&format=json&lllimit=500&titles=';
        if (conf.enableNeedingShow === true) {
            tailOfApiUrl = '/api.php?action=query&prop=langlinks|links&redirects=&format=json&pllimit=500&lllimit=500&titles=';
        }
        ajaxUrl = getOriginOfWikiLang(conf.fromLang) + mw.config.get('wgScriptPath') + tailOfApiUrl;
    }
 
    function getSelectedTextLinks() {
        // borrowed from: http://stackoverflow.com/questions/4220478 :)
        var selection,
            selectionAncestor,
            range,
            allWithinRangeParent;
 
        // if `window.getSelection` is not defined (on IE) return nothing.
        if (window.getSelection === undefined) {
            return [];
        }
        selection = window.getSelection();
 
        // if nothing is selected, return empty array
        if (selection.isCollapsed) {
            return [];
        }
 
        range = selection.getRangeAt(0);
        selectionAncestor = range.commonAncestorContainer;
        if (selectionAncestor.getElementsByTagName === undefined) { // if it is not a formal HTML selection
            return [];
        }
        allWithinRangeParent = selectionAncestor.getElementsByTagName('a');
 
        return $.map(allWithinRangeParent, function (el) {
            // The second parameter says to include the element
            // even if it's not fully selected
            if (selection.containsNode(el, true)) {
                return el;
            }
        });
    }
 
    function onFinish() {
        $('#translatorProgress').hide('slow');
        $('#translatorStatus').css('font-weight', 'bold').text(conf.doneText).show('slow');
        if (conf.enableNeedingShow) {
            var links = [],
                result,
                linksCount,
                titleExistance = {},
                title;
            $('.translatorNeededLink').each(function (k, v) {
                title = $(v).attr('data-title');
                if (titleExistance[title] === true) {
                    return;
                }
                titleExistance[title] = true;
                linksCount = $(v).attr('data-links-to-count');
                if (parseInt(linksCount, 10) === 500) {
                    linksCount = '500+';
                }
                links.push([title, parseInt($(v).attr('data-interwikis'), 10), linksCount]);
            });
            links = links.sort(function (x, y) { return y[1] - x[1]; });
            result = '<table class="wikitable sortable"><tr><th>' + conf.name + '</th><th>' + conf.interwikiCount + '</th><th>' + conf.linkedTo + '</th></tr>' + links.map(function (x) { return '<tr><td>' + x[0] + '</td><td>' + x[1] + '</td><td>' + x[2] + '</tr>'; }).join('') + '</table>';
            $('#translatorPlusContainer').remove();
            $('<div style="line-height: 1.25; font-size: 50%;" id="translatorPlusContainer">' + conf.listOfUnavailablePagesOn + ' ' + conf.homeWiki + '.wiki:\n<div style="height: 10em; overflow-y: scroll;">' + result + '</div></div>').insertAfter('#translatorBar');
        }
    }
 
    function increaseProgressCount() {
        progressCount = progressCount + 1;
        $('#translatorProgress').attr('value', progressCount);
 
        if (progressCount === itemsCount) {
            onFinish();
        }
    }
 
    function queryTranslationFromData(data) {
        var languageLinks,
            linksToCount = 0,
            translation;
 
        if (data.query === undefined || data.query.pages === undefined) {
            return null;
        }
        $.each(data.query.pages, function (key, value) { // for retrieving first object index
            languageLinks = value.langlinks;
            if (value.links !== undefined) {
                linksToCount = value.links.length;
            }
        });
        if (languageLinks === undefined) {
            return null;
        }
        $.each(languageLinks, function (key, value) { // we can also use .filter here
            if (value.lang === conf.homeWiki) {
                translation = value['*'];
            }
        });
        return {
            translation: translation,
            linksToCount: linksToCount,
            interwikis: languageLinks.length
        };
    }
 
    function commonAjaxRunner(title, translatorFunction) {
        $.ajax({
            url: ajaxUrl + encodeURIComponent(title),
            complete: function () {
                increaseProgressCount();
            },
            success: function (data) {
                var translation = queryTranslationFromData(data);
                if (translation !== null) {
                    translatorFunction(translation);
                }
            },
            dataType: 'jsonp'
        });
    }
 
    function addTranslationToNode(node, translation) {
        if (translation.translation !== undefined) {
            node.after('<span class="translatorAddedcontent">(<a href="' + getOriginOfWikiLang(conf.homeWiki) + mw.util.wikiGetlink(translation.translation) + '">' + translation.translation + '</a>)</span>');
        } else if (conf.enableNeedingShow === true) {
            node.after('<span class="translatorAddedcontent">(<span style="color: red;" class="translatorNeededLink" data-title="' + node.attr('title') + '" data-interwikis="' + translation.interwikis + '" data-links-to-count="' + translation.linksToCount + '">' + translation.interwikis + '</span>)</span>');
        }
    }
 
    function translateFromLanguageLinkNode(title, node) {
        commonAjaxRunner(title, function (translation) {
            addTranslationToNode(node, translation);
        });
    }
 
    // for [[Link]]s in textareas
    function addTranslationToTextareaLink(title, translation) {
        translationTextArea.val(translationTextArea.val().replace(
            new RegExp('(\\[\\[:?)' + escape(title) + '((?:\\|[^\\]]*)?)(\\]\\])'),
            '$1' + translation + (conf.removeLinksAliases ? '' : '$2') + '$3'
        ));
    }
 
    function translateFromLanguageLinks(title) {
        commonAjaxRunner(title, function (translation) {
            if (translation.translation !== undefined) {
                addTranslationToTextareaLink(title, translation.translation);
            }
        });
    }
 
    // for {{template|Link}} in textareas
    function addTranslationToTextareaLinksInTemplate(title, translation) {
        var i, definedTemplate;
        for (i = 0; i < definedTemplateList.length; i = i + 1) {
            definedTemplate = definedTemplateList[i];
            translationTextArea.val(translationTextArea.val().replace(
                new RegExp('(\\{\\{\\s*(?:[Tt]emplate:)?)' + definedTemplate + '\\|' + escape(title) + '([\\|\\}])'),
                '$1' + definedTemplate + '|' + translation + '$2'
            ));
        }
    }
 
    function translateFromLanguageLinksInTemplate(title) {
        commonAjaxRunner(title, function (translation) {
            if (translation.translation !== undefined) {
                addTranslationToTextareaLinksInTemplate(title, translation.translation);
            }
        });
    }
 
    // for {{TemplateLink}}s in textareas
    function addTranslationToTextareaTemplateLink(title, translation) {
        translationTextArea.val(translationTextArea.val().replace(
            new RegExp('(\\{\\{\\s*(?:[Tt]emplate:)?)' + escape(title) + '([\\n\\|\\}])'),
            '$1' + translation + '$2'
        ));
    }
 
    function translateFromLanguageTemplateLinks(title) {
        commonAjaxRunner('Template:' + title, function (translation) {
            if (translation.translation !== undefined) {
                addTranslationToTextareaTemplateLink(title, translation.translation.replace(/^.*?:/, ''));
            }
        });
    }
 
    function parseUrl(url) {
        if (url === undefined) {
            return undefined;
        }
        var match = url.match(/\/wiki\/([^#]*)/);
        if (match === null) {
            match = url.match(/\/w\/index\.php\?title=([^&#]*).*redlink=1/);
        }
 
        if (match !== null) {
            return decodeURI(match[1]); // returns () matched text
        }
        return undefined;
    }