User:Guywan/Scripts/FileMoverHelper.js

// [[Category:Wikipedia scripts]] // // Authors: [[User:Guywan]] // [[User:BrandonXLF]] // [[User:SD0001]] // // <nowiki> $.when($.ready, mw.loader.us

// [[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.edit)
                    	{
                        	editrate = data.query.userinfo.ratelimits.edit.user.hits / data.query.userinfo.ratelimits.edit.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>

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.