User:Chaotic Enby/RecentUnblockHighlighter.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
This user script seems to have a documentation page at User:Chaotic Enby/RecentUnblockHighlighter. |
// <nowiki>
// Initialize the MediaWiki API
var ruhMediaWikiApi = new mw.Api();
async function getWikitextFromCache( title ) {
const api = new mw.ForeignApi( 'https://wiki.riteme.site/w/api.php' );
let wikitext = '';
await api.get( {
action: 'query',
prop: 'revisions',
titles: title,
rvslots: '*',
rvprop: 'content',
formatversion: '2',
uselang: 'content', // needed for caching
smaxage: '86400', // cache for 1 day
maxage: '86400' // cache for 1 day
} ).then( ( data ) => {
wikitext = data.query.pages[ 0 ].revisions[ 0 ].slots.main.content;
} );
return wikitext;
}
async function getUsernames() {
const dataString = await getWikitextFromCache( 'User:Chaotic_Enby/RecentUnblockHighlighter/data' );
return JSON.parse( dataString );
}
// Setting up global-ish variables
var trackingTime = 7776000000; // Exactly 90 days in millisections
class UserHighlighterSimple {
/**
* @param {jQuery} $ jquery
* @param {Object} mw mediawiki
* @param {Window} window
*/
constructor( $, mw, window ) {
// eslint-disable-next-line no-jquery/variable-pattern
this.$ = $;
this.mw = mw;
this.window = window;
}
async execute() {
const dataJSON = await getUsernames();
if ( !this.window.userHighlighterSimpleNoColors ) {
this.setHighlightColors();
}
const $links = this.$( '#article a, #bodyContent a, #mw_contentholder a' );
$links.each( async ( index, element ) => {
this.$link = this.$( element );
if ( !this.linksToAUser() ) {
return;
}
this.user = this.getUserName();
const isUserSubpage = this.user.includes( '/' );
if ( isUserSubpage ) {
return;
}
await this.addClassesAndHoverTextToLinkIfNeeded(this.$link, dataJSON);
} );
}
addCSS( htmlClass, cssDeclaration ) {
// .plainlinks is for Wikipedia Signpost articles
// To support additional custom signature edge cases, add to the selectors here.
this.mw.util.addCSS( `
.plainlinks .${ htmlClass }.external,
.${ htmlClass },
.${ htmlClass } b,
.${ htmlClass } big,
.${ htmlClass } font,
.${ htmlClass } kbd,
.${ htmlClass } small,
.${ htmlClass } span {
${ cssDeclaration }
}
` );
}
hasHref( url ) {
return Boolean( url );
}
isAnchor( url ) {
return url.charAt( 0 ) === '#';
}
isHttpOrHttps( url ) {
return url.startsWith( 'http://', 0 ) ||
url.startsWith( 'https://', 0 ) ||
url.startsWith( '/', 0 );
}
/**
* Figure out the wikipedia article title of the link
*
* @param {string} url
* @param {mw.Uri} urlHelper
* @return {string}
*/
getTitle( url, urlHelper ) {
// for links in the format /w/index.php?title=Blah
const titleParameterOfUrl = this.mw.util.getParamValue( 'title', url );
if ( titleParameterOfUrl ) {
return titleParameterOfUrl;
}
// for links in the format /wiki/PageName. Slice off the /wiki/ (first 6 characters)
if ( urlHelper.path.startsWith( '/wiki/' ) ) {
return decodeURIComponent( urlHelper.path.slice( 6 ) );
}
return '';
}
notInUserOrUserTalkNamespace() {
const namespace = this.titleHelper.getNamespaceId();
const notInSpecialUserOrUserTalkNamespace = this.$.inArray( namespace, [ 2, 3 ] ) === -1;
return notInSpecialUserOrUserTalkNamespace;
}
linksToAUser() {
let url = this.$link.attr( 'href' );
if ( !this.hasHref( url ) || this.isAnchor( url ) || !this.isHttpOrHttps( url ) ) {
return false;
}
url = this.addDomainIfMissing( url );
// mw.Uri(url) throws an error if it doesn't like the URL. An example of a URL it doesn't like is https://meta.wikimedia.org/wiki/Community_Wishlist_Survey_2022/Larger_suggestions#1%, which has a section link to a section titled 1% (one percent).
let urlHelper;
try {
urlHelper = new this.mw.Uri( url );
} catch {
return false;
}
// Skip links that aren't to user pages
const isUserPageLink = url.includes( '/w/index.php?title=User' ) || url.includes( '/wiki/User' );
if ( !isUserPageLink ) {
return false;
}
// Even if it is a link to a userpage, skip URLs that have any parameters except title=User, action=edit, and redlink=. We don't want links to diff pages, section editing pages, etc. to be highlighted.
const urlParameters = urlHelper.query;
delete urlParameters.title;
delete urlParameters.action;
delete urlParameters.redlink;
const hasNonUserpageParametersInUrl = !this.$.isEmptyObject( urlParameters );
if ( hasNonUserpageParametersInUrl ) {
return false;
}
const title = this.getTitle( url, urlHelper );
// Handle edge cases such as https://web.archive.org/web/20231105033559/https://wiki.riteme.site/wiki/User:SandyGeorgia/SampleIssue, which shows up as isUserPageLink = true but isn't really a user page.
try {
this.titleHelper = new this.mw.Title( title );
} catch {
return false;
}
if ( this.notInUserOrUserTalkNamespace() ) {
return false;
}
const isDiscussionToolsSectionLink = url.includes( '#' );
if ( isDiscussionToolsSectionLink ) {
return false;
}
return true;
}
// Brandon Frohbieter, CC BY-SA 4.0, https://stackoverflow.com/a/4009771/3480193
countInstances( string, word ) {
return string.split( word ).length - 1;
}
/**
* mw.Uri(url) expects a complete URL. If we get something like /wiki/User:Test, convert it to https://wiki.riteme.site/wiki/User:Test. Without this, UserHighlighterSimple doesn't work on metawiki.
*
* @param {string} url
* @return {string} url
*/
addDomainIfMissing( url ) {
if ( url.startsWith( '/' ) ) {
url = window.location.origin + url;
}
return url;
}
/**
* @return {string}
*/
getUserName() {
const user = this.titleHelper.getMain().replace( /_/g, ' ' );
return user;
}
async customUnblock( userName, dataJSON ) {
if(dataJSON.hasOwnProperty(userName) && dataJSON[userName].hasOwnProperty("expiry")) {
if(dataJSON[userName].expiry > Date.now()) {
if(dataJSON[userName].hasOwnProperty("comment")) {
return [true, dataJSON[userName].comment];
} else {
return [true, ""];
}
}
}
return [false, ""];
}
async recentUnblock( userName, dataJSON ) {
// Retrieve the logs of blocks directed to this specific user
var params = {
action: 'query',
format: 'json',
list: 'logevents',
letype: 'block',
letitle: 'User:' + userName
};
var blocks = await ruhMediaWikiApi.get( params );
if(blocks.query.logevents.length == 0) {
return [false, ""];
}
var mostRecentBlock = blocks.query.logevents[0];
if(mostRecentBlock.action == "unblock") {
if(Date.now() > Date.parse(mostRecentBlock.timestamp) + trackingTime) {
return [false, ""];
}
if(blocks.query.logevents.length > 1 && blocks.query.logevents[1].params.duration != "infinity" && Date.now() > Date.parse(blocks.query.logevents[1].params.expiry)) {
return [false, ""];
}
return [true, mostRecentBlock.comment];
}
if(mostRecentBlock.action == "block") {
return [false, ""]; // We do not want to track people still being blocked or whose block expired naturally
}
return [false, ""];
}
async checkForPermission( functionCheck, className, descriptionForHover, link, dataJSON ) {
var [check, desc] = await functionCheck(this.user, dataJSON);
if ( check ) {
if ( desc == "" ) {
desc = descriptionForHover;
}
this.addClassAndHoverText( className, desc, link );
}
}
addClassAndHoverText( className, descriptionForHover, link ) {
link.addClass( className );
const title = this.$link.attr( 'title' );
if ( !title || title.startsWith( 'User:' ) || title.startsWith( 'User talk:' ) ) {
link.attr( 'title', descriptionForHover );
}
// If the user has been unblocked recently, we want to track them, so be aggressive about overriding the background and foreground color. That way there's no risk their signature is unreadable due to background color and foreground color being too similar.
link.addClass( link.attr( 'class' ) + ' UHS-override-signature-colors' );
}
async addClassesAndHoverTextToLinkIfNeeded( link, dataJSON ) {
// Adds the class, less classes than needed as it is just "recently unblocked - less than 1 month (default)" and "recently unblocked with custom ROPE"
this.checkForPermission( this.customUnblock, 'UHS-custom-unblock', 'Recently unblocked account', link, dataJSON );
}
setHighlightColors() {
// Highest specificity goes on bottom. So if you want an admin+steward to be highlighted steward, place the steward CSS below the admin CSS in this section.
this.addCSS( 'UHS-override-signature-colors', `
color: #0645ad !important;
background-color: transparent !important;
background: unset !important;
` );
this.addCSS( 'UHS-custom-unblock', 'text-decoration:underline wavy rgb(250, 117, 188) !important;' );
}
}
// Fire after wiki content is added to the DOM, such as when first loading a page, or when a gadget such as the XTools gadget loads.
mw.hook( 'wikipage.content' ).add( async () => {
await mw.loader.using( [ 'mediawiki.util', 'mediawiki.Uri', 'mediawiki.Title' ], async () => {
await ( new UserHighlighterSimple( $, mw, window ) ).execute();
} );
} );
// Fire after an edit is successfully saved via JavaScript, such as edits by the Visual Editor and HotCat.
mw.hook( 'postEdit' ).add( async () => {
await mw.loader.using( [ 'mediawiki.util', 'mediawiki.Uri', 'mediawiki.Title' ], async () => {
await ( new UserHighlighterSimple( $, mw, window ) ).execute();
} );
} );
// This second part focuses on adding "rope" to existing unblocked users and storing them in the data file
async function addRope( user, time ){
console.log(user);
console.log(time);
var dataJSON = await getUsernames();
console.log(JSON.stringify(dataJSON));
var blockParams = {
action: 'query',
format: 'json',
list: 'logevents',
letype: 'block',
letitle: 'User:' + user
};
var blocks = await ruhMediaWikiApi.get( blockParams );
dataJSON[user] = { expiry: Date.parse(blocks.query.logevents[0].timestamp) + time, comment: blocks.query.logevents[0].comment };
console.log(JSON.stringify(dataJSON));
var params = {
action: 'edit',
title: 'User:Chaotic Enby/RecentUnblockHighlighter/data',
text: JSON.stringify(dataJSON),
format: 'json',
summary: 'Updating log entry for ' + user
};
if ( (mw.config.get( "wgUserName" ) == "Chaotic Enby") ) { // Exclusively for testing purposes
ruhMediaWikiApi.postWithToken( 'csrf', params ).done( function ( data ) { console.log( data );} );
} else if ( mw.config.get( "wgUserGroups" ).includes("sysop") ) {
ruhMediaWikiApi.postWithToken( 'csrf', params );
}
}
const timeString = ["2 weeks", "1 month", "3 months", "6 months", "1 year"];
const timeCount = [14, 30, 90, 180, 365]; // In days, converted in milliseconds later down the line
var portlets = [];
if ( mw.config.get("wgRelevantUserName") != null && (mw.config.get( "wgUserName" ) == "Chaotic Enby" || mw.config.get( "wgUserGroups" ).includes("sysop"))) {
var blockParams = {
action: 'query',
format: 'json',
list: 'logevents',
letype: 'block',
letitle: 'User:' + mw.config.get("wgRelevantUserName")
};
ruhMediaWikiApi.get( blockParams ).then((blocks) => {
if(blocks.query.logevents[0].action == "unblock" && Date.parse(blocks.query.logevents[0].timestamp) > Date.now() - 365 * 86400 * 1000){
mw.util.addPortlet( 'p-ruh', 'UH', '#p-cactions' );
portlets.push( mw.util.addPortletLink ( 'p-ruh', '#', 'Untrack', 'pruh-null', 'Removes user highlighting' ) );
jQuery( portlets[0] ).on( "click", async () => addRope( mw.config.get( "wgRelevantUserName" ), 0 ) );
for ( let i = 0; i < timeString.length; i++ ) {
portlets.push( mw.util.addPortletLink ( 'p-ruh', '#', timeString[i], 'pruh-' + i, 'Highlight user for ' + timeString[i] + ' following their unblock' ) );
jQuery( portlets[i + 1] ).on( "click", async () => addRope( mw.config.get( "wgRelevantUserName" ), timeCount[i] * 86400 * 1000 ) );
}
}
});
}
// </nowiki>