MediaWiki:Common.js: Difference between revisions

From MDrivenWiki
No edit summary
No edit summary
Line 5: Line 5:
// ==/UserScript==
// ==/UserScript==


mw.loader.using(['mediawiki.api', 'mediawiki.util', 'oojs-ui'], function () {
mw.loader.using(['mediawiki.api', 'mediawiki.util', 'jquery', 'bootstrap'], function () {
     function addCleanDeleteLink() {
     function addCleanDeleteLink() {
         if (mw.config.get('wgUserGroups').indexOf('sysop') !== -1) {
         if (mw.config.get('wgUserGroups').indexOf('sysop') !== -1) {
Line 22: Line 22:
     function gatherAllDecisions(pageTitle) {
     function gatherAllDecisions(pageTitle) {
         var decisions = {};
         var decisions = {};
         var windowManager = new OO.ui.WindowManager();
         showModal('Handle Links and Redirects', `
        $('body').append(windowManager.$element);
            <div class="form-group">
 
                <label>Specify how you would like to handle all incoming links and redirects:</label>
        askForLinkHandling(pageTitle, decisions, windowManager, function () {
                <select id="link-handling-select" class="form-control">
            confirmDeletion(pageTitle, decisions, windowManager, function () {
                    <option value="delete">Delete Links and Redirects</option>
                 showLoadingDialog(windowManager, function (loadingDialog, updateLoadingText) {
                    <option value="change">Change Target of Links and Redirects</option>
                     executeAllActions(pageTitle, decisions, function () {
                </select>
                        loadingDialog.close().closed.then(function() {
            </div>
                            location.reload();
        `, function () {
                        });
            var choice = $('#link-handling-select').val();
                     }, updateLoadingText);
            if (choice === 'change') {
                showModal('Specify New Target', `
                    <div class="form-group">
                        <label>Enter the new target page name to update all links and redirects:</label>
                        <input type="text" id="new-target-input" class="form-control" placeholder="Enter new target">
                    </div>
                 `, function () {
                     decisions.links = $('#new-target-input').val();
                     confirmDeletion(pageTitle, decisions);
                 });
                 });
             });
             } else {
                decisions.links = '';
                confirmDeletion(pageTitle, decisions);
            }
         });
         });
     }
     }


     function askForLinkHandling(pageTitle, decisions, windowManager, callback) {
     function confirmDeletion(pageTitle, decisions) {
         function LinkHandlingDialog(config) {
         showModal('Confirm Page Deletion', `
             LinkHandlingDialog.super.call(this, config);
             <p>Are you sure you want to delete "${pageTitle}" after handling all links and redirects?</p>
        }
         `, function () {
         OO.inheritClass(LinkHandlingDialog, OO.ui.ProcessDialog);
            decisions.deletion = true;
 
             showLoadingDialog('Performing Cleanup', function (updateLoadingText) {
        LinkHandlingDialog.static.name = 'linkHandlingDialog';
                executeAllActions(pageTitle, decisions, function () {
        LinkHandlingDialog.static.title = 'Handle Links and Redirects';
                    location.reload();
        LinkHandlingDialog.static.actions = [
                 }, updateLoadingText);
             { action: 'continue', label: 'Continue', flags: ['primary', 'progressive'] },
            { action: 'cancel', label: 'Cancel', flags: ['safe', 'close'] }
        ];
 
        LinkHandlingDialog.prototype.initialize = function () {
            LinkHandlingDialog.super.prototype.initialize.apply(this, arguments);
 
            this.radioSelect = new OO.ui.RadioSelectWidget({
                 items: [
                    new OO.ui.RadioOptionWidget({ data: 'delete', label: 'Delete Links and Redirects' }),
                    new OO.ui.RadioOptionWidget({ data: 'change', label: 'Change Target of Links and Redirects' })
                ]
             });
             });
 
         });
            var fieldset = new OO.ui.FieldsetLayout({
                items: [
                    new OO.ui.FieldLayout(this.radioSelect, {
                        label: 'Specify how you would like to handle all incoming links and redirects:',
                        align: 'top'
                    })
                ]
            });
 
            this.content = new OO.ui.PanelLayout({
                padded: true,
                expanded: false
            });
 
            this.content.$element.append(fieldset.$element);
            this.$body.append(this.content.$element);
        };
 
        LinkHandlingDialog.prototype.getActionProcess = function (action) {
            var dialog = this;
            var process = new OO.ui.Process(function () {
                if (action === 'continue') {
                    var choice = dialog.radioSelect.findSelectedItem();
                    if (choice && choice.data === 'change') {
                        dialog.close().closed.then(function () {
                            askForNewTarget(pageTitle, decisions, windowManager, callback);
                        });
                    } else {
                        decisions.links = '';
                        dialog.close().closed.then(function () {
                            callback();
                        });
                    }
                } else if (action === 'cancel') {
                    dialog.close().closed.then(function () {
                        windowManager.destroy();
                    });
                }
            });
            return process;
         };
 
        windowManager.addWindows([new LinkHandlingDialog()]);
        windowManager.openWindow('linkHandlingDialog');
     }
     }


     function askForNewTarget(pageTitle, decisions, windowManager, callback) {
     function showModal(title, body, onConfirm) {
         function NewTargetDialog(config) {
         var modal = $(`
            NewTargetDialog.super.call(this, config);
            <div class="modal fade" tabindex="-1" role="dialog">
        }
                <div class="modal-dialog" role="document">
         OO.inheritClass(NewTargetDialog, OO.ui.ProcessDialog);
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${title}</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            ${body}
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary">Confirm</button>
                        </div>
                    </div>
                </div>
            </div>
         `);


         NewTargetDialog.static.name = 'newTargetDialog';
         modal.find('.btn-primary').click(function () {
        NewTargetDialog.static.title = 'Specify New Target';
             onConfirm();
        NewTargetDialog.static.actions = [
             modal.modal('hide');
             { action: 'continue', label: 'Continue', flags: ['primary', 'progressive'] },
         });
             { action: 'cancel', label: 'Cancel', flags: ['safe', 'close'] }
         ];


         NewTargetDialog.prototype.initialize = function () {
         modal.on('hidden.bs.modal', function () {
            NewTargetDialog.super.prototype.initialize.apply(this, arguments);
             modal.remove();
 
        });
            this.input = new OO.ui.TextInputWidget({
                value: '',
                placeholder: 'Enter new target'
            });
 
            var fieldset = new OO.ui.FieldsetLayout({
                items: [
                    new OO.ui.FieldLayout(this.input, {
                        label: 'Enter the new target page name to update all links and redirects:',
                        align: 'top'
                    })
                ]
            });
 
            this.content = new OO.ui.PanelLayout({
                padded: true,
                expanded: false
            });
 
            this.content.$element.append(fieldset.$element);
            this.$body.append(this.content.$element);
        };
 
        NewTargetDialog.prototype.getActionProcess = function (action) {
             var dialog = this;
            var process = new OO.ui.Process(function () {
                if (action === 'continue') {
                    decisions.links = dialog.input.getValue();
                    dialog.close().closed.then(function () {
                        callback();
                    });
                } else if (action === 'cancel') {
                    dialog.close().closed.then(function () {
                        windowManager.destroy();
                    });
                }
            });
            return process;
        };


         windowManager.addWindows([new NewTargetDialog()]);
         $('body').append(modal);
         windowManager.openWindow('newTargetDialog');
         modal.modal('show');
     }
     }


     function confirmDeletion(pageTitle, decisions, windowManager, callback) {
     function showLoadingDialog(message, callback) {
         var dialog = new OO.ui.MessageDialog();
         var modal = $(`
         windowManager.addWindows([dialog]);
            <div class="modal fade" tabindex="-1" role="dialog">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Performing Cleanup</h5>
                        </div>
                        <div class="modal-body">
                            <p id="loading-text">${message}</p>
                        </div>
                    </div>
                </div>
            </div>
         `);


         windowManager.openWindow(dialog, {
         $('body').append(modal);
            title: 'Confirm Page Deletion',
        modal.modal('show');
            message: 'Are you sure you want to delete "' + pageTitle + '" after handling all links and redirects?',
            actions: [
                { label: 'Confirm Deletion', action: 'confirm', flags: ['primary', 'destructive'] },
                { label: 'Cancel', action: 'cancel' }
            ]
        }).closed.then(function (data) {
            if (data.action === 'confirm') {
                decisions.deletion = true;
                callback();
            } else {
                windowManager.destroy();
            }
        });
    }


    function showLoadingDialog(windowManager, callback) {
        callback(function (text) {
        function LoadingDialog(config) {
             $('#loading-text').text(text);
            LoadingDialog.super.call(this, config);
            console.log(text); // Log progress
        }
        OO.inheritClass(LoadingDialog, OO.ui.ProcessDialog);
 
        LoadingDialog.static.name = 'loadingDialog';
        LoadingDialog.static.title = 'Performing Cleanup';
 
        LoadingDialog.prototype.initialize = function () {
             LoadingDialog.super.prototype.initialize.apply(this, arguments);
 
            this.loadingLabel = new OO.ui.LabelWidget({ label: 'Starting...' });
 
            this.content = new OO.ui.PanelLayout({
                padded: true,
                expanded: false
            });
 
            this.content.$element.append(this.loadingLabel.$element);
            this.$body.append(this.content.$element);
        };
 
        LoadingDialog.prototype.getActionProcess = function (action) {
            return new OO.ui.Process();
        };
 
        windowManager.addWindows([new LoadingDialog()]);
        windowManager.openWindow('loadingDialog').then(function (opened) {
            opened.then(function (dialog) {
                callback(dialog, function (text) {
                    dialog.loadingLabel.setLabel(text);
                    console.log(text); // Log progress
                });
            });
         });
         });
     }
     }

Revision as of 23:28, 7 July 2024

// ==UserScript==
// @name        MediaWiki Clean Delete
// @namespace   MediaWikiScripts
// @description Adds a 'Clean Delete' action link to pages for admins to delete pages and clean up incoming links and redirects.
// ==/UserScript==

mw.loader.using(['mediawiki.api', 'mediawiki.util', 'jquery', 'bootstrap'], function () {
    function addCleanDeleteLink() {
        if (mw.config.get('wgUserGroups').indexOf('sysop') !== -1) {
            if ($('#ca-cleandelete').length === 0) {
                var $link = $('<div>').attr('id', 'ca-cleandelete').attr('class', 'mw-list-item').append(
                    $('<a>').attr('href', '#').attr('class', 'ca-cleandelete').text('Clean Delete').click(function (e) {
                        e.preventDefault();
                        gatherAllDecisions(mw.config.get('wgPageName'));
                    })
                );
                $('#p-actions .tab-group').append($link);
            }
        }
    }

    function gatherAllDecisions(pageTitle) {
        var decisions = {};
        showModal('Handle Links and Redirects', `
            <div class="form-group">
                <label>Specify how you would like to handle all incoming links and redirects:</label>
                <select id="link-handling-select" class="form-control">
                    <option value="delete">Delete Links and Redirects</option>
                    <option value="change">Change Target of Links and Redirects</option>
                </select>
            </div>
        `, function () {
            var choice = $('#link-handling-select').val();
            if (choice === 'change') {
                showModal('Specify New Target', `
                    <div class="form-group">
                        <label>Enter the new target page name to update all links and redirects:</label>
                        <input type="text" id="new-target-input" class="form-control" placeholder="Enter new target">
                    </div>
                `, function () {
                    decisions.links = $('#new-target-input').val();
                    confirmDeletion(pageTitle, decisions);
                });
            } else {
                decisions.links = '';
                confirmDeletion(pageTitle, decisions);
            }
        });
    }

    function confirmDeletion(pageTitle, decisions) {
        showModal('Confirm Page Deletion', `
            <p>Are you sure you want to delete "${pageTitle}" after handling all links and redirects?</p>
        `, function () {
            decisions.deletion = true;
            showLoadingDialog('Performing Cleanup', function (updateLoadingText) {
                executeAllActions(pageTitle, decisions, function () {
                    location.reload();
                }, updateLoadingText);
            });
        });
    }

    function showModal(title, body, onConfirm) {
        var modal = $(`
            <div class="modal fade" tabindex="-1" role="dialog">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${title}</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            ${body}
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary">Confirm</button>
                        </div>
                    </div>
                </div>
            </div>
        `);

        modal.find('.btn-primary').click(function () {
            onConfirm();
            modal.modal('hide');
        });

        modal.on('hidden.bs.modal', function () {
            modal.remove();
        });

        $('body').append(modal);
        modal.modal('show');
    }

    function showLoadingDialog(message, callback) {
        var modal = $(`
            <div class="modal fade" tabindex="-1" role="dialog">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Performing Cleanup</h5>
                        </div>
                        <div class="modal-body">
                            <p id="loading-text">${message}</p>
                        </div>
                    </div>
                </div>
            </div>
        `);

        $('body').append(modal);
        modal.modal('show');

        callback(function (text) {
            $('#loading-text').text(text);
            console.log(text); // Log progress
        });
    }

    function executeAllActions(pageTitle, decisions, callback, updateLoadingText) {
        var api = new mw.Api();

        function handleLinksAndRedirects(action, newTarget, next) {
            updateLoadingText(action === 'update' ? 'Updating all links and redirects...' : 'Removing all links and redirects...');
            api.get({
                action: 'query',
                list: 'backlinks',
                bltitle: pageTitle,
                bllimit: 'max'
            }).done(function (data) {
                if (data.query.backlinks) {
                    var promises = data.query.backlinks.map(function (link) {
                        return new Promise(function (resolve) {
                            if (action === 'update') {
                                updateLink(link.title, newTarget, api).then(resolve);
                            } else {
                                removeLink(link.title, api).then(resolve);
                            }
                        });
                    });
                    Promise.all(promises).then(function () {
                        updateLoadingText(action === 'update' ? 'All links and redirects updated.' : 'All links and redirects removed.');
                        next();
                    });
                } else {
                    next();
                }
            }).fail(function (error) {
                console.error('Error fetching backlinks:', error);
                updateLoadingText('Error fetching backlinks: ' + error);
                next();
            });
        }

        function updateLink(pageTitle, newTarget, api) {
            return api.postWithToken('csrf', {
                action: 'edit',
                title: pageTitle,
                text: '#REDIRECT [[' + newTarget + ']]',
                summary: 'Updated redirect to new target [[' + newTarget + ']]'
            }).fail(function (error) {
                console.error('Error updating link:', error);
            });
        }

        function removeLink(pageTitle, api) {
            return api.postWithToken('csrf', {
                action: 'edit',
                title: pageTitle,
                text: '',
                summary: 'Removed link to [[' + pageTitle + ']]'
            }).fail(function (error) {
                console.error('Error removing link:', error);
            });
        }

        function performDeletion(pageTitle, next) {
            updateLoadingText('Deleting the page...');
            api.postWithToken('csrf', {
                action: 'delete',
                title: pageTitle,
                reason: 'Automated clean delete by admin'
            }).done(function () {
                updateLoadingText('Page deleted.');
                next();
            }).fail(function (error) {
                console.error('Error during clean deletion:', error);
                updateLoadingText('Error during clean deletion: ' + error);
                next();
            });
        }

        var tasks = [
            function (resolve) {
                if (decisions.links === '') {
                    handleLinksAndRedirects('remove', '', resolve);
                } else {
                    handleLinksAndRedirects('update', decisions.links, resolve);
                }
            },
            function (resolve) {
                if (decisions.deletion) {
                    performDeletion(pageTitle, resolve);
                } else {
                    resolve();
                }
            }
        ];

        (function executeTasks(i) {
            if (i < tasks.length) {
                tasks[i](function () {
                    executeTasks(i + 1);
                });
            } else {
                callback();
            }
        })(0);
    }

    mw.hook('wikipage.content').add(addCleanDeleteLink);
});
This page was edited 146 days ago on 08/26/2024. What links here