MediaWiki:Catwatch.js

Da Wikinotizie, le notizie a contenuto aperto

Nota: dopo aver pubblicato, potrebbe essere necessario pulire la cache del proprio browser per vedere i cambiamenti.

  • Firefox / Safari: tieni premuto il tasto delle maiuscole Shift e fai clic su Ricarica, oppure premi Ctrl-F5 o Ctrl-R (⌘-R su Mac)
  • Google Chrome: premi Ctrl-Shift-R (⌘-Shift-R su un Mac)
  • Internet Explorer / Edge: tieni premuto il tasto Ctrl e fai clic su Aggiorna, oppure premi Ctrl-F5
  • Opera: premi Ctrl-F5.
/*
Il "Controllo categorie" (grazie a [[w:en:User:ais523]] che per primo ha avuto l'idea) aggiunge elementi alla watchlist se una pagina viene aggiunta ad una categoria (ed e' ancora presente al momento del controllo). Questo evento apparira' solo se un'altra pagina della watchlist e' stata modificata quel giorno (se l'aggiunta e' l'unica cosa successa non apparira').<br/>
La ricategorizzazione di una pagina  appartenente ad una categoria osservata verra' segnalata anche se la modifica riguardava un'altra categoria (a meno che  quella osservata venga cancellata).<br/>
I cancellamenti dalla categoria controllata non verranno visualizzati.<br/>
L'ora delle modifiche si riferisce a quella dei server, potrebbe essere differente da quella locale.<br/>

Per ogni pagina aggiunta verranno mostrati i seguenti link:
 * Alla relativa categoria
 * Alla pagina aggiunta
 * All'ultima modifica della pagina
 * Alla cronologia della pagina
 */

/*
 * 1 agosto 2012
 * reso indipendente da: progetto, lingua di interfaccia, preferenza formato date
 *
 * derivato da "//it.wikipedia.org/wiki/Wikipedia:Monobook.js/Catwatch.js"
 * link oldid "//it.wikipedia.org/wiki/?oldid=44876411"
 * ---
 * conseguentemente, la licenza è CC-BY-SA
 *
 **/

// start of auto-executing function which contains all code
mw.loader.using( [ 'mediawiki.user' , 'mediawiki.util' ] ).then( function z_all_code() {

    if ( mw.config.get( 'wgCanonicalSpecialPageName' ) !== 'Watchlist' ) {
        // serve solo in Special:Watchlist
        return;
    }

    var
    server = mw.config.get( 'wgServer' ),
    apiLink = server + mw.util.wikiScript( 'api' ),
    indexLink = server + mw.util.wikiScript( 'index' ),
    titleLink = indexLink + '?title=',
    wikiLink = server + mw.util.getUrl( '' ),
    monthNames = ["","gennaio","febbraio","marzo","aprile","maggio","giugno","luglio","agosto","settembre","ottobre","novembre","dicembre"],
    shortMonthNames = ["","gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic"];

    function cwOntoWatchlist( responseText, catName )
    {
        var
        i, temp, temp2,
        pages, times, h4Elements;

        function areSameDate( textDate, ISOdateTime ) {
            // ISOdate : 2012-08-01T18:50:12Z
            // textDate :
            //    dmy : 1 ago 2012
            //    ymd : 2012 ago 1
            //    mdy : ago 1, 2012
            //    ISO 8601 : 2012-08-01

            function ISOdateFromText() {

                function day() {

                    var tempDay;

                    switch ( dateFormat ) {
                        case 'dmy':
                            tempDay = textDate.split( ' ' )[0];
                            break;
                        case 'ymd':
                            tempDay = textDate.split( ' ' )[2];
                            break;
                        case 'mdy':
                            tempDay = textDate.split( /,? / )[1];
                            break;
                    }

                    return ( '0' + tempDay ).substr( -2 );

                }

                function month() {

                    var tempMonth, monthNum;

                    switch ( dateFormat ) {
                        case 'dmy':
                        case 'ymd':
                            tempMonth = textDate.split( ' ' )[1];
                            break;
                        case 'mdy':
                            tempMonth = textDate.split( /,? / )[0];
                            break;
                    }

                    monthNum = shortMonthNames.indexOf( tempMonth );
                    if ( monthNum == -1 ) {
                        monthNum = monthNames.indexOf( tempMonth );
                    }

                    return ( '0' + monthNum ).substr( -2 );

                }

                function year() {

                    switch ( dateFormat ) {
                        case 'dmy':
                            return textDate.split( ' ' )[2];
                        case 'ymd':
                            return textDate.split( ' ' )[0];
                        case 'mdy':
                            return textDate.split( /,? / )[2];
                    }

                }

                return year() + '-' + month() + '-' + day();

            }

            var
            dateFormat = mw.user.options.get( 'date' ),
            ISOdate = ISOdateTime.substr( 0, 10 );

            if ( dateFormat == 'default' ) {
                dateFormat = 'dmy';
            }

            if ( dateFormat == 'ISO 8601' ) {
                return ISOdate == textDate;
            } else {
                return ISOdate == ISOdateFromText();
            }

        }

        if( responseText.indexOf("<categorymembers/>") != -1 ) return; //cat is empty, nothing to do here
        if( responseText.indexOf('title="') == -1 ) return; // this error happens sometimes, just do nothing here

        pages = responseText.split('title="');
        times = responseText.split('timestamp="');

        h4Elements = document.getElementsByTagName("h4"); //get dates in the watchlist

        // skip first element, it's unnecessary
        for (var cicla=1; cicla<pages.length; cicla++)
        {
            pages[cicla] = pages[cicla].split('" timestamp=')[0];
            times[cicla] = times[cicla].split('" />')[0];

            // 2008-08-25
            times[cicla] = new String(times[cicla]);

            i = h4Elements.length;
            while(i--)
            {
                if ( areSameDate( h4Elements[i].innerHTML, times[cicla] ) )
                {
                    temp = h4Elements[i].nextSibling.firstChild;
                    if(temp == null) temp = h4Elements[i].nextSibling.nextSibling.firstChild;
                    while(temp != null)
                    {
                        if( temp.tagName != null  &&  temp.tagName.toLowerCase() === "li" ) {
                            temp2 = temp.innerHTML.match( /<span class="mw-changeslist-date">(\d\d):(\d\d)|; (\d\d):(\d\d)(:\d\d)? \. \./ );
                            if ( temp2 == null ) {
                                temp2 = temp;
                                break;
                            } else {
                                if ( temp2[1] !== undefined ) {                                   
                                    temp2 = new Number( temp2[1] ) * 100 + new Number( temp2[2] );
                                }
                                else {
                                    temp2 = new Number( temp2[3] ) * 100 + new Number( temp2[4] );
                                }
                                diag+=temp2+",";
                                if( temp2 < new Number( times[cicla].substr(11,2) + times[cicla].substr(14,2) ) ) {
                                    temp2 = temp;
                                    break;
                                }
                            }
                        }
                        temp2 = temp;
                        temp = temp.nextSibling;
                        if(temp == null) break;
                    }
                    temp = document.createElement("li");
                    if(temp2 == null) {
                        return;
                    }
                    if(h4Elements[i].nextSibling.firstChild != null) // IE-like whitespace handling
                        h4Elements[i].nextSibling.insertBefore(temp,temp2);
                    else // Firefox-like whitespace handling
                        h4Elements[i].nextSibling.nextSibling.insertBefore(temp,temp2);

                    temp.innerHTML =
                    '<span style="font-weight:bold;">'
                    + "(diff) (<a href='" + titleLink
                    + encodeURI( pages[cicla] )
                    + "&action=history'>cron</a>) . . <a "
                    + "href='" + wikiLink + "Category:"
                    + encodeURI( catName )
                    + "'>Categoria:" + catName + "</a>; " + times[cicla].substr(11,2) + ":" + times[cicla].substr(14,2)
                    + " . . (+ <a "
                    + "href='" + wikiLink
                    + encodeURI( pages[cicla] ) + "'>" + pages[cicla] + "</a> "
                    + "(<a href='" + titleLink + encodeURI( pages[cicla] )
                    + "&diff=last'>last</a>))</span>";
                }
            }
        }
    }

    function ajaxGet( $ ) {

        $.ajax({
            url: mw.util.wikiScript("index"),
            data: ({
                title  : "User:" + mw.config.get('wgUserName') + "/CategorieOsservate.js",
                action : 'raw',
                ctype  : 'text/javascript'
            }),
            cache: false,
            success: function(data){
                try {
                    eval(data);
                }
                catch(e) {
                    alert( "La sintassi della pagina Utente:" + mw.config.get('wgUserName') + "/CategorieOsservate.js è errata." );
                    return;
                }

                if( typeof CategorieOsservate == 'undefined' )
                {
                    if( confirm( "Ancora non hai una lista di categorie da controllare. Vuoi crearne una?" ) ) {
                        location.href =
                        titleLink + 'User:' + mw.config.get('wgUserName')
                        + '/CategorieOsservate.js&action=edit'
                        + '&preload=MediaWiki:Catwatch.js/PreloadCategorieOsservate.js';
                    }
                }
                else
                {
                    $.each(CategorieOsservate, function(i, cat){
                        $.ajax({
                            url: mw.util.wikiScript("api"),
                            data: ({
                                action : "query",
                                list : 'categorymembers',
                                cmtitle : 'Category:' + cat,
                                cmlimit : '100',
                                cmprop : "title|timestamp",
                                cmsort : "timestamp",
                                cmdir : "desc",
                                format : "xml"
                            }),
                            dataType: "text",
                            success: function(data){
                                cwOntoWatchlist(data, cat);
                            }
                        });
                    });
                }
            }
        });

    }

    if ( document.readyState === 'loading' ) {
        jQuery(document).ready( function($) {
            ajaxGet( $ );
        } );
    } else {
        ajaxGet( jQuery );
    }

} );
// end of the auto-executing function which contains all code