Prijeđi na sadržaj

Suradnik:MGA73/FileDelinker.js

Izvor: Wikipedija

Napomena: Nakon objave možda ćete trebati očistiti međuspremnik svog preglednika kako biste vidjeli promjene.

  • Firefox / Safari: držite Shift i pritisnite Reload, ili pritisnite bilo Ctrl-F5 ili Ctrl-R (⌘-R na Macu)
  • Google Chrome: pritisnite Ctrl-Shift-R (⌘-Shift-R na Macu)
  • Internet Explorer / Edge: držite Ctrl i kliknite Refresh, ili pritisnite Ctrl-F5
  • Opera: pritisnite Ctrl-F5.
mw.loader.using(['oojs-ui', 'mediawiki.api', 'mediawiki.util']).then(function () {
  $(function () {
    if (mw.config.get('wgNamespaceNumber') !== 6) return;

    function getLocalFileUsage(fileName) {
      return new mw.Api().get({
        action: 'query',
        prop: 'fileusage',
        titles: fileName,
        fulimit: 'max',
        format: 'json'
      }).then(function (data) {
        var pages = [];
        Object.values(data.query.pages).forEach(function (page) {
          if (page.fileusage) {
            pages = pages.concat(page.fileusage.map(function (usage) {
              return usage.title;
            }));
          }
        });
        return pages;
      });
    }

    function removeFileReferences(content, fileName) {
      const normalizedName = fileName.replace(/ /g, '[ _]');
      const escapedName = normalizedName.replace(/[-\\/\\^$*+?.()|[\\]{}]/g, '\\$&');
      const fileRegex = new RegExp('\\[\\[(File|Skeda|Datei|Faili|Datoteka|Figura|चित्र)[:/]?' + escapedName + '(\\|[^\\]]*)*\\]\\]', 'gim');
      const gallerySectionRegex = /<gallery>([\s\S]*?)<\/gallery>/gi;
      const infoboxRegexWithBrackets = new RegExp('(\\|\\s*[^=]+?=\\s*)\\[\\[(File|Skeda|Datei|Datoteka|Faili|Figura|चित्र)[:/]?' + escapedName + '(\\|[^\\]]*)?\\]\\]', 'gim');
      const infoboxRegex = new RegExp('(\\|\\s*[^=]+\\s*=\\s*)' + escapedName + '([\u200E\u200F\\s]*)', 'gim');

      let updatedContent = content;
      updatedContent = updatedContent.replace(gallerySectionRegex, (match, galleryContent) => {
        const updatedGallery = galleryContent.split('\n').filter(line => !line.includes(fileName)).join('\n');
        return `<gallery>${updatedGallery}</gallery>`;
      });
      updatedContent = updatedContent.replace(infoboxRegexWithBrackets, (match, before) => before);
      updatedContent = updatedContent.replace(infoboxRegex, (match, beforeEquals, afterEquals) => beforeEquals + '' + afterEquals);
      updatedContent = updatedContent.replace(fileRegex, '');
      return updatedContent;
    }

    function removeLinksFromPageAndSave(page, fileName) {
      new mw.Api().get({
        action: 'query',
        prop: 'revisions',
        titles: page,
        rvslots: 'main',
        rvprop: 'content',
        format: 'json'
      }).then(function (data) {
        const pageContent = Object.values(data.query.pages)[0].revisions[0].slots.main['*'];
        const updatedContent = removeFileReferences(pageContent, fileName);
        if (updatedContent === pageContent) return;
        new mw.Api().postWithEditToken({
          action: 'edit',
          title: page,
          text: updatedContent,
          summary: 'Removing references to [[File:' + fileName + ']] (no license)'
        });
      });
    }

    function nominateFileForDeletion(fileName) {
      const pageTitle = 'File:' + fileName;
      new mw.Api().get({
        action: 'query',
        prop: 'revisions',
        titles: pageTitle,
        rvslots: 'main',
        rvprop: 'content',
        format: 'json'
      }).then(function (data) {
        const page = Object.values(data.query.pages)[0];
        const currentContent = page.revisions?.[0]?.slots?.main?.['*'] || '';//<nowiki>
        const deletionTag = '\n\n{{subst:Brisati|No license}}';//</nowiki>
        const newContent = currentContent + deletionTag;

        new mw.Api().postWithEditToken({
          action: 'edit',
          title: pageTitle,
          text: newContent,
          summary: 'Nominating file for deletion: No license - pages that linked to this file has been delinked.'
        });
      });
    }

    var button = new OO.ui.ButtonWidget({ label: 'Delink file', icon: 'unlink', flags: ['progressive'] });
    var pageCountLabel = new OO.ui.LabelWidget({ label: ' (0 pages)', classes: ['page-count-label'] });

    $('#mw-content-text').prepend($('<div>').css('margin-bottom', '10px').append($('<div>').append(button.$element, pageCountLabel.$element)));

   button.on('click', function () {
      var fileName = mw.config.get('wgTitle');
      button.setDisabled(true);

      getLocalFileUsage('File:' + fileName).then(function (pages) {
         pageCountLabel.setLabel(' (' + pages.length + ' pages)');

         // Always nominate the file for deletion
         nominateFileForDeletion(fileName);

         // If file is used, delink from all pages
         if (pages.length > 0) {
            pages.forEach(page => removeLinksFromPageAndSave(page, fileName));
            alert('Links removed and file nominated for deletion.');
         } else {
            alert('File nominated for deletion.');
         }
      }).catch(function (error) {
         console.error('Error fetching file usage:', error);
         alert('An error occurred while fetching file usage.');
      }).finally(function () {
         button.setDisabled(false);
      });
   });

    var fileName = mw.config.get('wgTitle');
    getLocalFileUsage('File:' + fileName).then(function (pages) {
      pageCountLabel.setLabel(' (' + pages.length + ' pages)');
    });
  });
});