User:JJPMaster/fileunlink.js
Appearance
Note: After saving, changes may not occur immediately. Click here to learn how to bypass your browser's cache.
- Mozilla / Firefox / Safari: hold down Shift while clicking Reload, or press Ctrl-Shift-R (Cmd-Shift-R on Apple Mac);
- Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5;
- Konqueror: simply click the Reload button, or press F5;
- Opera users may need to completely clear their cache in Tools→Preferences.
Warning: Malicious code can compromise your account. Page preview will cause your web browser to execute this page's content as code under some skins, including Monobook. If you have any questions about any code you plan to add, you can ask at the appropriate reading room. |
Documentation for this user script can be added at User:JJPMaster/fileunlink. |
// <nowiki>
if (mw.config.get("wgNamespaceNumber") == 6 && window.isReviewer)
var fileunlinkLink = mw.util.addPortletLink('luna-actions', '#', 'Unlink (file uses)', 'luna-fileunlink', 'Remove all uses of this file');
$(fileunlinkLink).click(() => {
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>