MediaWiki:AbuseLogRC.js

// ====================== //      AbuseLog in RC //  ====================== /* Originally created by "User:Suppa chuppa" on http://runescape.wikia.com/wiki/User:Suppa_chuppa/abuselog.js    Edited by User:leviathan_89 api documentation: /api.php?query=list example: /api.php?action=query&list=abuselog&afllimit=2 Adds a table on top of Special:RecentChanges showing the last triggered anti-abuse filters.

$(function {   //    // Configuration    //    // MediaWiki data    var data =  {        mw: mw.config.get([ 'wgCanonicalSpecialPageName', 'wgUserLanguage', 'wgUserName' ]),       ug: wgUserGroups.join(' ')    };    // Run condition    if ( typeof window.abuseLogRCactive !== 'undefined' || data.mw.wgCanonicalSpecialPageName != 'Recentchanges' ) {         return;    }    window.abuseLogRCactive = true;    // Configuration    var config = {            interval: null,            showTo: null,            entries: null,            order: null,            timeFrame1: null,            timeFrame2: null,            timeFrame3: null,            dateSep: null        };    var userType;    var customUser;    var abuseFilterOn;    // Checking user's custom settings    var abuseLogRC_showTo;      // in case it wasn't declared    var abuseLogRC_order;       // in case it wasn't declared    config.interval = ( typeof abuseLogRC_interval == 'number' ) ? Math.max(5, abuseLogRC_interval) : 60;    config.entries = ( typeof abuseLogRC_entries == 'number' ) ? Math.max(1, abuseLogRC_entries) : 3; config.showTo = ( abuseLogRC_showTo == 'all' ) ? 'all' : 'sysop'; config.order = ( abuseLogRC_order == 'newer' ) ? 'newer' : 'older'; config.dateSep = ( typeof abuseLogRC_dateSep == 'string' ) ? abuseLogRC_dateSep : '-'; config.timeFrame1 = ( typeof abuseLogRC_timeFrame1 == 'number' ) ? abuseLogRC_timeFrame1 * 3600000 : 2 * 3600000; config.timeFrame2 = ( typeof abuseLogRC_timeFrame2 == 'number' ) ? abuseLogRC_timeFrame2 * 3600000 : 12 * 3600000; config.timeFrame3 = ( typeof abuseLogRC_timeFrame3 == 'number' ) ? abuseLogRC_timeFrame3 * 3600000 : 24 * 3600000;

// END Configuration //   // i18n //   var lang = data.mw.wgUserLanguage; var splitLang = lang.split('-')[0]; var i18n = { // English en: { loading: 'Loading...', optionsHeader: 'Abuse Log Watch options', autoRefresh: 'Auto-refresh table', autoRefreshStuck: 'Click here if table gets stuck', lastUpdate: 'Last update:', time: 'Time', pageName: 'Page Name', user: 'User', triggeredFilter: 'Triggered abuse filter:', diffLink: 'diff', talkLink: 'talk', contribsLink: 'contribs', abuseLogLink: 'abuse log', blockLink: 'block', vstfLink: 'VSTF', vstfTooltip: 'Ask VSTF for help', apiError: 'API error:', ajaxError: 'AJAX error:' },           // Italian it: { loading: 'Caricamento...', optionsHeader: 'Opzioni monitoraggio registro Filtro Anti-Abuso', autoRefresh: 'Aggiorna automaticamente la tabella', autoRefreshStuck: 'Clicca qui se la tebella si blocca', lastUpdate: 'Ultimo aggiornamento:', time: 'Ora', pageName: 'Nome pagina', user: 'Utente', triggeredFilter: 'Fitro anti-abuso attivato:', diffLink: 'diff', talkLink: 'discussione', contribsLink: 'contributi', abuseLogLink: 'registro abusi', blockLink: 'blocca', vstfLink: 'VSTF', vstfTooltip: 'Chiedi aiuto al VSTF', apiError: 'Errore API:', ajaxError: 'Errore AJAX:' },           // Polish pl: { loading: 'Wczytywanie...', optionsHeader: 'Obserwowanie rejestru nadużyć', autoRefresh: 'Automatycznie odświeżaj tabelę', autoRefreshStuck: 'Kliknij tutaj, jeśli tabela się nie odświeża', lastUpdate: 'Ostatnia aktualizacja:', time: 'Czas', pageName: 'Nazwa strony', user: 'Użytkownik', triggeredFilter: 'Uruchomiony filtr:', diffLink: 'różn.', talkLink: 'dyskusja', contribsLink: 'wkład', abuseLogLink: 'rejestr nadużyć', blockLink: 'zablokuj', vstfLink: 'VSTF', vstfTooltip: 'Poproś VSTF o pomoc', apiError: 'Błąd API:', ajaxError: 'Błąd AJAX:' },   };

// Select language // Check if user's language is present if (typeof i18n[lang] === 'object') { $.extend( i18n, i18n.en, i18n[lang] ); } else { // Check to see if the parent language has a translation, example pt-br -> pt       if (typeof i18n[splitLang] === 'object') { $.extend( i18n, i18n.en, i18n[splitLang] ); } else { // Fallback to English $.extend( i18n, i18n.en ); }   }    // END i18n

//   // Choosing to create the table or not //   // Checking user rights if ( (data.ug.indexOf('sysop') + data.ug.indexOf('vstf') + data.ug.indexOf('staff') + data.ug.indexOf('helper') > -4) ) { userType = 'sysop'; } else { userType = 'all'; }   // Checking if user name matches custom users list if (typeof abuseLogRC_users == 'object') { customUser = (abuseLogRC_users.indexOf(data.mw.wgUserName) > -1) ? true : false; } else { customUser = false; }

// Check if AbuseFilter is enabled var AfQuery = { 'meta': 'siteinfo', 'siprop': 'extensions', 'action': 'query' };   callAPI(AfQuery, 'GET', function(response) {        var o = response.query.extensions;        var found = false;        var i;        if ($.isArray(o)) {            for ( i = 0; i < o.length && !found ; ++i ) {                found = o[i].name === 'Abuse Filter';            }        }        if (found) {            // Create table if everything checks out            if ( (config.showTo == userType || customUser) ) {                createTableHTML;            }        }    }); // END choosing //   // Functions //   // Variables var refreshTimer = null; var itemSince = null; var itemIds = [];

// URLs function articleURL(article) { return wgArticlePath.replace('$1', encodeURI(article.replace(/ /g, '_'))); }	function scriptURL(article) { return wgScript + '?title=' + encodeURIComponent(article.replace(/ /g, '_')); }   // Zero padding function addZero(n) { if (n < 10) { n = '0' + n;       } return n;   } // callAPI function callAPI(data, method, callback) { data['format'] = 'json'; $.ajax({			data: data,			dataType: 'json',			url: wgScriptPath + '/api.php',			type: method,			success: function(response) {				if (response.error) {                   $('#abErrorsLog ul').append('' + i18n.apiError + ' ' + response.error.info + '');				} else {					callback(response);				}			},			error: function(xhr, error) {                $('#abErrorsLog ul').append('' + i18n.ajaxError + ' ' + error + '');            },			timeout: 10000		}); }

// loadComplete function loadComplete { if ($('#abAutoRefresh:checked').length) { window.clearTimeout(refreshTimer); var refreshInterval = config.interval; refreshTimer = window.setTimeout(loadData, refreshInterval * 1000); }		$('#ab_update img').hide; $('#abLastUpdate').text((new Date).toLocaleTimeString); }	// refreshData function refreshData{ $('#abHeader').nextAll.remove;     // clears table rows $('#abErrorsLog ul').empty;          // clears errors log itemIds = []; itemSince = null; loadData; }	// Add urgency class function urgencyClass(timeNew, timeOld) { // Variables are UNIX times timeDifference = timeNew - timeOld; if (timeDifference <= config.timeFrame1) { return 'abUrgency1'; } else { if (timeDifference <= config.timeFrame2) { return 'abUrgency2'; } else { if (timeDifference <= config.timeFrame3) { return 'abUrgency3'; } else { return 'abUrgency4'; }           }        }	}

// loadData function loadData { $('#ab_update img').show; var itemQuery = { 'afllimit': config.entries, 'afldir': config.order, 'action': 'query', 'list': 'abuselog' };       // Select only new items if (itemSince) { itemQuery['itemend'] = itemSince; }       // Get data callAPI(itemQuery, 'GET', function(response) {			var revs = [];			var curDate = '';			for (var i in response.query.abuselog) {				var item = response.query.abuselog[i];				// Remove duplicates which may occur during autorefresh				if ($.inArray(item.id, itemIds) > -1) {					continue;				}               if(itemIds.length > config.entries - 1) {                    refreshData;                }				itemIds.push(item.id);

// Time var now = new Date; var then = new Date(item.timestamp); var date = { y: then.getFullYear, m: addZero(then.getMonth), d: addZero(then.getDay) };				var time = { h: addZero(then.getHours), m: addZero(then.getMinutes), s: addZero(then.getSeconds) };               // Set time limit for next requests itemSince = item.timestamp; $('#abHeader').after(                   '' +                        '' + date.y + config.dateSep + date.m + config.dateSep + date.d + ' ' + time.h + ':' + time.m + ':' + time.s +                         ' ' +                        '' +                            '' + item.title + '' + ' ' +                             '(' + i18n.diffLink + ')' +                        ' ' +                        '' +                             '' + item.user + '' +                         ' ' +                    ' ' + '' + '<a href="/wiki/Special:AbuseLog?title=Special%3AAbuseLog&wpSearchFilter=' + item.filter_id + '" target="_blank">' + i18n.triggeredFilter + '&nbsp' + item.filter_id + '</a>' + ' ' +                       '<td class="abItemTools">&raquo; ' + '<a href="' + articleURL('User_talk:' + item.user) + '" target="_blank">' + i18n.talkLink + '</a> &bull; ' + '<a href="' + articleURL('Special:Contributions/' + item.user) + '" target="_blank">' + i18n.contribsLink + '</a> &bull; ' + '<a href="/wiki/Special:AbuseLog?wpSearchUser=' + item.user + '" target="_blank">' + i18n.abuseLogLink + '</a> &bull; ' + '<a href="http://vstf.wikia.com/" target="_blank" title="' + i18n.vstfTooltip + '">' + i18n.vstfLink + '</a> &bull; ' + '<a href="' + articleURL('Special:Block/' + item.user) + '" target="_blank">' + i18n.blockLink + '</a>' + ' ' +                   ' '				);			}			if (revs.length === 0) {				loadComplete;				return;			}		}); }   // CreateHTML body function createTableHTML {

// Table container $('#mw-content-text').before(           '<div id="ab_options"> <div id="ab_main"> '        ); // Table options $('#ab_options').empty.append(           ' ' +                ' ' + i18n.optionsHeader + ' ' +                ' ' +                    '<input type="checkbox" id="abAutoRefresh" checked="checked" /> <label for="abAutoRefresh">' + i18n.autoRefresh + '   ' +                    '<input type="button" id="abRefresh" value="' + i18n.autoRefreshStuck + '">' +                    '<div id="ab_update" style="float:right;"><img src="http://images.wikia.com/common/skins/common/images/ajax.gif" width="16" height="16" alt="' + i18n.loading + '"/> ' + ' ' + i18n.lastUpdate + ' &nbsp  ' +                ' ' +                ' <ul></ul> ' +            ' '		); // Bind refresh function $('#abRefresh').click(refreshData);

// Main table var $table = $(' ').addClass('wikitable').attr('id', 'abData').css({'width':'100%', 'font-size':'14px'}); $table.append(           '<tr id="abHeader">' +                ' ' + i18n.time + ' ' +                ' ' + i18n.pageName + ' ' +                ' ' + i18n.user + ' ' +            ' '		); // Insert table in container $('#ab_main').empty.append($table);

// Get data loadData; }	// End functions });