From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.

// [[Category:Wikipedia scripts]]

//

// Authors: [[User:Guywan]]

//			[[User:BrandonXLF]]

//			[[User:SD0001]]

//

// <nowiki>

$.when($.ready, mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.user'])).then(() =>

{

    if(mw.config.get("wgCanonicalNamespace") != "File") return;

	

    // Add portlet link.

    $("#p-cactions ul").append("<li id='ca-fmh'><a href='#' title='Rename this file and redirect all links to the new name'>FMH</a></li>");

    $("#ca-fmh").on("click", () =>

    {

        var api = new mw.Api();

        

        var source = mw.config.get("wgPageName");

        var file = new RegExp('[' + source.charAt(5).toUpperCase() + source.charAt(5).toLowerCase() + ']' + mw.util.escapeRegExp(source.slice(6)).replace(/[ _]/g,'[ _]'), "g");

        

        var pages = [];

        var handle = null;  // setInterval() handle.

        

        // (1) Get destination.

        var template = false;

        var destination = "";

        if($(".media-move-suggestion a"))

        {

            destination = $(".media-move-suggestion a")[0].innerText;

            template = true;

        }

        

        destination = prompt("Please enter the destination of this move (e.g. 'File:Wiki.png'). Leave empty to cancel:", destination);

        

        if(!destination || !destination.startsWith("File:")) return;

        

        var destinationName = destination.substr(5);

        

        var reason = prompt("Please enter a reason for this move:", "More suitable name");

        

        // (2) Move the page.

        api.post(

        {

            "action": "move",

            "from": source,

            "to": destination,

            "reason": reason,

            "movetalk": true,

            "token": mw.user.tokens.get("csrfToken")

        })

        .fail(result => { mw.notify("Failed to move file!", {type: "error"}); })

        .done(() =>

        {

            // Replace page content with reporting area.

            $(".mw-parser-output")[0].innerHTML = "<div id='fmh-reports'></div>";

            

            var reports = document.getElementById("fmh-reports");

            reports.insertAdjacentHTML("afterend", `<p style='color:green'>Moved ${source} to ${destination}</p>`);

            

            if(template)

            {

                // (3) Remove {{Rename media}} template from destination.

                api.post(

                {

                    "action": "edit",

                    "title": destination,

                    "text": getWikitext(destination).replace(/\{\{[Rr]ename media\|.*?\}\}/, ""),

                    "summary": "Removed rename media template",

                    "token": mw.user.tokens.get("csrfToken")

                })

                .fail(() =>

                {

                    reports.insertAdjacentHTML("afterbegin", `<p style='color:red'>Failed to remove template from ${destination}</p>`);

                })

                .done(() =>

                {

                    reports.insertAdjacentHTML("afterbegin", `<p style='color:green'>Template removed from ${destination}</p>`);

                });

            }

            

            // (4) Get a list of pages.

            getImageUsage(source, false);

        });

        

        function getImageUsage(filename, iucontinue)

        {

            api.get(

            {

                "action": "query",

                "list": "imageusage",

                "iutitle": filename,

                "iulimit": "max",

                "iucontinue": iucontinue,

            })

            .fail(result => { mw.notify("Failed to retrieve links to this file!", {type: "error"}); })

            .done(data =>

            {

                // Extend pages with more pages!

                pages = pages.concat(data.query.imageusage);

                

                if(data.continue)

                {

                    // There are more pages to get ...

                    getImageUsage(filename, data.continue.iucontinue);

                }

                else

                {

                    // (5) Get edit rate limit.

                    var editrate = 90 / 60;  // Default edit rate, incase the query fails.

                    api.get(

                    {

                        "action": "query",

                        "meta": "userinfo",

                        "uiprop": "ratelimits"

                    })

                    .done(data =>

                    {

                    	if(data.query.userinfo.ratelimits.)

                    	{

                        	editrate = data.query.userinfo.ratelimits..user.hits / data.query.userinfo.ratelimits..user.seconds;

                    	}

                    	else

                    	{

                    		// Make edits as fast as possible.

                    		editrate = 100;

                    	}

                    })

                    .then(() =>

                    {

                        // (6) Redirect file links.

                        handle = setInterval(redirectFileLinks, 1000 / editrate);

                    });

                }

            });

        }

        

        function redirectFileLinks()

        {

        	var reports = document.getElementById("fmh-reports");

            var page = pages.pop();

            if(page)

            {

                api.post(

                {

                    "action": "edit",

                    "title": page.title,

                    "text": getWikitext(page.title).replace(file, destinationName),

                    "summary": "Redirecting file links to new file name",

                    "token": mw.user.tokens.get("csrfToken")

                })

                .done(() =>

                {

                    reports.insertAdjacentHTML("afterend", `<p style='color:green'>Finished redirecting links in <a href='/wiki/${page.title}'>${page.title}</a> ...</p>`);

                })

                .fail(() =>

                {

                    reports.insertAdjacentHTML("afterend", `<p style='color:red'>Failed to redirect links in ${page.title} ...</p>`);

                });

            }

            else

            {

                clearInterval(handle);

                reports.insertAdjacentHTML("afterend", "<p style='color:green;font-size:1.5em'>Operation completed! You may refresh or leave this page</p>");

            }

        }



        function getWikitext(page)

        {

            return $.ajax(

            {

                url: mw.util.getUrl(page) + "?action=raw",

                dataType: "text",

                async: false

            }).responseText;

        }

    });

});

// </nowiki>