MediaWiki:Common.js

From Guild Wars Wiki
Jump to navigationJump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/** Legacy support for old user JS - don't use this in site wide files. **/
function importScript (page){
    mw.loader.load('/index.php?action=raw&ctype=text/javascript&title=' + encodeURIComponent(page));
}
function importStylesheet (page){
    mw.loader.load('/index.php?action=raw&ctype=text/css&title=' + encodeURIComponent(page), 'text/css');
}

/** Additional scripts **/
if ( mw.config.get('wgIsArticle') || window.location.href.indexOf( 'action=submit' ) > -1 || mw.config.get('wgNamespaceNumber') == -1 )
{
  mw.loader.load( '/index.php?title=MediaWiki:CollapsibleTables.js&action=raw&ctype=text/javascript' );

  jQuery( function( $ )
  {
    // Feedback namespace, user related additions
    if ( ( mw.config.get('wgNamespaceNumber') == 202 || mw.config.get('wgNamespaceNumber') == 203 ) )
    {
      var regExp = /^Feedback(?:_talk)?:User\/([^\/]+)(\/.*?)?$/;
      if ( ( obj = document.getElementById( 'catlinks' ) ) && obj.innerHTML.match( 'Category:Staff feedback pages' ) )
        regExp = /^Feedback_talk:([^\/]+)(\/.*?)?$/;
      
      if ( ( match = mw.config.get('wgPageName').match( regExp ) ) && ( obj = document.getElementById( 'p-tb' ) ) && ( obj = obj.getElementsByTagName( 'ul' )[0] ) )
      {
        match[1] = encodeURIComponent( match[1] );
        obj.innerHTML = obj.innerHTML.replace( /^([\s\S]*?<li id="t-recentchangeslinked".*?\/li>)([\s\S]+)$/i, '$1<li id="t-contributions"><a title="View the list of contributions of this user" href="/wiki/Special:Contributions/' + match[1] + '">User contributions</a></li>\n<li id="t-log"><a href="/index.php?title=Special:Log&amp;user=' + match[1] + '">Logs</a></li>\n<li id="t-emailuser"><a title="Send an e-mail to this user" href="/wiki/Special:EmailUser/' + match[1] + '">E-mail this user</a></li>\n$2' );
      }
      delete obj, regExp, match;
    }
  } );
}

/*
 * Extension for the deletion drop down list
 */
if (mw.config.get('wgAction') == 'delete')
{
  jQuery( function( $ )
  {
    if ( ( delReasonBtn = document.getElementById( 'wpConfirmB' ) ) )
    {
      var delReasonList        = document.getElementById( 'wpDeleteReasonList' );
      var delLink              = document.createElement( 'a' );
      delLink.href             = 'javascript:void(0);'
      delLink.title            = document.getElementById( 'wpReason' ).value;
      delLink.style.fontSize   = '0.9em';
      delLink.style.marginLeft = '1em';
      delLink.onclick          = function()
      {
        document.getElementById( 'wpReason' ).value = this.title;
      }
      delReasonList.onchange   = function ()
      {
        document.getElementById( 'wpReason' ).value = '';
        this.onchange = null;
      }
      delLink.appendChild( document.createTextNode( 'restore default reason' ) );
      delReasonBtn.parentNode.appendChild( delLink );
      delete delLink, delReasonList, delReasonBtn;
    }
  } );
}

/*
 * Image upload form helper
 */
if ( mw.config.get('wgPageName') == 'Special:Upload' && document.getElementById( 'mw-upload-form' ) !== 'undefined' )
{
  mw.loader.load( '/index.php?title=MediaWiki:UploadForm.js&action=raw&ctype=text/javascript' );
}

/*
 * Display protection log information for users who cannot edit protected pages
 */
function anonymousQueryProtectionLog () {
    if ( mw.config.get('wgAction') === 'edit' && document.getElementsByClassName('permissions-errors')[0] != null ) {
        // Helper function to display times and dates correctly
        function padzero (s) {  return (s < 10 ? '0' : '') + s; }

        // Query the wiki API to fetch the protection log details
        var qstr = '/api.php?action=query&format=json&list=logevents&letype=protect&letitle='+encodeURIComponent(mw.config.get('wgPageName'))+'&lelimit=1i&leprop=title|user|timestamp|parsedcomment|details';
        $.getJSON(qstr)
        .done(function(querydata){
            var data = querydata.query.logevents[0];

            // Pages protected prior to 2015 don't return a timestamp or user.
            // Give up because there isn't any useful data available.
            if (!('timestamp' in data)) {
                console.log('Page was protected prior to 2015.');
                return;
            }
            var comment = ''; if (data.parsedcomment !== '') { comment = '<span class="comment">('+data.parsedcomment+')</span>'; }
            var details = data.params[0], ptype = 'semi-protected', pexplain = 'registered users';
            if (details.match(/^[edit=sysop]/i)) { ptype = 'protected';  pexplain = 'users with administrator privileges'; }

            // Convert the given mediawiki timestamp string 'YYYY-MM-DDThh-mm-ssZ' into something we can use
            var timestamp = data.timestamp;
            var date = new Date(timestamp.substr(0,4), timestamp.substr(5,2), timestamp.substr(8,2), timestamp.substr(11,2), timestamp.substr(14,2), timestamp.substr(17,2));
            var datestring = padzero(date.getUTCHours()) + ":" + padzero(date.getUTCMinutes()) + ", " + padzero(date.getUTCDate()) + " " + mw.config.get('wgMonthNames')[date.getUTCMonth()] + " " + date.getUTCFullYear();

            // Generate a box identical the default mediawiki protection log message for logged in users
            var boxString = '<div class="mw-warning-with-logexcerpt mw-content-ltr" dir="ltr" lang="en">'
                            +'<p>'
                             +'<b>Warning:</b> This page has been <b><a href="/wiki/Special:ProtectedPages" title="Special:ProtectedPages">'+ptype+'</a></b>, so that only '+pexplain+' can edit it.\n'
                            +'</p>'
                            +'<ul>\n'
                             +'<li class="mw-logline-protect">'+datestring+' <a href="/wiki/User:'+encodeURIComponent(data.user)+'" title="User:'+data.user+'" class="mw-userlink">'+data.user+'</a> <span class="mw-usertoollinks">(<a href="/wiki/User_talk:'+encodeURIComponent(data.user)+'" title="User talk:'+data.user+'">Talk</a> | <a href="/wiki/Special:Contributions/'+encodeURIComponent(data.user)+'" title="Special:Contributions/'+data.user+'">contribs</a>)</span> protected "<a href="/wiki/'+encodeURIComponent(data.title)+'" title="'+data.title+'">'+data.title+'</a>" '+details+' '+comment+' <span class="mw-logevent-actionlink">(<a href="/index.php?title='+encodeURIComponent(data.title)+'&action=history" title="'+data.title+'">hist</a>)</span> </li>\n'
                            +'</ul>\n'
                            +'<a href="/index.php?title=Special:Log&page='+encodeURIComponent(data.title)+'&type=protect" title="Special:Log">View full log</a>'
                           +'</div>';
            $(boxString).fadeIn(1000).prependTo('#mw-content-text');
        })
        .fail(function(e){
           console.log(e);
        });
    }
}
anonymousQueryProtectionLog();

/**
 * Convert UTC time to local time. (see [[Template:UTC time]])
 */
function autoConvertUTC () {
    function pad (s) {  return (s < 10 ? '0' : '') + s; }
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    $('.utc-auto-convert').each(function(i,v){
        // Get UTC time using MediaWiki {{#time: U}} epoch format
        var utcseconds = v.getAttribute('data-time');
        if (utcseconds == 'error') {
            return;
        }
        var d = new Date(0);
        d.setUTCSeconds(utcseconds);
        var offset = (-1 * d.getTimezoneOffset() / 60);
        var offsetstring = '';
        if (offset > 0) { offsetstring = '+' + offset; }
        if (offset < 0) { offsetstring = offset; }
        
        // Default to showing the time only
        var datestring = pad(d.getHours()) + ':' + pad(d.getMinutes()) + ' UTC' + offsetstring;
        var titlestring = pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ' UTC';
        
        // But check for different formatting in case there is a day of the week given inside the span
        if (!v.textContent.match(/^\d/)) {
            datestring  = days[d.getDay()] + ' ' + datestring;
            titlestring = days[d.getUTCDay()] + ' ' + titlestring;
        }
        
        // Show result
        $(v).html('<span style="cursor:help; border-bottom:1px dotted silver;" title="'+titlestring+'">'+datestring+'</span>');
    });
}
autoConvertUTC();