User:JJPMaster/fileunlink.js

// <nowiki>
if (mw.config.get("wgNamespaceNumber") == 6 && window.isReviewer) {
	var fileunlinkLink = window.addLunaLink({
		id: 'luna-fileunlink', 
		text: 'Unlink (file uses)', 
		href: '#', 
		tooltip: 'Remove all uses of this file',
		onClick: fileUnlink
	}); 

}
async function getImageUses() {
    var params = {
		action: 'query',
		format: 'json',
		list: 'imageusage',
		iulimit: 'max',
		iutitle: mw.config.get("wgPageName")
	},
	api = new mw.Api();

	const data = await api.get(params);
	return data.query.imageusage;
}
async function getFileUnlinkedContent(title, unlinked) {
	var params = {
		action: 'parse',
		page: title,
		prop: 'wikitext',
		format: 'json'
	},
	api = new mw.Api();
	const data = await api.get(params);
	var text = data.parse.wikitext['*'];
	var myPage = new Morebits.wikitext.Page(text);
	var newText = myPage.commentOutImage(unlinked.substr(5), "Commented out").getText();
	return newText;
}
	
async function fileUnlink() {
	if (window.isReviewer) {
		var doIt = confirm("You are about to remove all of the links to this page. If you mess up, this is likely to be very difficult to reverse. Are you *ABSOLUTELY SURE* you want to do this?");
		if (!doIt) return;
		var uses = await getImageUses();
		var params, api;
		for (var u of uses) {
			var content = await getFileUnlinkedContent(u.title, mw.config.get("wgPageName"));
			params = {
				action: 'edit',
				format: 'json',
				text: content,
				title: u.title,
				summary: `Removing use(s) of [[${mw.config.get("wgPageName").replace(/_/g, ' ')}]]`,
				tags: "Luna"
			};
			api = new mw.Api();
			
			api.postWithToken( 'csrf', params ).done( function ( data ) {
				console.log( data );
			} );
		}
		if (getImageUses().length > 0) 
			alert("It looks like not all of the image uses were removed. This is most likely because you hit the rate limit. Please try again later.");
		else alert("Done!");
	}
	else {
		alert("Luna: You must be a reviewer or administrator to use this tool.");
		return;
	}
}
// </nowiki>