User:Jon Kolbert/mr.js

/* Taken from User:Legoktm/massrename.js*/ (function( mw, $ ) {

window.mrg_queue = []; // In-progress queue window.mrg_count = 0; // Total count window.mrg_done = 0; // Already moved count window.mrg_movetoken = null; // Populated later

function fetch_cat_members( name, cont, callback ) { var params ={ action: 'query', rawcontinue: '', list: 'categorymembers', cmtitle: 'Category:' + name, cmnamespace: 6, cmlimit: 'max' };		if ( cont !== undefined ) { params.cmcontinue = cont; }		( new mw.Api ).get(params).done( function( data ) {			if ( data['query-continue'] ) {				fetch_cat_members( name, data['query-continue']['categorymembers']['cmcontinue'], callback );			}			callback( data.query.categorymembers );		}); }

function refresh_progressbar { var selector = $('#mrg-progress'); selector.progressbar('option', 'max', window.mrg_count); selector.progressbar('option', 'value', window.mrg_done); }

function rename_file( old, newname, reason, callback ) { ( new mw.Api ).post({			action: 'move',			from: old,			to: newname,			reason: reason,			movetalk: 1,			bot: 1,			token: window.mrg_movetoken		}, {			async: false // Don't run parallel requests, be nice to sever kittens!		}).done( callback ); }

function queue { fetch_cat_members( $('#mrg-cat').val, undefined, function( members ) {			var old_length = window.mrg_queue.length;			$.each( members, function( _, val ) { window.mrg_queue.push(val.title); });			window.mrg_count += members.length;			if ( old_length == 0 ) {				run;			}			refresh_progressbar;		}); }

function escapeRegExp(str) { // From MDN return str.replace(/([.*+?^=!:${}|\[\]\/\\])/g, "\\$1"); }

function run { while ( window.mrg_queue.length > 0 ) { var old_name = window.mrg_queue.shift, new_name, find = $('#mrg-find').val, replace = $('#mrg-rep').val, reason = $('#mrg-son').val; new_name = old_name.replace(new RegExp(escapeRegExp(find), 'g'), replace); rename_file( old_name, new_name, reason, function( data ) {				window.mrg_done += 1;				refresh_progressbar;			}); }	}

function init { var html = [ ' ',			' ',			'Category name (without namespace): ', 'Find: ', 'Replace: ', 'Reason: ', '<input type="text" name="mrg-son" id="mrg-son"', ' ',			' ',			' '		].join("\n"); $('#mw-content-text').after($(html)); // Stick it somewhere in the DOM mw.util.addCSS('label, input { display: block; }'); mw.loader.using(['jquery.ui'], function {			$('#mrg-dialog').dialog({ buttons: [ {						text: 'Move', click: queue }				],				title: 'Mass Rename Gadget' });			$('#mrg-progress').progressbar({max: 1});		});

( new mw.Api ).getToken( 'move').done( function( token ) {			window.mrg_movetoken = token;		}); }

function small_init { mw.loader.using('mediawiki.util', function{			var portletlink = mw.util.addPortletLink( 'p-cactions', '#', 'Mass Rename', 'ca-mrg', 'Rename stuff');			$( portletlink).click( function( e ) { e.preventDefault; init; });		});	}

$( small_init ); }( mediaWiki, jQuery ));