Aller au contenu

Utilisateur:Grind24/qui.js

Une page de Wikipédia, l'encyclopédie libre.
Note : après avoir enregistré la page, vous devrez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

Mozilla / Firefox / Konqueror / Safari : maintenez la touche Majuscule (Shift) en cliquant sur le bouton Actualiser (Reload) ou pressez Maj-Ctrl-R (Cmd-R sur Apple Mac) ;

Firefox (sur GNU/Linux) / Chrome / Internet Explorer / Opera : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5.
/* <source lang="javascript">
Veillez laisser ces lignes intactes
Userscript: [[Utilisateur:Grind24/Qui]]. Qui est un script qui permet de changer rapidement votre statuts sur wikipédia et vous autorise à facilement retrouver le statuts de vos amis wikipédiens. Vous pouvez l'installer en ajoutant "importScript( 'User:Grind24/qui.js );" dans votre [[Special:MyPage/monobook.js]]. 
    coded by [[User:Grind24]] j

<nowiki> */

// Variables 
var statuspage = "/Statuts";
var friendspage = "/MesamisQui";
var watcherspage = "/InscritQui";
var linkprefix = mw.config.get('wgServer')+mw.config.get('wgScript')+"?title=User:";
var statusCookieName = "wikipedia.qui.status";
var quiCookieRedirect = "wikipedia.qui.redirectto";
var encodedUserName = encodeURIComponent(mw.config.get('wgUserName'));
var lastseenQueryString = "/api.php?action=query&format=json&list=usercontribs&uclimit=1&ucprop=timestamp&ucuser=";

var qui_system = new Object();
qui_system['online']  = [ "En ligne",   "//upload.wikimedia.org/wikipedia/commons/thumb/a/ab/Green_pog.svg/15px-Green_pog.svg.png" ];
qui_system['around']  = [ "Invisible",   "//upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Purple_pog.svg/15px-Purple_pog.svg.png" ];
qui_system['busy']    = [ "Occuper",     "//upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Blue_pog.svg/15px-Blue_pog.svg.png" ];
qui_system['sleep']   = [ "Au lit", "//upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Red_pog.svg/15px-Red_pog.svg.png" ];
qui_system['offline'] = [ "Hors ligne",  "//upload.wikimedia.org/wikipedia/commons/thumb/4/46/Black_pog.svg/15px-Black_pog.svg.png" ];
qui_system['unknown'] = [ "Inconnu",  "//upload.wikimedia.org/wikipedia/commons/thumb/1/1a/White_pog.svg/15px-White_pog.svg.png" ];

function qui_init() {
    // Import the CSS elements
    if( typeof( quivar_custom_stylesheet ) != "undefined" )
        importStylesheet( quivar_custom_stylesheet );
    else importStylesheet( "User:Grind24/qui.css");

    var current_status = qui_getCookie( statusCookieName ) || "unknown";
    // Ajoute le menu
    if( current_status == "unknown" )
        qui_downloadStatus();
    
    if( typeof( qui_system[current_status]) == "undefined" ) {
        qui_deleteCookie( quiCookieRedirect );
        mw.notify( $("<a href'"+mw.config.get('wgServer') +mw.config.get('wgScript') + "?title=WP:Qui'>Qui</a> a rencontré un statut inconnu.\nVeillez rafraichir votre <a href='"+mw.config.get('wgScript') + "?title=Special:MyPage/Status'>statuts</a>.") );
        current_status = "unknown";
    }
    qui_addMenu( current_status );
    
    //Somme nous ici pour modifier notre statuts?
    if ( (mw.config.get('wgTitle') == mw.config.get('wgUserName')+statuspage || mw.config.get('wgTitle') == mw.config.get('wgUserName')+friendspage) && mw.config.get('wgAction') == "view" ) {
        var new_location = qui_getCookie( quiCookieRedirect );
        qui_deleteCookie( quiCookieRedirect );
        if( new_location ) {
            document.location.href = mw.config.get('wgArticlePath').replace( '$1', new_location );
        }
    } else if( mw.config.get('wgTitle') == mw.config.get('wgUserName')+statuspage ) {
        if( mw.config.get('wgAction') == "edit" && location.href.indexOf("&action=edit&newstatus=") != -1) {
            //Get new status
            var statusRegExp = /&action=edit&newstatus=(.*)/;
            var new_status = statusRegExp.exec( location.href )[1];
            var qui_cmt = mw.config.get('wgUserName') +' est maintenant ' + qui_system[new_status][0].toLowerCase() +'.';
            
            qui_setCookie( statusCookieName, new_status, 24, "/", false, false );
            //Modifie la forme
            document.getElementById('wpTextbox1').value = new_status;
            document.getElementById('wpSummary').value = qui_cmt;
            document.getElementById('wpMinoredit').checked = true;

            // Enregistrer!
            document.getElementById('editform').submit();
        }
    } else if( mw.config.get('wgTitle') == mw.config.get('wgUserName')+friendspage ) {
        var currentlist = document.getElementById('wpTextbox1').value;

        if( mw.config.get('wgAction') == "edit" && location.href.indexOf("&action=edit&addfriend=") != -1) {
            //Ajoutez des amis
            var statusRegExp = /&action=edit&addfriend=(.*)/;
            var new_friend = decodeURIComponent( statusRegExp.exec( location.href )[1] );
            var userexp = new RegExp("\\[\\[User:"+new_friend+watcherspage+".*[\r\n]*", "g" );
            var qui_cmt = "Ajouter [[User:"+new_friend+"|"+new_friend+"]] dans ma liste [[WP:Qui|Qui]] ";

            if( currentlist.match( userexp ) ) {
                alert( "Cet utilisateur semble être déjà présent sur votre liste.");
                return;
            }
            //Modifie la forme
            document.getElementById('wpTextbox1').value += "[[User:"+new_friend+watcherspage+"|"+new_friend+"]]\n";
            document.getElementById('wpSummary').value = qui_cmt;
            // Enregistrer!
            document.getElementById('editform').submit();
        } else if ( mw.config.get('wgAction') == "edit" && location.href.indexOf("&action=edit&delfriend=") != -1) {
            //Supprimer des amis
            var statusRegExp = /&action=edit&delfriend=(.*)/;
            var del_friend = decodeURIComponent( statusRegExp.exec( location.href )[1]);
            var userexp = new RegExp("\\[\\[User:"+del_friend+watcherspage+".*[\r\n]*", "g" );
            var qui_cmt = "Supprimer [[User:"+del_friend+"|"+del_friend+"]] de ma liste [[WP:Qui|Qui]]";
            
            currentlist = currentlist.replace( userexp, "" );
           
            //Modifie la forme
            document.getElementById('wpTextbox1').value = currentlist;
            document.getElementById('wpSummary').value = qui_cmt;
            document.getElementById('wpMinoredit').checked = true;
            // Submit it!
            document.getElementById('editform').submit();
        }
    } 
}

function qui_addMenu( current_status ) {
    if( navigator.userAgent.indexOf( "MSIE" ) != -1 )
        var body = document.getElementById( 'globalWrapper');
    else var body = document.getElementsByTagName( 'body')[0];
    var indicator = document.createElement( "div" );
    indicator.className = "qui-indicator noprint";
    indicator.id = "qui-indicator";

    var link = document.createElement( "a" );
    link.href = "javascript:qui_openMenu();";
    link.setAttribute( "title", qui_system[current_status][0] );
    var img = document.createElement( "img" );
    img.className = "qui-status-image";
    img.setAttribute( "src",  qui_system[current_status][1] );
    img.setAttribute( "alt", qui_system[current_status][0] );
    link.appendChild( img );
    indicator.appendChild( link );

    var qui_elements = "";
    for( var astatus in qui_system ) {
        if( astatus != "unknown" && typeof( qui_system[astatus] ) == 'object' && qui_system[astatus].length ) {
            qui_elements += '<li class="qui-menuelement qui-statusitem qui-' + astatus + '-icon" id="qui-' + astatus +
                '" onClick="qui_switchStatus(\'' + astatus + '\');">' + qui_system[astatus][0] + '</li>';
        }
    }

    if( mw.config.get('wgNamespaceNumber') == 2 || mw.config.get('wgNamespaceNumber') == 3 ) {
        var subject_user = mw.config.get('wgTitle');
        subject_user = subject_user.replace( RegExp( "\\/.*", "g"), "" );

        if( subject_user != mw.config.get('wgUserName') ) {
            qui_elements += '<li class="qui-menuelement" id="qui-add-friend" onClick="qui_addFriend(\''+ subject_user + '\');">' +
                'Ajouter ' + subject_user + '</li>';

            qui_elements += '<li class="qui-menuelement" id="qui-del-friend" onClick="qui_delFriend(\''+ subject_user + '\');">' +
                'Supprimer ' + subject_user + '</li>';
        }
    }

    qui_elements += '<li class="qui-menuelement" id="qui-watchlist" onClick="qui_openWatchList();">Qui est inscrit?</li>';
    qui_elements += '<li class="qui-menuelement" id="qui-friends" onClick="qui_openFriendsMenu();">Voir mes ami(e)s</li>';

    var menu = document.createElement( "ul" );
    menu.className = "qui-menu";
    menu.id = "qui-menu";
    menu.innerHTML = qui_elements;

    if (indicator.addEventListener) {
        indicator.addEventListener( "click", qui_openMenu, false);
        indicator.addEventListener( "mouseover", qui_openMenu, false);
        indicator.addEventListener( "mouseout", qui_closeMenu, false);
        menu.addEventListener( "mouseover", qui_openMenu, false);
        menu.addEventListener( "mouseout", qui_closeMenu, false);
    } else if (indicator.attachEvent) {
        indicator.attachEvent("onclick", qui_openMenu);
        indicator.attachEvent("onmouseover", qui_openMenu);
        menu.attachEvent("onmouseenter", qui_openMenu);
        menu.attachEvent("onmouseleave", qui_closeMenu);
    } else {
        indicator.onclick = qui_openMenu;
        indicator.onmouseover = qui_openMenu;
        indicator.onmouseout = qui_closeMenu;
        menu.onmouseover = qui_openMenu;
        menu.onmouseout = qui_closeMenu;
    }

    indicator.appendChild( menu );
    body.appendChild( indicator );
};

function qui_openMenu() {
    var menu = document.getElementById("qui-menu");
    menu.style.display = "block";
};

function qui_closeMenu() {
    var menu = document.getElementById("qui-menu");
    menu.style.display = "none";
};

function qui_switchStatus( ourstatus ) {
    qui_setCookie( quiCookieRedirect, mw.config.get('wgPageName'), 24, "/", false, false );
    document.location.href = linkprefix+encodedUserName+statuspage+"&smaxage=0&action=edit&newstatus="+ourstatus;
};

function qui_downloadStatus() {
    var a=new XMLHttpRequest();
    a.open("GET", linkprefix+encodedUserName+statuspage + "&smaxage=0&action=raw", true);
    a.onreadystatechange = function()
    {
        if(a.readyState != 4) return;
        var new_status = a.responseText ? a.responseText : "unknown";
        qui_setCookie( statusCookieName, new_status, 24, "/", false, false );
        qui_addMenu( new_status );
    };
    a.send(null);
};

var buddy_list = new Object();
// Array fmt: friend: [status, lastseen, HTMLobj]
    
function qui_openFriendsMenu() {
    var b=new XMLHttpRequest();
    b.open("GET", linkprefix+encodedUserName+friendspage + "&smaxage=0&action=raw", true);
    b.onreadystatechange = function()
    {
        if(b.readyState != 4) return;
        if( b.responseText ) {
            var array_of_users = b.responseText.split( /[\r\n]/ );
            var userexp = /\[\[User:([^\/]*)/;
            for( i=0 ; i < array_of_users.length; i++ ) {
                var local_username = userexp.exec(array_of_users[i])[1];
                if( local_username ) {
                    buddy_list[local_username] = {status: false, lastseen: false, HTMLobj: false };
                    qui_getFriendStatus( local_username );
                }
            }
        }
    };
    if( b.responseXML ) { window.console.log ("testing") }
    b.send(null);
};

function qui_getFriendStatus( friend ) {
    var c=new XMLHttpRequest();
    c.open("GET", linkprefix+encodeURIComponent(friend)+statuspage + "&smaxage=0&action=raw", true);
    c.onreadystatechange = function() {
        if(c.readyState != 4)
            return;
        var local_status = c.responseText || "unknown";
        if( typeof( qui_system[local_status] ) == "undefined" )
            local_status = "unknown";

        buddy_list[friend]["status"] = local_status;
        qui_getFriendLastSeen( friend );
    };
    c.send(null);
};

function qui_getFriendLastSeen( friend ) {
    var d=new XMLHttpRequest();
    d.open("GET", mw.config.get('wgServer') + mw.config.get('wgScriptPath') + lastseenQueryString + encodeURIComponent(friend), true);
    d.onreadystatechange = function() {
        if(d.readyState != 4) return;
        try {
            eval( "var queryResult="+ d.responseText );
        } catch (someError ) {
            alert( "Oh chère ..., JSON a rencontré un problème patienter? \n" + friend+ "\nError: " +someError );
        }
        if( queryResult.query.usercontribs[0] ) {
            var local_lastseen = qui_APIToJSDate(queryResult.query.usercontribs[0].timestamp);
            buddy_list[friend]["lastseen"] = local_lastseen;
        }
        qui_addFriendToMenu( friend );
    };
    d.send(null);
};

function qui_addFriendToMenu( friend ) {
    var friend_status = buddy_list[friend]["status"];
    var friend_lastseen = buddy_list[friend]["lastseen"];
    
    if( friend_lastseen )
        var friend_lastseen_string = " (" + qui_lastseenString(friend_lastseen) + ")";
    else var friend_lastseen_string = "";

    var menu = document.getElementById("qui-menu");
    var menu_item = document.createElement( "li" );
    menu_item.className = "qui-menuelement qui-friendsitem qui-" + friend_status + "-icon";
    menu_item.innerHTML = '<a class="qui-friend-link" href="' + linkprefix + encodeURIComponent(friend) + '" title="' + friend 
        + ' est maintenant ' + qui_system[friend_status][0] + '">' 
        + friend + '</a> (<a class="qui-friend-talklink" href="' + mw.config.get('wgServer') + mw.config.get('wgScript') + '?title=User%20talk:' + encodeURIComponent(friend)
        + '" title="Page de discussion">' 
        + 'Di</a>) (<a class="qui-friend-dellink" href="javascript:qui_delFriend(\'' + friend + '\');" title="Supprimer cet amis">' 
        + 'Sup</a>)' + friend_lastseen_string;
    menu.appendChild( menu_item );
    buddy_list[friend]["HTMLobj"] = menu_item;

    document.getElementById( "qui-friends" ).style.display = "none";
};

function qui_addFriend( newfriend ) {
    qui_setCookie( quiCookieRedirect, mw.config.get('wgPageName'), 24, "/", false, false );
    document.location.href = linkprefix+encodedUserName+friendspage+"&smaxage=0&action=edit&addfriend="+encodeURIComponent(newfriend?newfriend:mw.config.get('wgTitle'));
};

function qui_delFriend( oldfriend ) {
    qui_setCookie( quiCookieRedirect, mw.config.get('wgPageName'), 24, "/", false, false );
    document.location.href = linkprefix+encodedUserName+friendspage+"&smaxage=0&action=edit&delfriend="+encodeURIComponent(oldfriend);
};

function qui_openWatchList() {
    document.location.href = mw.config.get('wgServer') + mw.config.get('wgScript') + "?title=Special:Whatlinkshere/User:"+encodedUserName+watcherspage; 
};

function qui_lastseenString( our_lastseentime ) {
    var lastseentime = our_lastseentime.getTime();
    var currentDate = new Date().getTime();
    var aminute = 60000; var ahour = 60*aminute; var aday = 24*ahour; amonth = 30.5*aday; var ayear = 12*amonth;
    var aminuteAgo = currentDate - aminute*1.5;
    var ahourAgo = currentDate - ahour*1.5;
    var adayAgo = currentDate - aday*1.5;
    var amonthAgo = currentDate - amonth*1.5;
    var ayearAgo = currentDate - ayear*1.5;
    
    if( lastseentime < ayearAgo )
        return ""+Math.round((ayearAgo - lastseentime) / ayear)+"Ans";
    else if( lastseentime < amonthAgo )
        return ""+Math.round((amonthAgo - lastseentime) / amonth)+"Ms";
    else if( lastseentime < adayAgo )
        return ""+Math.round((adayAgo - lastseentime) / aday)+"Jr";
    else if( lastseentime < ahourAgo )
        return ""+Math.round((ahourAgo - lastseentime) / ahour)+"Hrs";
    else if( lastseentime < aminuteAgo )
        return ""+Math.round((aminuteAgo - lastseentime) / aminute)+"Min";
    else return "&lt;m";
};

// Cookie helpers, modified from en.wiktionary
function qui_setCookie(our_cookieName, our_cookieValue, our_hours, our_path, our_domain, our_secure) {
var expire = new Date();
var nHours = our_hours;
expire.setTime( expire.getTime() + (3600000 * nHours) );
document.cookie = our_cookieName + "=" + escape(our_cookieValue)
        + ((expire) ? "; expires=" + expire.toGMTString() : "" )
        + ((our_path) ? "; path=" + our_path : "" )
        + ((our_domain) ? "; domain=" + our_domain : "" )
        + ((our_secure) ? "; secure" : "" );
}

function qui_getCookie(cookieName) {
  var start = document.cookie.indexOf( cookieName + "=" );
  if ( start == -1 ) return "";
  var len = start + cookieName.length + 1;
  if ( ( !start ) &&
    ( cookieName != document.cookie.substring( 0, cookieName.length ) ) )
      {
        return "";
      }
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function qui_deleteCookie(cookieName) {
  var the_cookieValue = qui_getCookie(cookieName);
  if ( the_cookieValue ) {
    qui_setCookie( cookieName, "", -48, "/", false, false);
  }
}

function qui_APIToJSDate(api_date) {
    var hourpart = api_date.slice(api_date.indexOf('T')+1, api_date.indexOf('Z'));
    var hourparts = hourpart.split(":");
    var datepart = api_date.slice(0, api_date.indexOf('T'));
    var dateparts = datepart.split("-");
    var js_date = new Date( dateparts[0], dateparts[1]-1, dateparts[2], hourparts[0], hourparts[1], hourparts[2], 0);
    return js_date;
}

/* if( navigator.appName == "Microsoft Internet Explorer" && mw.config.get('wgUserName') != "Grind24" ) 
  jsMsg( "Le script "qui" n'est pas compatible avec Internet Explorer et sera donc désactiver." );
else */
  $( qui_init );

/* </nowiki></source> */