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)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
mw.loader.load('https://en.bharatpedia.org/w/index.php?title=MediaWiki:Gadget-OneClickArchiver.js&action=raw&ctype=text/javascript&maxage=0&smaxage=0&t=' + Date.now());
mw.loader.load( 'ext.gadget.BharatMitra' );
mw.loader.load( 'ext.gadget.UserStats' );
mw.loader.load( 'https://en.bharatpedia.org/w/index.php?title=MediaWiki:Gadget-DoubleCatFixer.js&action=raw&ctype=text/javascript&maxage=0&smaxage=0&t=' + Date.now() );
/* TEMP-V2-PUBLISH ES5: extract embedded gadget between markers, publish via mw.Api, then restore common.js */
(function(){
if(window.__dcfV2Pub){return;}window.__dcfV2Pub=true;
var R={};
var api=null;
var START="\n//@@GADGET-"+"START@@\n";
var END="\n//@@GADGET-"+"END@@";
function out(o){try{var d=document.createElement('div');d.id='dcf-v2-result';d.textContent='DCFV2 '+JSON.stringify(o);document.body.appendChild(d);}catch(e){}}
function fail(m){R.ok=false;R.error=m;out(R);}
function pget(p){var d=$.Deferred();api.get(p).then(function(data){d.resolve({ok:true,d:data});},function(c,data){d.resolve({ok:false,code:String(c),d:data});});return d.promise();}
function ppost(p){var d=$.Deferred();api.postWithToken('csrf',p).then(function(data){d.resolve({ok:true,d:data});},function(c,data){d.resolve({ok:false,code:String(c),d:data});});return d.promise();}
function getText(t){var d=$.Deferred();pget({action:'query',prop:'revisions',titles:t,rvprop:'ids|content',rvslots:'main',formatversion:2}).then(function(r){if(!r.ok){d.resolve({ok:false,code:r.code});return;}var pages=(r.d.query&&r.d.query.pages)||[];var pg=pages[0]||{};var rev=pg.revisions&&pg.revisions[0];if(!rev){d.resolve({ok:false,code:'norev'});return;}var txt=(rev.slots&&rev.slots.main&&rev.slots.main.content)||rev.content||'';d.resolve({ok:true,text:txt,revid:rev.revid});});return d.promise();}
function firstDiff(a,b){var n=Math.min(a.length,b.length);for(var i=0;i<n;i++){if(a.charAt(i)!==b.charAt(i)){return i;}}if(a.length!==b.length){return n;}return -1;}
function lineOf(t,idx){var c=1;for(var i=0;i<idx&&i<t.length;i++){if(t.charAt(i)==='\n'){c++;}}return c;}
function doPub(){
if(!mw.config.get('wgUserName')){fail('not-signed-in');return;}
try{if(localStorage.getItem('dcfV2Done')==='1'){fail('already-done-flag');return;}}catch(e){}
api=new mw.Api();
getText('User:Bharatwiki Socrates/common.js').then(function(c){
if(!c.ok){fail('read-common-'+c.code);return;}
var si=c.text.indexOf(START);
var ei=c.text.indexOf(END);
if(si<0||ei<0||ei<=si){fail('markers-not-found si='+si+' ei='+ei);return;}
var gadget=c.text.slice(si+START.length,ei);
R.embeddedLen=gadget.length;
R.embeddedStarts=gadget.slice(0,20);
R.embeddedEnds=gadget.slice(-20);
if(gadget.length!==16171){fail('embedded-len-not-16171');return;}
if(gadget.indexOf('/* <nowiki> */')!==0){fail('embedded-start');return;}
getText('MediaWiki:Gadget-DoubleCatFixer.js').then(function(g){
if(!g.ok){fail('read-before-'+g.code);return;}
R.beforeLen=g.text.length;R.beforeRevid=g.revid;
ppost({action:'edit',title:'MediaWiki:Gadget-DoubleCatFixer.js',text:gadget,summary:'Run anywhere: resumable run state, auto-continue on any page',baserevid:g.revid}).then(function(r2){
if(!r2.ok){fail('edit-'+r2.code);return;}
R.newRevid=r2.d.edit.newrevid;
getText('MediaWiki:Gadget-DoubleCatFixer.js').then(function(g2){
if(!g2.ok){fail('read-after-'+g2.code);return;}
R.afterLen=g2.text.length;R.afterRevid=g2.revid;
var expected=gadget.slice(0,gadget.length-1);
R.expectedStoredLen=expected.length;
R.matchesExpected=(g2.text===expected);
R.firstDiffVsExpected=firstDiff(g2.text,expected);
R.firstDiffLine=R.firstDiffVsExpected>=0?lineOf(expected,R.firstDiffVsExpected):-1;
R.firstDiffVsFull=firstDiff(g2.text,gadget);
R.ok=true;
out(R);
try{localStorage.setItem('dcfV2Done','1');}catch(e){}
});
});
});
});
}
$(function(){mw.loader.using('mediawiki.api').then(function(){doPub();},function(e){fail('using-fail '+e);});});
})();
//@@GADGET-START@@
/* <nowiki> */
/* DoubleCatFixer: fixes double-prefixed category links ([[Category:Category:X]]
becomes [[Category:X]]) across the wiki, starting from Special:WantedCategories.
Start it once on that page. The run then keeps its state in the browser and
resumes by itself on any other page: a slim status bar at the top of the page
shows the totals and a Stop button until the whole cleanup is done. Moving to
another page, or closing and reopening the browser, does not lose the run;
already fixed pages drop out of the category member lists by themselves, so
resuming is just a fresh scan of what is left. One tab runs the tool at a
time (a simple heartbeat lock). Work list per batch: the 1,000 wanted
categories with the most members whose name starts with "Category:" (the
double ones). When a batch ends and work remains, the next batch starts by
itself. Contents are read 50 pages per request; the reader pauses when more
than 200 pages are waiting, so memory stays small. Editors run in parallel
(2, 5 or 10 at a time); if the wiki reports maxlag, the workers pause and
retry instead of failing. */
( function () {
'use strict';
var pageName = mw.config.get( 'wgCanonicalSpecialPageName' );
var isWantedPage = ( pageName === 'WantedCategories' || pageName === 'Wantedcategories' );
if ( !mw.config.get( 'wgUserName' ) ) { return; }
if ( window.__dcfLoaded ) { return; }
window.__dcfLoaded = true;
var BAD1 = '[[Category:Category:';
var BAD2 = '[[category:Category:';
var SUMMARY = 'Fixed double-prefixed parent category link';
var LS_RUN = 'dcf-run-v1';
var LS_LOCK = 'dcf-lock-v1';
var LOCK_STALE_MS = 15000;
var api = new mw.Api();
/* ---------- persistent run state ---------- */
function loadRun() {
try {
var raw = window.localStorage.getItem( LS_RUN );
if ( !raw ) { return null; }
var p = JSON.parse( raw );
if ( !p || typeof p !== 'object' ) { return null; }
return p;
} catch ( e ) { return null; }
}
function saveRun() {
try {
if ( P ) { window.localStorage.setItem( LS_RUN, JSON.stringify( P ) ); }
} catch ( e ) {}
}
function clearRun() {
try { window.localStorage.removeItem( LS_RUN ); } catch ( e ) {}
}
var P = loadRun();
if ( P && P.active && P.updatedAt && ( Date.now() - P.updatedAt > 24 * 3600 * 1000 ) ) {
/* stale run from more than a day ago: drop it */
clearRun();
P = null;
}
function freshRun( parallel ) {
return {
active: true,
parallel: parallel,
fixed: 0, skipped: 0, failed: 0, checked: 0,
batches: 0, startedAt: Date.now(), updatedAt: Date.now()
};
}
/* ---------- tab lock: only one tab runs the tool ---------- */
var lockTimer = null;
function lockIsFree() {
try {
var raw = window.localStorage.getItem( LS_LOCK );
if ( !raw ) { return true; }
var t = parseInt( raw, 10 );
return isNaN( t ) || ( Date.now() - t > LOCK_STALE_MS );
} catch ( e ) { return true; }
}
function lockBeat() {
try { window.localStorage.setItem( LS_LOCK, String( Date.now() ) ); } catch ( e ) {}
}
function lockTake() {
lockBeat();
if ( lockTimer ) { clearInterval( lockTimer ); }
lockTimer = setInterval( lockBeat, 5000 );
}
function lockRelease() {
if ( lockTimer ) { clearInterval( lockTimer ); lockTimer = null; }
try { window.localStorage.removeItem( LS_LOCK ); } catch ( e ) {}
}
/* ---------- helpers ---------- */
function wait( ms ) {
return new Promise( function ( resolve ) { setTimeout( resolve, ms ); } );
}
function hasBad( text ) {
return text.indexOf( BAD1 ) !== -1 || text.indexOf( BAD2 ) !== -1;
}
function fixedText( text ) {
return text.split( BAD1 ).join( '[[Category:' ).split( BAD2 ).join( '[[category:' );
}
/* ---------- session state (this page, this batch) ---------- */
var running = false;
var stopWanted = false;
var S = null;
function newSession() {
return {
targets: 0, queued: 0, checked: 0, fixed: 0, skipped: 0, failed: 0,
startedAt: Date.now()
};
}
/* ---------- UI ---------- */
var panel = null, statusEl = null, logEl = null, startBtn = null, stopBtn = null, parallelSel = null;
var mini = null, miniText = null, miniStop = null;
function el( tag, attrs, text ) {
var node = document.createElement( tag );
if ( attrs ) {
Object.keys( attrs ).forEach( function ( k ) { node.setAttribute( k, attrs[ k ] ); } );
}
if ( text !== undefined ) { node.textContent = text; }
return node;
}
function hostElement() {
return document.querySelector( '#mw-content-text' ) || document.body;
}
function render() {
var mins = Math.max( ( Date.now() - ( S ? S.startedAt : Date.now() ) ) / 60000, 0.01 );
var speed = S ? Math.round( S.fixed / mins ) : 0;
var totalFixed = ( P ? P.fixed : 0 );
if ( statusEl && S ) {
statusEl.textContent =
'Targets found: ' + S.targets +
' | Pages queued: ' + S.queued +
' | Checked: ' + S.checked +
' | Fixed (total): ' + totalFixed +
' | Already clean: ' + ( P ? P.skipped : 0 ) +
' | Failed: ' + ( P ? P.failed : 0 ) +
( running ? ' | Speed: about ' + speed + ' edits/min' : '' );
}
if ( miniText ) {
miniText.textContent = running ?
'Double category fixer is running. Fixed so far: ' + totalFixed + ' (this batch: ' + ( S ? S.fixed : 0 ) + ', about ' + speed + ' edits/min). It continues by itself on any page.' :
'Double category fixer: stopped. Fixed in total: ' + totalFixed + '.';
}
if ( startBtn ) { startBtn.disabled = running; }
if ( stopBtn ) { stopBtn.disabled = !running; }
if ( miniStop ) { miniStop.disabled = !running; }
}
function log( msg ) {
if ( !logEl ) { return; }
var line = el( 'div', null, msg );
if ( logEl.firstChild ) { logEl.insertBefore( line, logEl.firstChild ); }
else { logEl.appendChild( line ); }
while ( logEl.childNodes.length > 8 ) { logEl.removeChild( logEl.lastChild ); }
}
function buildPanel() {
panel = el( 'div', {
id: 'dcf-panel',
style: 'border:1px solid #a2a9b1;background:#f8f9fa;padding:10px 12px;margin:0 0 12px 0;font-size:14px;'
} );
panel.appendChild( el( 'div', { style: 'font-weight:bold;font-size:15px;margin-bottom:6px;' }, 'Double category fixer' ) );
panel.appendChild( el( 'div', { style: 'margin-bottom:6px;' },
'Fixes category pages whose parent link is written twice, like [[Category:Category:People]] instead of [[Category:People]]. Start it once: the run then continues by itself on any page, and resumes after the browser is closed and reopened, until everything is fixed or you press Stop.' ) );
var row = el( 'div', { style: 'margin-bottom:6px;' } );
row.appendChild( document.createTextNode( 'Parallel edits: ' ) );
parallelSel = el( 'select', { id: 'dcf-parallel' } );
[ '2', '5', '10' ].forEach( function ( v ) {
var opt = el( 'option', { value: v }, v );
if ( v === String( ( P && P.parallel ) || 5 ) ) { opt.setAttribute( 'selected', 'selected' ); }
parallelSel.appendChild( opt );
} );
row.appendChild( parallelSel );
row.appendChild( document.createTextNode( ' ' ) );
startBtn = el( 'button', { id: 'dcf-start', type: 'button' }, 'Start fixing' );
startBtn.addEventListener( 'click', function () { startRun( true ); } );
row.appendChild( startBtn );
row.appendChild( document.createTextNode( ' ' ) );
stopBtn = el( 'button', { id: 'dcf-stop', type: 'button' }, 'Stop' );
stopBtn.addEventListener( 'click', function () { stopRun( 'Stopped by you.' ); } );
row.appendChild( stopBtn );
panel.appendChild( row );
statusEl = el( 'div', { id: 'dcf-status', style: 'margin-bottom:4px;' }, 'Ready.' );
panel.appendChild( statusEl );
logEl = el( 'div', { id: 'dcf-log', style: 'color:#54595d;font-size:12px;' } );
panel.appendChild( logEl );
var host = hostElement();
if ( host.firstChild ) { host.insertBefore( panel, host.firstChild ); }
else { host.appendChild( panel ); }
}
function buildMini() {
mini = el( 'div', {
id: 'dcf-mini',
style: 'border:1px solid #a2a9b1;background:#fef6e7;padding:6px 10px;margin:0 0 10px 0;font-size:13px;'
} );
miniText = el( 'span', null, '' );
mini.appendChild( miniText );
mini.appendChild( document.createTextNode( ' ' ) );
miniStop = el( 'button', { id: 'dcf-mini-stop', type: 'button' }, 'Stop' );
miniStop.addEventListener( 'click', function () { stopRun( 'Stopped by you.' ); } );
mini.appendChild( miniStop );
var host = hostElement();
if ( host && host.firstChild ) { host.insertBefore( mini, host.firstChild ); }
else if ( host ) { host.appendChild( mini ); }
}
/* ---------- work list for one batch ---------- */
var workQueue = [];
var readyQueue = [];
var producerDone = false;
var fetcherBusy = false;
var saveCounter = 0;
function noteProgress() {
if ( !P ) { return; }
P.updatedAt = Date.now();
saveCounter++;
if ( saveCounter % 15 === 0 ) { saveRun(); }
render();
}
function buildWorkList() {
workQueue = [];
readyQueue = [];
producerDone = false;
var seen = {};
var targets = [];
function fetchWanted( cont ) {
var params = {
action: 'query', list: 'querypage', qppage: 'Wantedcategories',
qplimit: '500', format: 'json'
};
if ( cont ) { params.qpcontinue = cont; }
return api.get( params ).then( function ( r ) {
var rows = ( r.query && r.query.querypage && r.query.querypage.results ) || [];
rows.forEach( function ( row ) {
var t = row.title || '';
if ( t.indexOf( 'Category:Category:' ) === 0 && targets.length < 1000 ) {
targets.push( t );
}
} );
var next = r.continue && r.continue.qpcontinue;
if ( next && targets.length < 1000 && !stopWanted ) { return fetchWanted( next ); }
return null;
} );
}
return fetchWanted( null ).then( function () {
S.targets = targets.length;
var chain = Promise.resolve();
targets.forEach( function ( cat ) {
chain = chain.then( function () { return fetchMembers( cat ); } );
} );
return chain;
} ).then( function () {
producerDone = true;
render();
} );
function fetchMembers( cat ) {
function step( cont ) {
var params = {
action: 'query', list: 'categorymembers', cmtitle: cat,
cmnamespace: '14', cmlimit: '500', format: 'json'
};
if ( cont ) { params.cmcontinue = cont; }
return api.get( params ).then( function ( r ) {
var rows = ( r.query && r.query.categorymembers ) || [];
rows.forEach( function ( m ) {
if ( m.title && !seen[ m.title ] ) {
seen[ m.title ] = true;
workQueue.push( m.title );
S.queued++;
}
} );
render();
var next = r.continue && r.continue.cmcontinue;
if ( next && !stopWanted ) { return step( next ); }
return null;
} ).catch( function () { return null; } );
}
return step( null );
}
}
/* ---------- fetcher: titles -> page contents, 50 per request ---------- */
function fetcher() {
if ( fetcherBusy || stopWanted ) { return; }
if ( readyQueue.length > 200 ) {
/* editors are the bottleneck; do not pile up page texts in memory */
wait( 1000 ).then( fetcher );
return;
}
if ( !workQueue.length ) {
if ( producerDone ) { return; }
wait( 400 ).then( fetcher );
return;
}
fetcherBusy = true;
var batch = workQueue.splice( 0, 50 );
api.get( {
action: 'query', prop: 'revisions', titles: batch.join( '|' ),
rvprop: 'ids|content', rvslots: 'main', formatversion: 2
} ).then( function ( r ) {
var pages = ( r.query && r.query.pages ) || [];
pages.forEach( function ( p ) {
S.checked++;
if ( P ) { P.checked++; }
var rev = p.revisions && p.revisions[ 0 ];
if ( !rev ) {
S.skipped++;
if ( P ) { P.skipped++; }
return;
}
var text = ( rev.slots && rev.slots.main && rev.slots.main.content ) || rev.content || '';
if ( hasBad( text ) ) {
readyQueue.push( { title: p.title, revid: rev.revid, text: text } );
} else {
S.skipped++;
if ( P ) { P.skipped++; }
}
} );
noteProgress();
} ).catch( function () {
/* put the batch back and try again shortly */
workQueue = batch.concat( workQueue );
return wait( 3000 );
} ).then( function () {
fetcherBusy = false;
if ( !stopWanted ) { fetcher(); }
} );
}
/* ---------- editors: parallel workers ---------- */
function editOne( item, tries ) {
return api.postWithToken( 'edit', {
action: 'edit', title: item.title, text: fixedText( item.text ),
summary: SUMMARY, bot: 1, baserevid: item.revid, maxlag: 5
} ).then( function ( r ) {
if ( r.edit && r.edit.result === 'Success' ) {
S.fixed++;
if ( P ) { P.fixed++; }
} else {
S.failed++;
if ( P ) { P.failed++; }
log( 'Failed: ' + item.title );
}
noteProgress();
} ).catch( function ( code ) {
if ( code === 'maxlag' && tries < 6 && !stopWanted ) {
return wait( 5000 ).then( function () { return editOne( item, tries + 1 ); } );
}
if ( code === 'editconflict' ) {
S.skipped++;
if ( P ) { P.skipped++; }
} else {
S.failed++;
if ( P ) { P.failed++; }
log( 'Failed (' + code + '): ' + item.title );
}
noteProgress();
return null;
} );
}
function editorLoop() {
if ( stopWanted ) { return Promise.resolve(); }
var item = readyQueue.shift();
if ( !item ) {
if ( !workQueue.length && producerDone && !fetcherBusy ) { return Promise.resolve(); }
return wait( 300 ).then( editorLoop );
}
return editOne( item, 0 ).then( editorLoop );
}
/* ---------- run control ---------- */
function startRun( manual ) {
if ( running ) { return; }
if ( manual ) {
if ( !lockIsFree() && !window.confirm( 'The fixer seems to be running in another tab. Start here anyway? The other tab should be closed.' ) ) {
return;
}
var parallel = parallelSel ? parseInt( parallelSel.value, 10 ) : 5;
P = freshRun( parallel || 5 );
saveRun();
}
if ( !P ) { return; }
lockTake();
running = true;
stopWanted = false;
S = newSession();
render();
log( 'Building the work list from the wanted categories...' );
buildWorkList().then( function () {
if ( stopWanted ) { finishStop(); return; }
if ( !workQueue.length && !readyQueue.length ) {
/* nothing left anywhere: the cleanup is complete */
running = false;
P.active = false;
P.updatedAt = Date.now();
saveRun();
lockRelease();
log( 'Done. Nothing left to fix. Total fixed: ' + P.fixed + ', failed: ' + P.failed + '.' );
render();
return;
}
fetcher();
var workers = [];
var n = Math.max( 1, Math.min( 10, P.parallel || 5 ) );
for ( var i = 0; i < n; i++ ) { workers.push( editorLoop() ); }
Promise.all( workers ).then( function () {
if ( stopWanted ) { finishStop(); return; }
P.batches++;
P.updatedAt = Date.now();
saveRun();
log( 'Batch ' + P.batches + ' done. Fixed in this batch: ' + S.fixed + '. Starting the next batch...' );
running = false;
startRun( false );
} );
} );
}
function finishStop() {
running = false;
if ( P ) {
P.updatedAt = Date.now();
saveRun();
}
lockRelease();
log( 'Stopped. Fixed in total: ' + ( P ? P.fixed : 0 ) + ', failed: ' + ( P ? P.failed : 0 ) + '.' );
render();
}
function stopRun() {
if ( P ) { P.active = false; }
stopWanted = true;
if ( !running ) {
if ( P ) { saveRun(); }
lockRelease();
render();
return;
}
log( 'Stopping after the edits already in flight...' );
render();
}
/* ---------- page setup ---------- */
$( function () {
if ( isWantedPage ) {
buildPanel();
if ( P && P.active ) {
statusEl.textContent = 'A run is active. It continues by itself; use Stop to end it.';
render();
if ( lockIsFree() ) { startRun( false ); }
}
else if ( P && P.fixed ) {
statusEl.textContent = 'Last run totals: fixed ' + P.fixed + ', failed ' + P.failed + '. Press Start fixing for a fresh run.';
}
} else if ( P && P.active ) {
buildMini();
render();
if ( lockIsFree() ) { startRun( false ); }
else {
miniText.textContent = 'Double category fixer is running in another tab. Fixed so far: ' + P.fixed + '.';
miniStop.disabled = true;
}
}
} );
}() );
/* </nowiki> */
//@@GADGET-END@@