User:MGA73/information.js
Appearance
Note: After saving, changes may not occur immediately. Click here to learn how to bypass your browser's cache.
- Mozilla / Firefox / Safari: hold down Shift while clicking Reload, or press Ctrl-Shift-R (Cmd-Shift-R on Apple Mac);
- Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5;
- Konqueror: simply click the Reload button, or press F5;
- Opera users may need to completely clear their cache in Tools→Preferences.
Warning: Malicious code can compromise your account. Page preview will cause your web browser to execute this page's content as code under some skins, including Monobook. If you have any questions about any code you plan to add, you can ask at the appropriate reading room. |
Documentation for this user script can be added at User:MGA73/information. |
$(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('Adding Information template');
}
}
});