Zum Inhalt springen

Benutzer:MGA73/information.js

Aus Wikibooks

Hinweis: Leere nach dem Veröffentlichen den Browser-Cache, um die Änderungen sehen zu können.

  • Firefox/Safari: Umschalttaste drücken und gleichzeitig Aktualisieren anklicken oder entweder Strg+F5 oder Strg+R (⌘+R auf dem Mac) drücken
  • Google Chrome: Umschalttaste+Strg+R (⌘+Umschalttaste+R auf dem Mac) drücken
  • Edge: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
$(document).ready(function() {
    // Only run this script on File pages
    if (mw.config.get('wgNamespaceNumber') === 6) {

        // Function to fetch pages that use the file
        function fetchFileUsage() {
            var fileName = mw.config.get('wgPageName').replace(/^(File|Datei):/, ''); // Get the file name without prefix

            // Fetch pages that use the file via the imageusage API
            var api = new mw.Api();
            api.get({
                action: 'query',
                list: 'imageusage',
                iutitle: 'File:' + fileName,
                iulimit: 10, // Limit to 10 results for now (can adjust as needed)
                format: 'json'
            }).done(function(data) {
                console.log("File usage data: ", data); // Log the usage data

                var usagePages = data.query.imageusage.map(function(usage) {
                    return `[[${usage.title}|${usage.title}]]`; // Format the pages using the file
                }).join(', ');

                // Check if we found any pages using the file
                if (usagePages) {
                    // Add the usage information to the edit text
                    insertInformationTemplate(usagePages);
                } else {
                    console.log("No pages found using this file.");
                    insertInformationTemplate(""); // No pages using the file
                }
            }).fail(function(error) {
                console.error("Error fetching file usage: ", error); // Log error if API request fails
            });
        }

        // Function to open the edit page and insert the Information template
        function insertInformationTemplate(usagePages) {
            console.log("Inserting Information template");

            var fileName = mw.config.get('wgPageName').replace(/^(File|Datei):/, ''); // File name without prefix

            var api = new mw.Api();
            api.get({
                action: 'query',
                titles: 'File:' + fileName,
                prop: 'imageinfo',
                iiprop: 'user|comment', // Get uploader and comment
                format: 'json'
            }).done(function(data) {
                var page = Object.values(data.query.pages)[0]; // Get the first page

                if (page.imageinfo && page.imageinfo[0]) {
                    var content = page.imageinfo[0].comment || ''; // Get the content (or empty if not available)

                    // Use the uploader's name instead of the editor's
                    var uploader = page.imageinfo[0].user;

                    // Now fetch the actual description content (not upload comment)
                    api.get({
                        action: 'query',
                        titles: 'File:' + fileName,
                        prop: 'revisions', // Fetch page content from the revisions
                        rvprop: 'content', // Get the content of the page
                        format: 'json'
                    }).done(function(data) {
                        var pageContent = Object.values(data.query.pages)[0].revisions[0]['*']; // The actual file page content

                        // Find the license in the content
                        var licenseMatch = pageContent.match(/{{([^}]+)}}/);
                        var license = licenseMatch ? licenseMatch[1] : ''; // Extract license or use empty if not found

                        // Clean content: Remove headers and leading blank lines
                        var cleanedContent = pageContent
                            .replace(/==[^=]+==/g, '') // Remove headers like == Beschreibung ==
                            .replace(/{{[^}]+}}/g, '') // Remove license templates
                            .replace(/^\s+|\s+$/g, '') // Remove blank lines at start and end
                            .trim(); // Final clean-up

                        // Prepare the description text
                        var descriptionText = usagePages
                            ? `${usagePages}: ${cleanedContent}` // Include usage pages and cleaned content
                            : cleanedContent; // No pages, just cleaned content

                        // Build the Information template dynamically
                        var templateText = `== {{int:filedesc}} ==
{{Information
|Description    = ${descriptionText}
|Source         = {{own}}
|Date           = 
|Author         = [[User:${uploader}|${uploader}]]
|Permission     = 
|other_versions = 
}}

== {{int:license-header}} ==
{{${license}}}`;

                        // Redirect to the edit page with the template and edit summary
                        var editUrl = mw.util.getUrl(mw.config.get('wgPageName'), { action: 'edit', templateText: encodeURIComponent(templateText) });
                        window.location.href = editUrl; // Redirect to the edit page
                    }).fail(function(error) {
                        console.error("Error fetching page content: ", error); // Log error if API request fails
                    });
                }
            }).fail(function(error) {
                console.error("Error fetching uploader data: ", error); // Log error if API request fails
            });
        }

        // Add the "Information" button to the page
        var $button = $('<button>')
            .text('[Information]')
            .css({
                backgroundColor: '#007BFF',
                color: '#FFFFFF',
                border: '1px solid #007BFF',
                borderRadius: '3px',
                padding: '5px 10px',
                cursor: 'pointer',
                margin: '5px'
            })
            .click(function(event) {
                event.preventDefault(); // Prevent default button behavior
                fetchFileUsage(); // Fetch the file usage and then proceed
            });

        // Add the button to the page (below the page title)
        $('#contentSub').append($button);

        // Automatically insert the Information template and edit summary if the page is in edit mode
        var urlParams = new URLSearchParams(window.location.search);
        if (mw.config.get('wgAction') === 'edit' && urlParams.has('templateText')) {
            var templateText = decodeURIComponent(urlParams.get('templateText'));
            var editBox = $('#wpTextbox1');
            editBox.val(templateText);

            // Set the edit summary
            $('#wpSummary').val('Hinzufügen der Information-Vorlage');
        }
    }
});