Help mee! Maak een account of meld je aan.
Stem nu opnieuw voor: de FINALE! van de Gouden WikiKids Award 2018

MediaWiki:Qui.js

Uit Wikikids
Ga naar: navigatie, zoeken
/* <source lang="javascript">
Please keep the following lines intact
Userscript: [[User:TheDJ/Qui]]. Qui is a script that helps you to switch your 
Wikipedia online status and allows you to easily view the online status of your
WikiFriends. You can install it by adding "importScript( 'User:TheDJ/qui.js );" to
your [[Special:MyPage/monobook.js]]. 
    Written by: [[User:TheDJ]] on en.wikipedia
    Editted by: [[User:Sumurai8]] to make it work on WikiKids.
    Simple Version, dutch translation by: [[User:Apoo]].

<nowiki> */

// Local variables
var statuspage = "/Status";
var friendspage = "/MediaWiki:Qui/Friends";
var watcherspage = "/QuiWatchers";
var linkprefix = wgServer+"/User:";
var statusCookieName = "wikikids.qui.status";
var quiCookieRedirect = "wikikids.qui.redirectto";
var encodedUserName = encodeURIComponent(wgUserName);
var lastseenQueryString = "/api.php?action=query&format=json&list=usercontribs&uclimit=1&ucprop=timestamp&ucuser=";
var qui_var = []

var qui_system = new Object();
qui_system['online']  = [ "Online", "http://upload.wikimedia.org/wikipedia/commons/thumb/a/ab/Green_pog.svg/15px-Green_pog.svg.png" ];
qui_system['afwezig'] = [ "Afwezig", "http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Orange_pog.svg/15px-Orange_pog.svg.png" ];
qui_system['school']  = [ "School", "http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Blue_pog.svg/15px-Blue_pog.svg.png" ];
qui_system['offline'] = [ "Offline", "http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Red_pog.svg/15px-Red_pog.svg.png" ];
qui_system['vakantie'] = [ "Vakantie", "http://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Purple_pog.svg/15px-Purple_pog.svg.png" ];
qui_system['unknown'] = [ "Onbekend", "http://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 importStylesheetURI("http://wikikids.wiki.kennisnet.nl/User%3ASumurai8%2FQui.css?action=raw&ctype=text/​css");

    var current_status = qui_getCookie( statusCookieName ) || "unknown";
    // Add the change status menu
    if( current_status == "unknown" )
        qui_downloadStatus();
    
    if( typeof( qui_system[current_status]) == "undefined" ) {
        qui_deleteCookie( quiCookieRedirect );
        jsMsg( "<a href'"+wgServer +wgScript + "WP:Qui'>Qui</a> verkeerde status ingevuld! \nKies opnieuw een status uit het lijstje <a href='"+wgServer +wgScript + "Special:MyPage/Status'>Status page</a>." );
        current_status = "unknown";
    }
    qui_addMenu( current_status );
    
    //Are we here to auto-edit the status?
    if ( (wgTitle == wgUserName+statuspage || wgTitle == friendspage) && wgAction == "view" ) {
        var new_location = qui_getCookie( quiCookieRedirect );
        qui_deleteCookie( quiCookieRedirect );
        if( new_location ) {
            document.location.href = wgServer+wgArticlePath.replace( '$1', new_location );
        }
    } else if( wgTitle == wgUserName+statuspage ) {
        if( 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 = wgUserName +' is nu ' + qui_system[new_status][0].toLowerCase() +'.';
            
            qui_setCookie( statusCookieName, new_status, 24, "/", false, false );
            //Modify the form
            document.getElementById('wpTextbox1').value = new_status;
            document.getElementById('wpSummary').value = qui_cmt;
            document.getElementById('wpMinoredit').checked = true;

            // Submit it!
            document.getElementById('editform').submit();
        }
    } else if( wgTitle == friendspage ) {
        var currentlist = document.getElementById('wpTextbox1').value;

        if( wgAction == "edit" && location.href.indexOf("action=edit&addfriend=") != -1) {
            //Get new friend
            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 = "[[User:"+new_friend+"|"+new_friend+"]] toegevoegd aan vriendenlijst";

            if( currentlist.match( userexp ) ) {
                alert( "Deze gebruiker zit al in je vriendenlijst.");
                return;
            }
            //Modify the form
            document.getElementById('wpTextbox1').value += "[[User:"+new_friend+watcherspage+"|"+new_friend+"]]\n";
            document.getElementById('wpSummary').value = qui_cmt;
            // Submit it!
            document.getElementById('editform').submit();
        } else if ( wgAction == "edit" && location.href.indexOf("action=edit&delfriend=") != -1) {
            //Get new friend
            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 = "[[User:"+del_friend+"|"+del_friend+"]] verwijdert uit vriendenlijst";
            
            currentlist = currentlist.replace( userexp, "" );
           
            //Modify the form
            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( wgNamespaceNumber == 2 || wgNamespaceNumber == 3 ) {
        var subject_user = wgTitle;
        subject_user = subject_user.replace( RegExp( "\\/.*", "g"), "" );

        if( subject_user != wgUserName ) {
            qui_elements += '<li class="qui-menuelement" id="qui-add-friend" onClick="qui_addFriend(\''+ subject_user + '\');">' +
                'Voeg ' + subject_user + ' toe</li>';

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

    qui_elements += '<li class="qui-menuelement" id="qui-friends" onClick="qui_openFriendsMenu();">Vriendenlijst</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, wgPageName, 24, "/", false, false );
    document.location.href = linkprefix+encodedUserName+statuspage+"?smaxage=0&action=edit&newstatus="+ourstatus;
};

function qui_downloadStatus() {
    var a=sajax_init_object();
    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=sajax_init_object();
    b.open("GET", wgServer+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:([^\/]*)/;
            qui_var['numusers'] = array_of_users.length;
            qui_var['numuserspast'] = 0;
            qui_var['timearr'] = [];
            qui_var['statusarr'] = [];
            qui_var['localusers'] = [];
            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_var['localusers'][qui_var['localusers'].length] = local_username
                    qui_getFriendStatus( local_username );
                }
            }
        }
    };
    if( b.responseXML ) { window.console.log ("testing") }
    b.send(null);
};

function qui_getFriendStatus( friend ) {
    var c=sajax_init_object();
    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_var["statusarr"][qui_var["statusarr"].length] = local_status;
        qui_getFriendLastSeen( friend );
    };
    c.send(null);
};

function qui_getFriendLastSeen( friend ) {
    var d=sajax_init_object();
    d.open("GET", wgServer + wgScriptPath + lastseenQueryString + encodeURIComponent(friend), true);
    d.onreadystatechange = function() {
        if(d.readyState != 4) return;
        try {
            eval( "var queryResult="+ d.responseText );
            qui_var['numuserspast']++
        } catch (someError ) {
            alert( "Oh dear, our JSON query went down the drain?\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_var["timearr"][qui_var["timearr"].length] = queryResult.query.usercontribs[0].timestamp;
        }
        if( qui_var['numusers'] == qui_var['numuserspast']) {
            qui_addFriendsToMenu( );
        }
    };
    d.send(null);
};

function qui_addFriendsToMenu( ) {
    var menu = document.getElementById("qui-menu");
    trailing_menuitem = document.createElement( "li" );
    trailing_menuitem.className = "qui-menuelement";
    trailing_menuitem.id = "qui-friends2";
    menu.appendChild( trailing_menuitem );

    qui_var['timearr'] = qui_var['timearr'].sort().reverse()
    qui_var['statusarr'] = qui_var['statusarr'].sort()
    for (var qui_a=0; qui_a<qui_var['numusers']; qui_a++) {
//        temp = qui_var['statusarr'][qui_a]
        temp = qui_APIToJSDate(qui_var['timearr'][qui_a])
        qui_var['doNext'] = true;
        for (var qui_b=0; qui_b<qui_var['numusers']; qui_b++) {
//            if ( buddy_list[qui_var['localusers'][qui_b]]['status'] == temp && qui_var['doNext']) {
            if ( String(buddy_list[qui_var['localusers'][qui_b]]['lastseen']) == String(temp) && qui_var['doNext']) {
                friend = qui_var['localusers'][qui_b]
                var friend_status = buddy_list[friend]["status"];
                var friend_lastseen = buddy_list[friend]["lastseen"];
                buddy_list[qui_var['localusers'][qui_b]]['status'] = "---"
                buddy_list[friend]['lastseen'] = "---"

                if( friend_lastseen )
                    var friend_lastseen_string = " (" + qui_lastseenString(friend_lastseen) + ")";
                else var friend_lastseen_string = "";
            
                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 
                    + ' is currently ' + qui_system[friend_status][0] + '">' 
                    + friend + '</a> (<a class="qui-friend-talklink" href="' + wgServer + wgScript + '/User%20talk:' + encodeURIComponent(friend)
                    + '" title="Overlegpagina">' 
                    + 'O</a>) (<a class="qui-friend-dellink" href="javascript:qui_delFriend(\'' + friend + '\');" title="Verwijder deze QuiFriend">' 
                    + 'V</a>)' + friend_lastseen_string;
                menu.appendChild( menu_item );
                buddy_list[friend]["HTMLobj"] = menu_item;
                qui_var['doNext'] = false
            }
        }            
    }

    document.getElementById( "qui-friends" ).style.display = "none"
//Disabled on request
//    document.getElementById( "qui-friends" ).onclick = ""
//Make it useless ever after
//    document.getElementById( "qui-friends" ).innerText = ""
//    document.getElementById( "qui-friends" ).style['height'] = "1px"
//    document.getElementById( "qui-friends" ).style['list-style-image'] = "url(' ')"
};

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

function qui_delFriend( oldfriend ) {
    qui_setCookie( quiCookieRedirect, wgPageName, 24, "/", false, false );
    if (window.confirm("Weet je zeker dat je "+oldfriend+" wilt verwijderen? Dit heeft effect op iedereen!")) {
        document.location.href = wgServer+friendspage+"?smaxage=0&action=edit&delfriend="+encodeURIComponent(oldfriend);
    }
};

function qui_openWatchList() {
    document.location.href = wgServer + wgScript + "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;
        currentDate = currentDate - ahour
    var aminuteAgo = currentDate - aminute;
    var ahourAgo = currentDate - ahour;
    var adayAgo = currentDate - aday;
    var amonthAgo = currentDate - amonth;
    var ayearAgo = currentDate - ayear;
    
    if( lastseentime < ayearAgo )
        return ""+Math.round((ayearAgo - lastseentime) / ayear)+"jr";
    else if( lastseentime < amonthAgo )
        return ""+Math.round((amonthAgo - lastseentime) / amonth)+"ma";
    else if( lastseentime < adayAgo )
        return ""+Math.round((adayAgo - lastseentime) / aday)+"dg";
    else if( lastseentime < ahourAgo )
        return ""+Math.round((ahourAgo - lastseentime) / ahour)+"u";
    else if( lastseentime < aminuteAgo )
        return ""+Math.round((aminuteAgo - lastseentime) / aminute)+"min";
    else return "&lt;1min";
};

// 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" && wgUserName != "TheDJ" ) 
  jsMsg( "The script User:TheDJ/qui.js is currently not yet compatible with Internet Explorer and therefore disabled." );
else */
  addOnloadHook( qui_init );

/* </nowiki></source> */
Afkomstig van Wikikids , de interactieve Nederlandstalige Internet-encyclopedie voor en door kinderen. "https://wikikids.nl/index.php?title=MediaWiki:Qui.js&oldid=182798"