Utilisateur:Phe/Auteur.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.
// Crée une page auteur en tentant de remplir les champs autant
// que possible, utilise les pages liées pour remplir la section Œuvres
function check_redirect(title)
{
    var wpTextbox1 = document.getElementById("wpTextbox1");
    if (!wpTextbox1)
        return;
    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") != "")
               wpTextbox1.value = '#REDIRECT [[' + title + ']]';
        }
    };
    request.send(null);
}

function fill_work_by_cb(data)
{
    var wpTextbox1 = document.getElementById("wpTextbox1");
    if (wpTextbox1 && data.query.backlinks) {
        var titles_text = '';
        for (var i = 0; i < data.query.backlinks.length; ++i) {
            titles_text += '*[[' + data.query.backlinks[i].title + ']]\n';
        }
        if (titles_text.length) {
            wpTextbox1.value = wpTextbox1.value.replace("'''Œuvres'''\n\n", "'''Œuvres'''\n\n" + titles_text);
        }
    }
}

function fill_work_by(title)
{
    var base_url = mw.config.get('wgServer') + mw.config.get('wgScriptPath')
        + "/api.php?format=json&redirects";

    var url = base_url
        + "&callback=fill_work_by_cb&action=query&list=backlinks&blnamespace=0&blfilterredir=nonredirects&bllimit=500&bltitle="
        + encodeURIComponent(title);

    create_script_obj(url);
}

function add_cat_century(century, text_box)
{
    var centuries = {
        '14': 'XV',                        
        '15': 'XVI',
        '16': 'XVII',
        '17': 'XVIII',
        '18': 'XIX',
        '19': 'XX',
    }
    if (centuries[century])
        text_box.value += '\n[[Catégorie:Auteurs du ' + centuries[century] + 'e siècle]]';
}

function add_cat_author_century(birth, death, text_box)
{
    var century = Math.floor((birth + 20) / 100);
    add_cat_century(century, text_box);
    if (Math.floor((death - 20) / 100) != century)
        add_cat_century(Math.floor((death - 20) / 100), text_box);
}

function author_fill_cb(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(/n\?\?\?\?/, birth);
            if (death)
                wpTextbox1.value = wpTextbox1.value.replace(/m\?\?\?\?/, death);

            add_cat_author_century(birth, death, wpTextbox1);
            break;
        }
    }
    fill_work_by(mw.config.get('wgPageName'))

    // This can undo all the above works by preferring to create a redirect to an existing author:
    check_redirect(mw.config.get('wgPageName'));
}

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

function split_title()
{
    return mw.config.get('wgTitle').replace(/ \(.*\)/, "").split(" ");
}

function get_special_word_pos(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;
}

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

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

function get_last_initial(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 = 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 && (lastname.charAt(1) == "’" || lastname.charAt(1) == "'"))
        last_initial = lastname.charAt(2);
    return last_initial;
}

/* Preload Template:Author when starting an author page, derived from [[User:Remember the dot]] code */
function preloadAuthorTemplate()
{
    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 = split_title();
    var lastname = get_last_name(words);
    var firstname = get_first_name(words);
    var last_initial = get_last_initial(words);

    wpTextbox1.value  = "{" + "{auteur" +
                        "|" + mw.config.get('wgTitle') + "" +
                        "|" + lastname + "" +
                        "|" + last_initial + "" +
                        "|(n????-m????)" + "" +
                        "}}\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=author_fill_cb&action=query&prop=categories&cllimit=20&titles="
        + encodeURIComponent(mw.config.get('wgTitle'));

    create_script_obj(url);
}

function auto_fill_text() {
    switch (mw.config.get('wgNamespaceNumber')) {
        case 102: //Author
            preloadAuthorTemplate();
    }
}

if (mw.config.get('wgAction') == "edit")
   $(document).ready(auto_fill_text);