Utilisateur:Phe/Auteur v2.js

La bibliothèque libre.

Note : après avoir enregistré vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

  • Firefox / Safari : Maintenez la touche Maj (Shift) en cliquant sur le bouton Actualiser ou pressez Ctrl-F5 ou Ctrl-R (⌘-R sur un Mac) ;
  • Google Chrome : Appuyez sur Ctrl-Maj-R (⌘-Shift-R sur un Mac) ;
  • Internet Explorer : Maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5 ;
  • Opera : Allez dans Menu → Settings (Opera → Préférences sur un Mac) et ensuite à Confidentialité & sécurité → Effacer les données d'exploration → Images et fichiers en cache.
// Create an author page and attempt to fill it

var auteur_v2 = {
    check_redirect : function (title, text_box) {
        var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath')
            + "/api.php?format=xml&action=query&prop=info&titles="
            + encodeURIComponent(title);
        var request = sajax_init_object();
        request.open('GET', url, true);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                var xml = request.responseXML;
                if (xml == null) return ;
                var page = xml.getElementsByTagName( "page" )[0];
                if (page.getAttribute("missing") != "")
                    text_box.value = '#REDIRECT [[' + title + ']]';
            }
        };
        request.send(null);
    },


    author_fill_cb : function (data) {
        var wpTextbox1 = document.getElementById("wpTextbox1");
        if (wpTextbox1 && !data.query.pages["-1"]) {
            for (var ids in data.query.pages) {
                var birth = 0, death = 0;
                var cats = data.query.pages[ids].categories;
                for (var i = 0; i < cats.length; ++i) {
                    var m = cats[i].title.match(/Catégorie:Naissance en (\d+)/);
                    if (m)
                        birth = Number(m[1]);
                    m = cats[i].title.match(/Catégorie:Décès en (\d+)/);
                    if (m)
                        death = Number(m[1]);
                }

                if (birth)
                    wpTextbox1.value = wpTextbox1.value.replace(/( \| anneeNaissance = )/, "$1" + birth);
                if (death)
                    wpTextbox1.value = wpTextbox1.value.replace(/( \| anneeDeces = )/, "$1" + death);
                break;
            }
            
            // This can undo all the above works by preferring to create a redirect to an existing author:
            this.check_redirect('Auteur:' + data.query.pages[ids].title, wpTextbox1);
        }
    },

    create_script_obj : function (url) {
        var scriptObj = document.createElement("script");
        scriptObj.setAttribute("type", "text/javascript");
        scriptObj.setAttribute("src", url);
        document.body.appendChild(scriptObj);
    },

    get_title : function () {
        if (mw.config.get('wgNamespaceNumber') == 2)
            return mw.config.get('wgTitle').split('/')[1].split(':')[1];
        return mw.config.get('wgTitle');
    },

    split_title : function () {
        return this.get_title().replace(/ \(.*\)/, "").split(" ");
    },

    get_special_word_pos : function (words) {
        var i;
        for (i = 0; i < words.length; ++i) {
            if (words[i] == 'van' || words[i] == 'von' ||
                words[i] == 'le' || words[i] == 'de') {
               return i;
            }
        }
        return -1;
    },

    get_first_name : function (words) {
        return words.slice(0, this.get_special_word_pos(words)).join(" ");
    },

    get_last_name : function (words) {
        return words.slice(this.get_special_word_pos(words)).join(" ");
    },

    remove_diacritics : function (cle) {
        var result = "";
        // only the most commons
        var diacritics = {
           'À' : 'A',
           'à' : 'a',
           'â' : 'a',
           'É' : 'E',
           'é' : 'e',
           'È' : 'E',
           'è' : 'e',
           'ç' : 'c'
        };
        for (var i = 0 ; i < cle.length; ++i) {
            if (diacritics[cle.charAt(i)])
                result += diacritics[cle.charAt(i)];
            else
                result += cle.charAt(i);
        }
        return result;
    },

    get_last_initial : function (words) {
        // get_last_name() can't be used here, we want the last word or the next
        // word following a special word
        var lastname = words[words.length - 1];
        var pos = this.get_special_word_pos(words);
        if (pos != -1 && pos < words.length - 1)
            lastname = words[pos + 1];

        var last_initial = lastname.slice(0, 1);
        // O'Donnel --> Od
        //if (lastname.length > 2 && last_initial.charAt(1) == "'")
        //    last_initial = last_initial.charAt(0) + lastname.charAt(2).toLowerCase();
        return this.remove_diacritics(last_initial);
    },

    preloadAuthorTemplate_v2 : function () {
        var wpTextbox1 = document.getElementById("wpTextbox1")
        if (wpTextbox1.value != "")
            return;

        // try to figure out what value we can fill, broken in some case because
        // it's difficult to handle name like Tom Van Moore but Tom van Moore is
        // handled correctly.
        var words = auteur_v2.split_title();
        var lastname = auteur_v2.get_last_name(words);
        var firstname = auteur_v2.get_first_name(words);
        var last_initial = auteur_v2.get_last_initial(words);
        var cle = auteur_v2.remove_diacritics(lastname + ", " + firstname);

        wpTextbox1.value  = "{{Auteur\n" +
                            " | nom = " + auteur_v2.get_title() + "\n" +
                            " | cle = " + cle + "\n" +
                            " | initiale = " + last_initial + "\n" +
                            " | anneeNaissance = " + "\n" + 
                            " | anneeDeces = " + "\n" +
                            " | description = " + "\n" +
                            " | metier = " + "\n" +
                            "}}\n\n" +
                            "== Œuvres ==\n\n";

        var base_url = "//fr.wikipedia.org"
            + mw.config.get('wgScriptPath')
            + "/api.php?format=json&redirects";
        var url = base_url
            + "&callback=auteur_v2.author_fill_cb&action=query&prop=categories&cllimit=20&titles="
            + encodeURIComponent(auteur_v2.get_title());

        auteur_v2.create_script_obj(url);
    }
}

if (mw.config.get('wgAction') == "edit" && mw.config.get('wgNamespaceNumber') == 102)
    $(document).ready(auteur_v2.preloadAuthorTemplate_v2);