User:Qwerfjkl/scripts/massXFD.js: Difference between revisions

Content deleted Content added
English date [Factotum]
m (via CAE)
 
(21 intermediate revisions by the same user not shown)
Line 1:
// <nowiki>
// TFD:
// Cat support (when emptying a cat of templates)
// oldtfdlist for previous TfDs
// notify Twinkle/UV/AWB
 
 
// todo: make counter inline, remove progresss and progressElement from editPAge(), more dynamic reatelimit wait.
// counter semi inline; adjust align in createProgressBar()
// Function to wipe the text content of the page inside #bodyContent
 
(function capitalise(s) {
return s[0].toUpperCase() + s.slice(1);
}
 
function capitalise(s) {
var XFDconfig = {
return s[0].toUpperCase() + s.slice(1);
"CFD": {
}
"title": "Mass CfD",
 
"placeholderDiscussionLink": 'Wikipedia:Categories for discussion/Log/2023 July 23#Category:Archaeological cultures by ethnic group',
const NS_TEMPLATE = 10;
"placeholderNominationTitle": 'Archaeological cultures by ethnic group',
const NS_CATEGORY = 14;
"placeholderRationale": '[[WP:DEFINING|Non-defining]] category.',
const NS_MODULE = 828;
"pageDemoText": "{{subst:Cfd|Category:Bishops}}",
 
"discussionLinkRegex": /^Wikipedia:Categories for discussion\/Log\/\d\d\d\d \w+ \d\d?#(.+)$/,
 
"userNotificationTemplate": 'Cfd mass notice',
var XFDconfig = {
"baseDiscussionPage": 'Wikipedia:Categories for discussion/Log/',
"CFD": {
"normaliseFunction": (title) => {return 'Category:' + capitalise(title.replace(/^ *[Cc]ategory:/, '').trim());},
"actionstitle": "Mass {CfD",
"placeholderDiscussionLink": 'Wikipedia:Categories for discussion/Log/2023 July 23#Category:Archaeological cultures by ethnic group',
"Delete": {
"placeholderNominationTitle": 'Archaeological cultures by ethnic group',
'prepend': '{{subst:Cfd|${sectionName}}}',
"placeholderRationale": '[[WP:DEFINING|Non-defining]] category.',
'action': 'deleting'
"pageDemoText": "{{subst:Cfd|sectionName}}",
"titleDemoText": "Category:FirstNominatedCategory|Category:FirstNominatedCategoryTarget1|Category:Target2\nCategory:Foo|Category:Bar\nCategory:Earth",
"discussionLinkRegex": /^Wikipedia:Categories for discussion\/Log\/\d\d\d\d \w+ \d\d?#(.+)$/,
"nominationReplacement": [/==== ?NEW NOMINATIONS ?====\s*(?:<!-- ?Please add the newest nominations below this line ?-->)?/, '$&\n\n${nominationText}'],
"userNotificationTemplate": 'Cfd mass notice',
"baseDiscussionPage": 'Wikipedia:Categories for discussion/Log/',
"normaliseFunction": (title) => { return (new mw.Title(title, NS_CATEGORY)).getPrefixedText() },
"actions": {
"Delete": {
'prepend': '{{subst:Cfd|${sectionName}}}',
'action': 'deleting'
},
"Rename": {
'prepend': '{{subst:Cfr|$1|${sectionName}}}',
'action': 'renaming'
},
"Merge": {
'prepend': '{{subst:Cfm|$1|${sectionName}}}',
'action': 'merging'
},
"Split": {
'prepend': '{{subst:Cfs|$1|$2|${sectionName}}}',
'action': 'splitting'
},
"Listify": {
'prepend': '{{subst:Cfl|$1|${sectionName}}}',
'action': 'listifying'
},
"Custom": {
'prepend': '{{subst:Cfd|type=|${sectionName}}}',
'action': ''
},
},
"RenamedisplayTemplates": [{
'prepend': '{{subst:Cfr|$1|${sectionName}}}',
'action': 'renaming'
},
"Merge": {
'prepend': '{{subst:Cfm|$1|${sectionName}}}',
'action': 'merging'
},
"Split": {
'prepend': '{{subst:Cfs|$1|$2|${sectionName}}}',
'action': 'splitting'
},
"Listify": {
'prepend': '{{subst:Cfl|$1|${sectionName}}}',
'action': 'listifying'
},
"Custom": {
'prepend': '{{subst:Cfd|type=|${sectionName}}}',
'action': ''
},
},
"displayTemplates": [{
data: 'lc',
label: 'Category link with extra links – {{lc}}'
Line 57 ⟶ 71:
label: 'Plain category link – {{cl}}'
}],
 
},
"RFD": {
"title": "Mass RfD",
"placeholderDiscussionLink": 'Wikipedia:Redirects for discussion/Log/2024 May 13#Knightfall (comics)',
"placeholderNominationTitle": 'Knightfall',
"placeholderRationale": 'No mention of "Knightfall" in the target article.',
"pageDemoText": "",
"discussionLinkRegex": /^Wikipedia:Redirects for discussion\/Log\/\d\d\d\d \w+ \d\d?#(.+)$/,
"userNotificationTemplate": 'Rfd mass notice',
"baseDiscussionPage": 'Wikipedia:Redirects for discussion/Log/',
"normaliseFunction": (title) => {return capitalise(title.trim())},
"actions":
{
'prepend': '{{subst:rfd|${sectionName}|content=\n${pageText}\n}}'
},
"RFD": {
"displayTemplate": "{{subst:rfd2|multi=yes|redirect=${pageName}|target={{subst:target of|${pageName}}}}}"
"title": "Mass RfD",
"placeholderDiscussionLink": 'Wikipedia:Redirects for discussion/Log/2024 May 13#Knightfall (comics)',
"placeholderNominationTitle": 'Knightfall',
"placeholderRationale": 'No mention of "Knightfall" in the target article.',
"pageDemoText": "",
"titleDemoText": "Title1\nTitle2\nTitle2",
"discussionLinkRegex": /^Wikipedia:Redirects for discussion\/Log\/\d\d\d\d \w+ \d\d?#(.+)$/,
"nominationReplacement": [/<!-- ?Add new entries directly below this line\. ?-->/, '$&\n${nominationText}\n'],
"userNotificationTemplate": 'Rfd mass notice',
"baseDiscussionPage": 'Wikipedia:Redirects for discussion/Log/',
"normaliseFunction": (title) => { return new mw.Title(title).getPrefixedText() },
"actions":
{
'prepend': '{{subst:rfd|${sectionName}|content=\n${pageText}\n}}'
},
"displayTemplate": "{{subst:rfd2|multi=yes|redirect=${pageName}|target=${redirectTarget}}}"
},
"TFD": {
"title": "Mass TfD",
"placeholderDiscussionLink": 'Wikipedia:Templates for discussion/Log/2025 August 4#Template:COVID-19 pandemic interactive maps/India/India cases',
"placeholderNominationTitle": 'COVID-19 pandemic interactive maps/India templates',
"placeholderRationale": 'Unused templates.',
"pageDemoText": "{{subst:Tfd|sectionName}}",
"titleDemoText": "Template:Foo\nTemplate:Bar",
"discussionLinkRegex": /^Wikipedia:Templates for discussion\/Log\/\d\d\d\d \w+ \d\d?#(.+)$/,
"nominationReplacement": [/=== ?\[\[Wikipedia:Templates for discussion\/Log\/\d\d\d\d \w+ \d\d?\|\w+ \d\d?\]\] ?===\s*(?:<!-- *Add new listings at the top of the list with the following formats for deletion and merging respectively:[\s\S]+?-->)?/, '$&\n${nominationText}'],
"userNotificationTemplate": 'Tfd mass notice',
"baseDiscussionPage": 'Wikipedia:Templates for discussion/Log/',
"normaliseFunction": (title) => {
let titleObj = new mw.Title(title);
if (titleObj.getNamespaceId() != 0) {
return titleObj.getPrefixedText()
} else {
return new mw.Title(title, NS_TEMPLATE).getPrefixedText(); // assume Template:
}
},
"actions": {
"Delete": {
'prepend': '{{subst:Tfd|heading=${sectionName}}}',
'action': 'deleting'
},
"Delete (inline notice)": {
'prepend': '{{subst:Tfd|type=inline|heading=${sectionName}}}',
'action': 'deleting'
},
"Delete (tiny notice)": {
'prepend': '{{subst:Tfd|type=tiny|heading=${sectionName}}}',
'action': 'deleting'
},
"Delete (sidebar notice)": {
'prepend': '{{subst:Tfd|type=sidebar|heading=${sectionName}}}',
'action': 'deleting'
},
"Delete (disabled notice)": {
'prepend': '{{subst:Tfd|type=disabled|heading=${sectionName}}}',
'action': 'deleting'
},
"Merge": {
'prepend': '{{subst:Tfm|$1|heading=${sectionName}}}}',
'action': 'merging'
},
"Merge (inline notice)": {
'prepend': '{{subst:Tfm|$1|type=inline|heading=${sectionName}}}',
'action': 'merging'
},
"Merge (tiny notice)": {
'prepend': '{{subst:Tfm|$1|type=tiny|heading=${sectionName}}}',
'action': 'merging'
},
"Merge (sidebar notice)": {
'prepend': '{{subst:Tfm|$1|type=sidebar|heading=${sectionName}}}',
'action': 'merging'
},
"Merge (disabled notice)": {
'prepend': '{{subst:Tfm|$1|type=disabled|heading=${sectionName}}}',
'action': 'merging'
},
"Custom delete": {
'prepend': '{{subst:Tfd|type=|heading=${sectionName}}}',
'action': ''
},
"Custom merge": {
'prepend': '{{subst:Tfm|$1|type=|heading=${sectionName}}}',
'action': ''
},
},
"displayTemplate": "{{Tfd links|${pageName}${moduleText}}}"
},
};
const match = /Special:Mass(\w+)/.exec(mw.config.get('wgPageName'));
const XFD = match ? match[1].toUpperCase() : false;
const config = XFDconfig[XFD];
 
function wipePageContent() {
var bodyContent = $('#bodyContent');
if (bodyContent) {
bodyContent.empty();
}
var header = $('#firstHeading');
};
if (header) {
const match = /Special:Mass(\w+)/.exec(mw.config.get('wgPageName'));
header.text(config.title);
const XFD = match ? match[1].toUpperCase() : false;
}
const config = XFDconfig[XFD];
$('title').text(`${config.title} - Wikipedia`);
}
 
function wipePageContentcreateProgressElement() {
var progressContainer = new OO.ui.PanelLayout({
var bodyContent = $('#bodyContent');
padded: true,
if (bodyContent) {
bodyContent.empty(); expanded: false,
classes: ['sticky-container']
});
return progressContainer;
}
 
var header = $('#firstHeading');
iffunction makeInfoPopup(headerinfo) {
var infoPopup = new OO.ui.PopupButtonWidget({
header.text(config.title);
icon: 'info',
framed: false,
label: 'More information',
invisibleLabel: true,
popup: {
head: true,
icon: 'infoFilled',
label: 'More information',
$content: $(`<p>${info}</p>`),
padded: true,
align: 'force-left',
autoFlip: false
}
});
return infoPopup;
}
 
$('title').text(`${config.title} - Wikipedia`);
function makeCategoryTemplateDropdown(label) {
}
var dropdown = new OO.ui.DropdownInputWidget({
required: true,
function createProgressElement() {
options: config.displayTemplates
var progressContainer = new OO.ui.PanelLayout({
padded: true,
expanded: false,
classes: ['sticky-container']
});
var fieldlayout = new OO.ui.FieldLayout(
return progressContainer;
dropdown,
}
{
label,
function makeInfoPopup (info) {
align: 'inline',
var infoPopup = new OO.ui.PopupButtonWidget( {
icon classes: ['infonewnomonly'],
framed: false, }
label: 'More information',);
return { invisibleLabelcontainer: truefieldlayout, dropdown };
popup: {}
 
head: true,
function createTitleAndInputFieldWithLabel(label, placeholder, classes = []) {
icon: 'infoFilled',
var input = new label: 'More information',OO.ui.TextInputWidget({
$content: $( `<p>${info}</p>` ),placeholder
padded: true,
align: 'force-left',
autoFlip: false
}
} );
return infoPopup;
}
function makeCategoryTemplateDropdown (label) {
var dropdown = new OO.ui.DropdownInputWidget( {
required: true,
options: config.displayTemplates
} );
var fieldlayout = new OO.ui.FieldLayout(
dropdown,
{ label,
align: 'inline',
classes: ['newnomonly'],
}
);
return {container: fieldlayout, dropdown};
}
function createTitleAndInputFieldWithLabel(label, placeholder, classes=[]) {
var input = new OO.ui.TextInputWidget( {
placeholder
} );
var fieldset = new OO.ui.FieldsetLayout( {
classes
} );
fieldset.addItems( [
new OO.ui.FieldLayout( input, {
label
} ),
] );
return {
container: fieldset,
inputField: input,
};
}
// Function to create a title and an input field
function createTitleAndInputField(title, placeholder, info = false) {
var container = new OO.ui.PanelLayout({
expanded: false
});
var titleLabel = new OO.ui.LabelWidget({
label: $(`<span>${title}</span>`)
});
var infoPopup = makeInfoPopup(info);
var inputField = new OO.ui.MultilineTextInputWidget({
placeholder,
indicator: 'required',
rows: 10,
autosize: true
});
if (info) container.$element.append(titleLabel.$element, infoPopup.$element, inputField.$element);
else container.$element.append(titleLabel.$element, inputField.$element);
return {
titleLabel,
inputField,
container,
infoPopup,
};
}
// Function to create a title and an input field
function createTitleAndSingleInputField(title, placeholder) {
var container = new OO.ui.PanelLayout({
expanded: false
});
var titleLabel = new OO.ui.LabelWidget({
label: title
});
var inputField = new OO.ui.TextInputWidget({
placeholder,
indicator: 'required'
});
container.$element.append(titleLabel.$element, inputField.$element);
return {
titleLabel,
inputField,
container
};
}
function createStartButton() {
var button = new OO.ui.ButtonWidget({
label: 'Start',
flags: ['primary', 'progressive']
});
 
 
return button;
var fieldset = new OO.ui.FieldsetLayout({
}
classes
function createAbortButton() {
var button = new OO.ui.ButtonWidget({
label: 'Abort',
flags: ['primary', 'destructive']
});
return button;
}
function createRemoveBatchButton() {
var button = new OO.ui.ButtonWidget( {
label: 'Remove',
icon: 'close',
title: 'Remove',
classes: [
'remove-batch-button'
],
flags: [
'destructive'
]
} );
return button;
}
function createNominationToggle() {
 
fieldset.addItems([
var newNomToggle = new OO.ui.ButtonOptionWidget( {
new OO.ui.FieldLayout(input, data: 'new',{
label: 'New nomination',
selected: true}),
} ]);
 
var oldNomToggle = new OO.ui.ButtonOptionWidget( {
return data: 'old',{
labelcontainer: 'Old nomination'fieldset,
}inputField: );input,
};
}
var toggle = new OO.ui.ButtonSelectWidget( {
// Function to create a title and an input field
items: [
function createTitleAndInputField(title, placeholder, info = false) {
var container = new OO.ui.PanelLayout({
expanded: false
});
 
var titleLabel = new OO.ui.LabelWidget({
label: $(`<span>${title}</span>`)
});
 
var infoPopup = makeInfoPopup(info);
var inputField = new OO.ui.MultilineTextInputWidget({
placeholder,
indicator: 'required',
rows: 10,
autosize: true
});
if (info) container.$element.append(titleLabel.$element, infoPopup.$element, inputField.$element);
else container.$element.append(titleLabel.$element, inputField.$element);
return {
titleLabel,
inputField,
container,
infoPopup,
};
}
 
// Function to create a title and an input field
function createTitleAndSingleInputField(title, placeholder) {
var container = new OO.ui.PanelLayout({
expanded: false
});
 
var titleLabel = new OO.ui.LabelWidget({
label: title
});
 
var inputField = new OO.ui.TextInputWidget({
placeholder,
indicator: 'required'
});
 
container.$element.append(titleLabel.$element, inputField.$element);
 
return {
titleLabel,
inputField,
container
};
}
 
function createStartButton() {
var button = new OO.ui.ButtonWidget({
label: 'Start',
flags: ['primary', 'progressive']
});
 
return button;
}
 
function createAbortButton() {
var button = new OO.ui.ButtonWidget({
label: 'Abort',
flags: ['primary', 'destructive']
});
 
return button;
}
 
function createRemoveBatchButton() {
var button = new OO.ui.ButtonWidget({
label: 'Remove',
icon: 'close',
title: 'Remove',
classes: [
'remove-batch-button'
],
flags: [
'destructive'
]
});
return button;
}
 
function createNominationToggle() {
 
var newNomToggle = new OO.ui.ButtonOptionWidget({
data: 'new',
label: 'New nomination',
selected: true
});
var oldNomToggle = new OO.ui.ButtonOptionWidget({
data: 'old',
label: 'Old nomination',
});
 
var toggle = new OO.ui.ButtonSelectWidget({
items: [
newNomToggle,
oldNomToggle
]
});
return {
toggle,
newNomToggle,
oldNomToggle,
]
} );
return {
toggle,
newNomToggle,
oldNomToggle,
};
}
 
 
function createMessageElement() {
var messageElement = new OO.ui.MessageWidget({
type: 'progress',
inline: true,
progressType: 'infinite'
});
return messageElement;
}
 
function createRatelimitMessagecreateWarningMessage() {
var ratelimitMessagewarningMessage = new OO.ui.MessageWidget({
type: 'warning',
style: 'background-color: yellow;'
});
return ratelimitMessagewarningMessage;
}
 
function createCompletedElement() {
var messageElement = new OO.ui.MessageWidget({
type: 'success',
});
return messageElement;
}
 
function createDoingElement() {
function createAbortMessage() { // pretty much a duplicate of ratelimitMessage
var abortMessagemessageElement = new OO.ui.MessageWidget({
type: 'warninginfo',
});
return abortMessagemessageElement;
}
 
function createNominationErrorMessagecreateAbortMessage() { // pretty much a duplicate of ratelimitMessage
var nominationErrorMessageabortMessage = new OO.ui.MessageWidget({
type: 'errorwarning',
});
text: 'Could not detect where to add new nomination.'
}) return abortMessage;
}
return nominationErrorMessage;
 
}
function createErrorMessage(text) {
var errorMessage = new OO.ui.MessageWidget({
function createFieldset(headingLabel) {
var fieldset = new OO.ui.FieldsetLayout({ type: 'error',
});
label: headingLabel,
errorMessage.setLabel(text);
return errorMessage;
}
 
function createNominationErrorMessage() { // pretty much a duplicate of ratelimitMessage
return createErrorMessage('Could not detect where to add new nomination.')
}
 
function createFieldset(headingLabel) {
var fieldset = new OO.ui.FieldsetLayout({
label: headingLabel,
});
return fieldset;
}
 
function createCheckboxWithLabel(label) {
var checkbox = new OO.ui.CheckboxInputWidget({
value: 'a',
selected: true,
label: "Foo",
data: "foo"
});
var fieldlayout = new OO.ui.FieldLayout(
checkbox,
{
label,
align: 'inline',
selected: true
}
);
return {
fieldlayout,
checkbox
};
}
function createMenuOptionWidget(data, label) {
var menuOptionWidget = new OO.ui.MenuOptionWidget({
data,
label
});
return menuOptionWidget;
}
function createActionDropdown() {
var items = Object.keys(config.actions)
.map(action => [action, action]) // [label, data]
.map(action => createMenuOptionWidget(...action));
 
var dropdown = new OO.ui.DropdownWidget({
label: 'Mass action',
menu: {
items
}
});
return { dropdown };
}
 
function createMultiOptionButton() {
var button = new OO.ui.ButtonWidget({
label: 'Additional action',
icon: 'add',
flags: [
'progressive'
]
});
return button;
}
 
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
 
function makeLink(title) {
return `<a href="/wiki/${title}" target="_blank">${title}</a>`;
}
 
function getDateDifference(date1) {
const currentDate = new Date();
// now
let date2 = `${currentDate.getUTCFullYear()} ${currentDate.toLocaleString('en', { month: 'long', timeZone: 'UTC' })} ${currentDate.getUTCDate()}`
 
// Parse the dates
const parseDate = (dateString) => {
const [year, month, day] = dateString.split(' ');
return new Date(`${year}-${month}-${day}`);
};
 
const d1 = parseDate(date1);
const d2 = parseDate(date2);
 
// Calculate the time difference in milliseconds
const timeDifference = Math.abs(d2 - d1);
 
// Convert the time difference from milliseconds to days
const dayDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));
 
return dayDifference;
}
 
function deepCopy(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
 
if (obj instanceof OO.ui.Element) {
return obj;
}
 
if (Array.isArray(obj)) {
const copy = [];
for (let i = 0; i < obj.length; i++) {
copy[i] = deepCopy(obj[i]);
}
return copy;
}
 
const copy = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepCopy(obj[key]);
}
}
return copy;
}
 
function delinkWikitext(text) {
// both piped and unpiped wikilinks
const wikilinkPattern = /\[\[([^\]]+)\|([^\]]+)\]\]|\[\[([^\]]+)\]\]/g;
 
return text.replace(wikilinkPattern, (match, p1, p2, p3) => {
if (p1 && p2) {
// If there is both link text and target (piped)
return p2; // Just return the link text
} else if (p3) {
// If there is only link text, without a target (unpiped)
return p3;
}
return match;
});
}
 
function parseHTML(html) {
// Create a temporary div to parse the HTML
var tempDiv = $('<div>').html(html);
 
// Find all li elements
var liElements = tempDiv.find('li');
 
// Array to store extracted hrefs
var hrefs = [];
 
let existinghrefRegexp = /^https:\/\/en\.wikipedia.org\/wiki\/([^?&]+?)$/;
let nonexistinghrefRegexp = /^https:\/\/en\.wikipedia\.org\/w\/index\.php\?title=([^&?]+?)&action=edit&redlink=1$/;
 
// Iterate through each li element
liElements.each(function () {
// Find all anchor (a) elements within the current li
let hrefline = [];
var anchorElements = $(this).find('a');
 
// Extract href attribute from each anchor element
anchorElements.each(function () {
var href = $(this).attr('href');
if (href) {
var existingMatch = existinghrefRegexp.exec(href);
var nonexistingMatch = nonexistinghrefRegexp.exec(href);
let page;
if (existingMatch) page = new mw.Title(existingMatch[1]);
if (nonexistingMatch) page = new mw.Title(nonexistingMatch[1]);
if (page && page.getNamespaceId() > -1 && !page.isTalkPage()) {
hrefline.push(page.getPrefixedText());
}
 
 
}
});
hrefs.push(hrefline);
});
 
return hrefs;
}
 
function handlepaste(widget, e) {
var types, pastedData, parsedData;
// Browsers that support the 'text/html' type in the Clipboard API (Chrome, Firefox 22+)
if (e && e.clipboardData && e.clipboardData.types && e.clipboardData.getData) {
types = e.clipboardData.types;
if (((types instanceof DOMStringList) && types.contains("text/html")) ||
($.inArray && $.inArray('text/html', types) !== -1)) {
// Extract data and pass it to callback
pastedData = e.clipboardData.getData('text/html');
 
parsedData = parseHTML(pastedData);
 
// Check if it's an empty array
if (!parsedData || parsedData.length === 0) {
// Allow the paste event to propagate for plain text or empty array
return true;
}
let confirmed = confirm('You have pasted formatted text. Do you want this to be converted into wikitext?');
if (!confirmed) return true;
processPaste(widget, pastedData);
 
// Stop the data from actually being pasted
e.stopPropagation();
e.preventDefault();
return false;
}
}
 
// Allow the paste event to propagate for plain text
return true;
}
 
function waitForPastedData(widget, savedContent) {
// If data has been processed by the browser, process it
if (widget.getValue() !== savedContent) {
// Retrieve pasted content via widget's getValue()
var pastedData = widget.getValue();
 
// Restore saved content
widget.setValue(savedContent);
 
// Call callback
processPaste(widget, pastedData);
}
// Else wait 20ms and try again
else {
setTimeout(function () {
waitForPastedData(widget, savedContent);
}, 20);
}
}
 
function processPaste(widget, pastedData) {
// Parse the HTML
var parsedArray = parseHTML(pastedData);
let stringOutput = '';
for (const pages of parsedArray) {
stringOutput += pages.join('|') + '\n';
}
widget.insertContent(stringOutput);
}
 
 
function getWikitext(pageTitle) {
var api = new mw.Api();
 
var requestData = {
"action": "query",
"format": "json",
"prop": "revisions",
"titles": pageTitle,
"formatversion": "2",
"rvprop": "content",
"rvlimit": "1",
};
return api.get(requestData).then(function (data) {
var pages = data.query.pages;
return pages[0].revisions[0].content; // Return the wikitext
}).catch(function (error) {
console.error('Error fetching wikitext:', error);
});
}
 
// function to revert edits - this is hacky, and potentially unreliable
function revertEdits() {
var revertAllCount = 0;
var revertElements = $('.massxfdundo');
if (!revertElements.length) {
$('#massxfdrevertlink').replaceWith('Reverts done.');
} else {
$('#massxfdrevertlink').replaceWith('<span><span id="revertall-text">Reverting...</span> (<span id="revertall-done">0</span> / <span id="revertall-total">' + revertElements.length + '</span> done)</span>');
 
revertElements.each(function (index, element) {
element = $(element); // jQuery-ify
var title = element.attr('data-title');
var revid = element.attr('data-revid');
revertEdit(title, revid)
.then(function () {
element.text('. Reverted.');
revertAllCount++;
$('#revertall-done').text(revertAllCount);
}).catch(function () {
element.html('. Revert failed. <a href="/wiki/Special:Diff/' + revid + '">Click here</a> to view the diff.');
});
}).promise().done(function () {
return fieldset;
$('#revertall-text').text('Reverts done.');
}
});
}
function createCheckboxWithLabel(label) {
}
var checkbox = new OO.ui.CheckboxInputWidget( {
 
value: 'a',
function revertEdit(title, revid, retry = false) {
selected: true,
var api = new mw.Api();
label: "Foo",
 
data: "foo"
} );
var fieldlayout = new OO.ui.FieldLayout(
checkbox,
{ label,
align: 'inline',
selected: true
}
);
return {
fieldlayout,
checkbox
};
}
function createMenuOptionWidget(data, label) {
var menuOptionWidget = new OO.ui.MenuOptionWidget( {
data,
label
} );
return menuOptionWidget;
}
function createActionDropdown() {
var items = Object.keys(config.actions)
.map(action => [action, action]) // [label, data]
.map(action => createMenuOptionWidget(... action));
 
var dropdown = new OO.ui.DropdownWidgetif (retry) {
label: 'Mass action', sleep(1000);
menu: {
items
}
 
} );
var requestData = {
return {dropdown};
action: 'edit',
}
title,
undo: revid,
function createMultiOptionButton() {
format: 'json'
var button = new OO.ui.ButtonWidget( {
label: 'Additional action',
icon: 'add',
flags: [
'progressive'
]
} );
return button;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function makeLink(title) {
return `<a href="/wiki/${title}" target="_blank">${title}</a>`;
}
function parseHTML(html) {
// Create a temporary div to parse the HTML
var tempDiv = $('<div>').html(html);
// Find all li elements
var liElements = tempDiv.find('li');
// Array to store extracted hrefs
var hrefs = [];
let existinghrefRegexp = /^https:\/\/en\.wikipedia.org\/wiki\/([^?&]+?)$/;
let nonexistinghrefRegexp = /^https:\/\/en\.wikipedia\.org\/w\/index\.php\?title=([^&?]+?)&action=edit&redlink=1$/;
// Iterate through each li element
liElements.each(function () {
// Find all anchor (a) elements within the current li
let hrefline = [];
var anchorElements = $(this).find('a');
// Extract href attribute from each anchor element
anchorElements.each(function () {
var href = $(this).attr('href');
if (href) {
var existingMatch = existinghrefRegexp.exec(href);
var nonexistingMatch = nonexistinghrefRegexp.exec(href);
let page;
if (existingMatch) page = new mw.Title(existingMatch[1]);
if (nonexistingMatch) page = new mw.Title(nonexistingMatch[1]);
if (page && page.getNamespaceId() > -1 && !page.isTalkPage()) {
hrefline.push(page.getPrefixedText());
}
}
});
hrefs.push(hrefline);
});
return hrefs;
}
function handlepaste(widget, e) {
var types, pastedData, parsedData;
// Browsers that support the 'text/html' type in the Clipboard API (Chrome, Firefox 22+)
if (e && e.clipboardData && e.clipboardData.types && e.clipboardData.getData) {
// Check for 'text/html' in types list
types = e.clipboardData.types;
if (((types instanceof DOMStringList) && types.contains("text/html")) ||
($.inArray && $.inArray('text/html', types) !== -1)) {
// Extract data and pass it to callback
pastedData = e.clipboardData.getData('text/html');
parsedData = parseHTML(pastedData);
// Check if it's an empty array
if (!parsedData || parsedData.length === 0) {
// Allow the paste event to propagate for plain text or empty array
return true;
}
let confirmed = confirm( 'You have pasted formatted text. Do you want this to be converted into wikitext?' );
if (!confirmed) return true;
processPaste(widget, pastedData);
// Stop the data from actually being pasted
e.stopPropagation();
e.preventDefault();
return false;
}
}
// Allow the paste event to propagate for plain text
return true;
}
function waitForPastedData(widget, savedContent) {
// If data has been processed by the browser, process it
if (widget.getValue() !== savedContent) {
// Retrieve pasted content via widget's getValue()
var pastedData = widget.getValue();
// Restore saved content
widget.setValue(savedContent);
// Call callback
processPaste(widget, pastedData);
}
// Else wait 20ms and try again
else {
setTimeout(function () {
waitForPastedData(widget, savedContent);
}, 20);
}
}
function processPaste(widget, pastedData) {
// Parse the HTML
var parsedArray = parseHTML(pastedData);
let stringOutput = '';
for (const pages of parsedArray) {
stringOutput += pages.join('|')+'\n';
}
widget.insertContent(stringOutput);
}
function getWikitext(pageTitle) {
var api = new mw.Api();
var requestData ={
"action": "query",
"format": "json",
"prop": "revisions",
"titles": pageTitle,
"formatversion": "2",
"rvprop": "content",
"rvlimit": "1",
};
return api.get(requestData).then(function (data) {
var pages = data.query.pages;
return pages[0].revisions[0].content; // Return the wikitext
}).catch(function (error) {
console.error('Error fetching wikitext:', error);
});
}
// function to revert edits - this is hacky, and potentially unreliable
function revertEdits() {
var revertAllCount = 0;
var revertElements = $('.massxfdundo');
if (!revertElements.length) {
$('#massxfdrevertlink').replaceWith('Reverts done.');
} else {
$('#massxfdrevertlink').replaceWith('<span><span id="revertall-text">Reverting...</span> (<span id="revertall-done">0</span> / <span id="revertall-total">'+revertElements.length+'</span> done)</span>');
revertElements.each(function (index, element) {
element = $(element); // jQuery-ify
var title = element.attr('data-title');
var revid = element.attr('data-revid');
revertEdit(title, revid)
.then(function() {
element.text('. Reverted.');
revertAllCount++;
$('#revertall-done').text( revertAllCount );
}).catch(function () {
element.html('. Revert failed. <a href="/wiki/Special:Diff/'+revid+'">Click here</a> to view the diff.');
});
}).promise().done(function () {
$('#revertall-text').text('Reverts done.');
});
}
}
function revertEdit(title, revid, retry=false) {
var api = new mw.Api();
if (retry) {
sleep(1000);
}
var requestData = {
action: 'edit',
title,
undo: revid,
format: 'json'
};
return new Promise(function (resolve, reject) {
api.postWithEditToken(requestData).then(function (data) {
if (data.edit && data.edit.result === 'Success') {
resolve(true);
} else {
console.error('Error occurred while undoing edit:', data);
reject();
}
}).catch(function (error) {
console.error('Error occurred while undoing edit:', error); // handle: editconflict, ratelimit (retry)
if (error == 'editconflict') {
resolve(revertEdit(title, revid, retry = true));
} else if (error == 'ratelimited') {
setTimeout(function () { // wait a minute
resolve(revertEdit(title, revid, retry = true));
}, 60000);
} else {
reject();
}
});
});
});
}
function getUserData(titles) {
var api = new mw.Api();
return api.get({
action: 'query',
list: 'users',
ususers: titles,
usprop: 'blockinfo|groups', // blockinfo - check if indeffed, groups - check if bot
format: 'json'
}).then(function(data) {
return data.query.users;
}).catch(function(error) {
console.error('Error occurred while fetching page author:', error);
return false;
});
}
function getPageAuthor(title) {
var api = new mw.Api();
return api.get({
action: 'query',
prop: 'revisions',
titles: title,
rvprop: 'user',
rvdir: 'newer', // Sort the revisions in ascending order (oldest first)
rvlimit: 1,
format: 'json'
}).then(function(data) {
var pages = data.query.pages;
var pageId = Object.keys(pages)[0];
var revisions = pages[pageId].revisions;
if (revisions && revisions.length > 0) {
return revisions[0].user;
} else {
return false;
}
}).catch(function(error) {
console.error('Error occurred while fetching page author:', error);
return false;
});
}
// Function to create a list of page authors and filter duplicates
async function createAuthorList(titles) {
var authorList = [];
var promises = titles.map(function(title) {
return getPageAuthor(title);
});
try {
const authors = await Promise.all(promises);
let queryBatchSize = 50;
let authorTitles = authors.map(author => author.replace(/ /g, '_')); // Replace spaces with underscores
let filteredAuthorList = [];
for (let i = 0; i < authorTitles.length; i += queryBatchSize) {
let batch = authorTitles.slice(i, i + queryBatchSize);
let batchTitles = batch.join('|');
 
function getRedirectData(titles) {
await getUserData(batchTitles)
var api = new mw.thenApi(response => {);
return responseapi.forEachget(user => {
action: if (user'query',
titles,
&& (!user.blockexpiry || user.blockexpiry !== "infinite")
redirects: 1,
&& !user.groups.includes('bot')
format: 'json'
&& !filteredAuthorList.includes('User talk:' + user.name))
}).then(function (data) {
filteredAuthorList.push('User talk:' + user.name);
return })data.query;
}).catch(function (error) {
console.error('Error occurred while fetching page author:', error);
return false;
});
}
 
function getUserData(titles) {
})
var api = new mw.catchApi(error => {);
return api.get({
console.error("Error querying API:", error);
action: });'query',
} list: 'users',
return filteredAuthorList;ususers: titles,
usprop: 'blockinfo|groups', // blockinfo - check if indeffed, groups - check if bot
} catch (error_1) {
format: 'json'
console.error('Error occurred while creating author list:', error_1);
}).then(function (data) {
return authorList;
return data.query.users;
}
}).catch(function (error) {
}
console.error('Error occurred while fetching page author:', error);
return false;
// Function to prepend text to a page
});
function editPage(title, text, summary, progressElement, ratelimitMessage, progress, type, titlesDict, retry=false) {
var api = new mw.Api();
var messageElement = createMessageElement();
messageElement.setLabel((retry) ? $('<span>').text('Retrying ').append($(makeLink(title))) : $('<span>').text('Editing ').append($(makeLink(title))) );
progressElement.$element.append(messageElement.$element);
var container = $('.sticky-container');
container.scrollTop(container.prop("scrollHeight"));
if (retry) {
sleep(1000);
}
 
function getPageAuthor(title) {
var requestData = {
var api = new mw.Api();
action: 'edit',
title, return api.get({
summary action: 'query',
format prop: 'jsonrevisions',
titles: title,
};
rvprop: 'user',
rvdir: 'newer', // Sort the revisions in ascending order (oldest first)
if (type === 'prepend') { // cat
requestData.nocreate = 1; // don'trvlimit: create new cat1,
// parse title format: 'json'
}).then(function (data) {
var targets = titlesDict[title];
var pages = data.query.pages;
for (let i = 0; ivar <pageId targets= Object.lengthkeys(pages)[0]; i++) {
var revisions = pages[pageId].revisions;
// we add 1 to i in the replace function because placeholders start from $1 not $0
let placeholder =if '$'(revisions +&& (irevisions.length +> 10); {
 
text = text.replace(placeholder, targets[i]);
return revisions[0].user;
}
} else {
text = text.replace(/\$\d/g, ''); // remove unmatched |$x
return false;
requestData.prependtext = text.trim() + '\n\n';
}
}).catch(function (error) {
console.error('Error occurred while fetching page author:', error);
} else if (type === 'append') { // user
requestData.appendtext = '\n\n' + text.trim()return false;
} else if (type === 'text'}) {;
requestData.text = text;
}
 
return new Promise(function(resolve, reject) {
 
if (window.abortEdits) {
// Function to create a list of page authors and filter duplicates
// hide message and return
async function createAuthorList(titles) {
messageElement.toggle(false);
var authorList = resolve()[];
var promises = titles.map(function return;(title) {
return getPageAuthor(title);
});
try {
const authors = await Promise.all(promises);
let queryBatchSize = 50;
let authorTitles = authors.filter(Boolean).map(author => author.replace(/ /g, '_')); // Replace spaces with underscores, remove false values
let filteredAuthorList = [];
for (let i = 0; i < authorTitles.length; i += queryBatchSize) {
let batch = authorTitles.slice(i, i + queryBatchSize);
let batchTitles = batch.join('|');
 
await getUserData(batchTitles)
.then(response => {
response.forEach(user => {
if (window.debuggingMode) console.log(user);
if (user
&& (!user.blockexpiry || user.blockexpiry !== "infinite" || 'blockpartial' in user)
&& !user.groups?.includes('bot')
&& !filteredAuthorList.includes('User talk:' + user.name))
filteredAuthorList.push('User talk:' + user.name);
});
 
})
.catch(error => {
console.error("Error querying API:", error);
});
}
return filteredAuthorList;
} catch (error_1) {
console.error('Error occurred while creating author list:', error_1);
return authorList;
}
}
api.postWithEditToken(requestData).then(function(data) {
 
if (data.edit && data.edit.result === 'Success') {
// Function to create a list of page authors and filter duplicates
messageElement.setType('success');
async function createRedirectTargetsList(titles) {
messageElement.setLabel( $('<span>' + makeLink(title) + ' edited successfully</span><span class="massxfdundo" data-revid="'+data.edit.newrevid+'" data-title="'+title+'"></span>') );
try {
let queryBatchSize resolve()= 50;
let redirectTitles = titles.map(title => title.replace(/ /g, '_')); // Replace spaces with underscores
} else {
let redirectTargets = {};
let nonredirects messageElement.setType('error')= [];
for (let i = 0; i < redirectTitles.length; i += queryBatchSize) {
messageElement.setLabel( $('<span>Error occurred while editing ' + makeLink(title) + ': '+ data + '</span>') );
console.error('Error occurred whilelet prependingbatch text= to page:'redirectTitles.slice(i, datai + queryBatchSize);
let batchTitles = batch.join('|');
 
reject();
await getRedirectData(batchTitles)
}
}) .catchthen(function(error)data => {
 
messageElement.setType('error');
if ('redirects' in data) {
messageElement.setLabel( $('<span>Error occurred while editing ' + makeLink(title) + ': '+ error + '</span>') );
data.redirects.forEach(redirect => {
console.error('Error occurred while prepending text to page:', error); // handle: editconflict, ratelimit (retry)
redirectTargets[redirect.from] = redirect.tofragment ? redirect.to + "#" + redirect.tofragment : redirect.to;
if (error == 'editconflict') {
});
editPage(title, text, summary, progressElement, ratelimitMessage, progress, type, titlesDict, retry=true).then(function() {
resolve let redirects = new Set(data.redirects.map(r => r.to));
let pages = new Set(Object.values(data.pages).map(p => p.title));
});
nonredirects.push(...[...pages].filter(x => !redirects.has(x)));
} else if (error == 'ratelimited') {
progress.setDisabled(true); } else {
nonredirects.push(...Object.values(data.pages).map(p => p.title));
handleRateLimitError(ratelimitMessage).then(function () { }
 
progress.setDisabled(false);
})
editPage(title, text, summary, progressElement, ratelimitMessage, progress, type, titlesDict, retry=true).then(function() {
resolve .catch();error => {
} console.error("Error querying API:", error);
});
}
return [redirectTargets, nonredirects];
else {
} catch reject(error_1); {
console.error('Error occurred while fetching redirect targets', error_1);
}
return [redirectTargets, nonredirects];
}
}
 
function editPage(options) {
const localOptions = deepCopy(options);
localOptions.text = localOptions.textToModify;
const api = new mw.Api();
const messageElement = createMessageElement();
 
messageElement.setLabel((localOptions.retry)
? $('<span>').text('Retrying ').append($(makeLink(localOptions.title)))
: $('<span>').text('Editing ').append($(makeLink(localOptions.title))));
 
localOptions.progressElement.$element.append(messageElement.$element);
const container = $('.sticky-container');
container.scrollTop(container.prop("scrollHeight"));
 
if (localOptions.retry) {
sleep(1000);
}
 
const requestData = {
action: 'edit',
title: window.debuggingMode ? 'User:Qwerfjkl/sandbox/51' : localOptions.title,
summary: localOptions.summary,
format: 'json'
};
 
if (localOptions.type === 'prepend') {
requestData.nocreate = 1;
const targets = localOptions.titlesDict[localOptions.title];
 
for (let i = 0; i < targets.length; i++) {
const placeholder = '$' + (i + 1);
localOptions.text = localOptions.text.replace(placeholder, targets[i]);
}
localOptions.text = localOptions.text.replace(/\$\d/g, '');
requestData.prependtext = localOptions.text.trim() + '\n\n';
} else if (localOptions.type === 'append') {
requestData.appendtext = '\n\n' + localOptions.text.trim();
} else if (localOptions.type === 'text') {
requestData.text = localOptions.text;
}
 
return new Promise((resolve, reject) => {
if (window.abortEdits) {
messageElement.toggle(false);
resolve();
return;
}
 
api.postWithEditToken(requestData)
.then((data) => {
if (data.edit && data.edit.result === 'Success') {
messageElement.setType('success');
messageElement.setLabel($('<span>' + makeLink(localOptions.title) + ' edited successfully</span><span class="massxfdundo" data-revid="' + data.edit.newrevid + '" data-title="' + localOptions.title + '"></span>'));
resolve();
} else {
handleError('Error occurred while editing', data, localOptions, messageElement, resolve, reject);
}
})
.catch((error) => handleError('Error occurred while editing', error, localOptions, messageElement, resolve, reject));
});
});
}
// global scope - needed to syncronise ratelimits
var massXFDratelimitPromise = null;
// Function to handle rate limit errors
function handleRateLimitError(ratelimitMessage) {
var modify = !(ratelimitMessage.isVisible()); // only do something if the element hasn't already been shown
if (massXFDratelimitPromise !== null) {
return massXFDratelimitPromise;
}
 
function handleError(msg, error, options, messageElement, resolve, reject) {
massXFDratelimitPromise = new Promise(function(resolve) {
messageElement.setType('error');
var remainingSeconds = 60;
messageElement.setLabel($('<span>' + msg + ' ' + makeLink(options.title) + ': ' + error + '</span>'));
var secondsToWait = remainingSeconds * 1000;
console.logerror('Ratemsg limit reached. Waiting for+ ' + remainingSeconds + page:', seconds...'error);
 
if (error === 'editconflict') {
ratelimitMessage.setType('warning');
editPage(deepCopy(options)).then(resolve);
ratelimitMessage.setLabel('Rate limit reached. Waiting for ' + remainingSeconds + ' seconds...');
} else if (error === 'ratelimited') {
ratelimitMessage.toggle(true);
options.progress.setDisabled(true);
handleRateLimitError(options.ratelimitMessage).then(() => {
var countdownInterval = setInterval(function() {
options.progress.setDisabled(false);
remainingSeconds--;
editPage(deepCopy(options)).then(resolve);
if (modify) {
});
ratelimitMessage.setLabel('Rate limit reached. Waiting for ' + remainingSeconds + ' second' + ((remainingSeconds === 1) ? '' : 's') + '...');
} else {
reject();
}
}
 
if (remainingSeconds <= 0 || window.abortEdits) {
 
clearInterval(countdownInterval);
// global scope - needed to syncronise ratelimits
massXFDratelimitPromise = null; // reset
var massXFDratelimitPromise = null;
ratelimitMessage.toggle(false);
// Function to handle rate limit resolve();errors
function handleRateLimitError(ratelimitMessage) {
var modify = !(ratelimitMessage.isVisible()); // only do something if the element hasn't already been shown
 
if (massXFDratelimitPromise !== null) {
return massXFDratelimitPromise;
}
}, 1000);
// Use setTimeout to ensure the promise is resolved even if the countdown is not reached
setTimeout(function() {
clearInterval(countdownInterval);
ratelimitMessage.toggle(false);
massXFDratelimitPromise = null; // reset
resolve();
}, secondsToWait);
});
return massXFDratelimitPromise;
}
// Function to show progress visually
function createProgressBar(label) {
var progressBar = new OO.ui.ProgressBarWidget();
progressBar.setProgress(0);
var fieldlayout = new OO.ui.FieldLayout( progressBar, {
label,
align: 'inline'
});
return {progressBar,
fieldlayout};
}
// Main function to execute the script
async function runMassXFD() {
Object.keys(XFDconfig).forEach(function (XfD) {
mw.util.addPortletLink ( 'p-tb', mw.util.getUrl( `Special:Mass${XfD}` ), `Mass ${XfD}`, `pt-mass${XfD.toLowerCase()}`, `Create a mass ${XfD} nomination`);
} );
if (XFD) {
// Load the required modules
mw.loader.using('oojs-ui').done(function() {
wipePageContent();
onbeforeunload = function() {
return "Closing this tab will cause you to lose all progress.";
};
elementsToDisable = [];
var bodyContent = $('#bodyContent');
mw.util.addCSS(`.sticky-container {
bottom: 0;
width: 100%;
max-height: 600px;
overflow-y: auto;
}`);
var nominationToggleObj = createNominationToggle();
var nominationToggle = nominationToggleObj.toggle;
 
massXFDratelimitPromise = new Promise(function (resolve) {
bodyContent.append(nominationToggle.$element);
elementsToDisable.push(nominationToggle) var remainingSeconds = 60;
var secondsToWait = remainingSeconds * 1000;
console.log('Rate limit reached. Waiting for ' + remainingSeconds + ' seconds...');
 
ratelimitMessage.setType('warning');
var rationaleObj = createTitleAndInputField('Rationale:', config.placeholderRationale);
ratelimitMessage.setLabel('Rate limit reached. Waiting for ' + remainingSeconds + ' seconds...');
var rationaleContainer = rationaleObj.container;
var rationaleInputField = rationaleObjratelimitMessage.inputFieldtoggle(true);
elementsToDisable.push(rationaleInputField);
 
var nominationToggleOldcountdownInterval = nominationToggleObj.oldNomToggle;setInterval(function () {
var nominationToggleNew = nominationToggleObj.newNomToggle remainingSeconds--;
if (modify) {
ratelimitMessage.setLabel('Rate limit reached. Waiting for ' + remainingSeconds + ' second' + ((remainingSeconds === 1) ? '' : 's') + '...');
var discussionLinkObj = createTitleAndSingleInputField('Discussion link', config.placeholderDiscussionLink);
var discussionLinkContainer = discussionLinkObj.container; }
var discussionLinkInputField = discussionLinkObj.inputField;
elementsToDisable.push(discussionLinkInputField);
 
if (remainingSeconds <= 0 || window.abortEdits) {
var newNomHeaderObj = createTitleAndSingleInputField('Nomination title', config.placeholderNominationTitle);
var newNomHeaderContainer = newNomHeaderObj.container clearInterval(countdownInterval);
massXFDratelimitPromise = null; // reset
var newNomHeaderInputField = newNomHeaderObj.inputField;
elementsToDisable ratelimitMessage.pushtoggle(newNomHeaderInputFieldfalse);
resolve();
}
}, 1000);
 
// Use setTimeout to ensure the promise is resolved even if the countdown is not reached
bodyContent.append(discussionLinkContainer.$element);
setTimeout(function () {
bodyContent.append(newNomHeaderContainer.$element, rationaleContainer.$element);
function displayElements clearInterval(countdownInterval) {;
if (nominationToggleOldratelimitMessage.isSelectedtoggle(false)) {;
massXFDratelimitPromise = null; // discussionLinkContainer.$element.show();reset
newNomHeaderContainer.$element.hideresolve();
}, rationaleContainer.$element.hide(secondsToWait);
});
return massXFDratelimitPromise;
}
 
// Function to show progress visually
function createProgressBar(label) {
var progressBar = new OO.ui.ProgressBarWidget();
progressBar.setProgress(0);
var fieldlayout = new OO.ui.FieldLayout(progressBar, {
label,
align: 'inline'
});
return {
progressBar,
fieldlayout
};
}
 
 
// Main function to execute the script
async function runMassXFD() {
 
Object.keys(XFDconfig).forEach(function (XfD) {
mw.util.addPortletLink('p-tb', mw.util.getUrl(`Special:Mass${XfD}`), `Mass ${XfD}`, `pt-mass${XfD.toLowerCase()}`, `Create a mass ${XfD} nomination`);
});
 
 
if (XFD && config) {
// Load the required modules
mw.loader.using('oojs-ui').done(function () {
wipePageContent();
if (!window.debuggingMode) { // annoying when reloading for debugging
onbeforeunload = function () {
return "Closing this tab will cause you to lose all progress.";
};
}
elseelementsToDisable if= (nominationToggleNew.isSelected()) {[];
var bodyContent = discussionLinkContainer.$element.hide('#bodyContent');
newNomHeaderContainer.$element.show();
rationaleContainer.$element.show();
 
mw.util.addCSS(`.sticky-container {
bottom: 0;
width: 100%;
max-height: 600px;
overflow-y: auto;
}`); // should probably be styled directly on the element than via the stylesheet
var nominationToggleObj = createNominationToggle();
var nominationToggle = nominationToggleObj.toggle;
 
bodyContent.append(nominationToggle.$element);
elementsToDisable.push(nominationToggle);
 
var rationaleObj = createTitleAndInputField('Rationale:', config.placeholderRationale);
var rationaleContainer = rationaleObj.container;
var rationaleInputField = rationaleObj.inputField;
elementsToDisable.push(rationaleInputField);
 
var nominationToggleOld = nominationToggleObj.oldNomToggle;
var nominationToggleNew = nominationToggleObj.newNomToggle;
 
var discussionLinkObj = createTitleAndSingleInputField('Discussion link', config.placeholderDiscussionLink);
var discussionLinkContainer = discussionLinkObj.container;
var discussionLinkInputField = discussionLinkObj.inputField;
elementsToDisable.push(discussionLinkInputField);
 
var newNomHeaderObj = createTitleAndSingleInputField('Nomination title', config.placeholderNominationTitle);
var newNomHeaderContainer = newNomHeaderObj.container;
var newNomHeaderInputField = newNomHeaderObj.inputField;
elementsToDisable.push(newNomHeaderInputField);
 
bodyContent.append(discussionLinkContainer.$element);
bodyContent.append(newNomHeaderContainer.$element, rationaleContainer.$element);
function displayElements() {
if (nominationToggleOld.isSelected()) {
discussionLinkContainer.$element.show();
newNomHeaderContainer.$element.hide();
rationaleContainer.$element.hide();
}
else if (nominationToggleNew.isSelected()) {
discussionLinkContainer.$element.hide();
newNomHeaderContainer.$element.show();
rationaleContainer.$element.show();
 
}
}
} displayElements();
displayElements nominationToggle.on('select', displayElements);
nominationToggle.on('select', displayElements);
 
function createActionNomination (actionsContainer, first=false) {
var count = actions.length+1;
let actionNominationTitle = XFD === 'CFD' ? 'Action batch #'+count : '';
var container = createFieldset(actionNominationTitle);
actionsContainer.append(container.$element);
var actionDropdownObj = createActionDropdown();
var dropdown = actionDropdownObj.dropdown;
 
elementsToDisable.push(dropdown);
dropdown.$element.css('max-width', 'fit-content');
let demoText = config.pageDemoText;
var prependTextObj = createTitleAndInputField('Text to tag the nominated pages with:', demoText, info='A dollar sign <code>$</code> followed by a number, such as <code>$1</code>, will be replaced with a target specified in the title field, or if not target is specified, will be removed.');
var prependTextLabel = prependTextObj.titleLabel;
var prependTextInfoPopup = prependTextObj.infoPopup;
var prependTextInputField = prependTextObj.inputField;
 
 
elementsToDisable.push(prependTextInputField);
function createActionNomination(actionsContainer, first = false) {
var prependTextContainer = new OO.ui.PanelLayout({
expanded: false var count = actions.length + 1;
let actionNominationTitle = (XFD === 'CFD' || XFD === 'TFD') ? 'Action batch #' + count : '';
});
var container = createFieldset(actionNominationTitle);
var actionObj = createTitleAndInputFieldWithLabel('Action', 'renaming', classes=['newnomonly']);
var actionContainer = actionObj actionsContainer.append(container.$element);
 
var actionInputField = actionObj.inputField;
elementsToDisable.push var actionDropdownObj = createActionDropdown(actionInputField);
var dropdown = actionDropdownObj.dropdown;
actionInputField.$element.css('max-width', 'fit-content');
 
if ( nominationToggleOld.isSelected() ) actionContainer.$element.hide(); // make invisible until needed
elementsToDisable.push(dropdown);
prependTextContainer.$element.append(prependTextLabel.$element, prependTextInfoPopup.$element, dropdown.$element, actionContainer.$element, prependTextInputField.$element);
dropdown.$element.css('max-width', 'fit-content');
let demoText = config.pageDemoText;
nominationToggle.on('select',function() {
var prependTextObj = createTitleAndInputField('Text to tag the nominated pages with:', demoText, info = 'A dollar sign <code>$</code> followed by a number, such as <code>$1</code>, will be replaced with a target specified in the title field, or if not target is specified, will be removed.');
if (nominationToggleOld.isSelected()) {
var prependTextLabel $('.newnomonly')= prependTextObj.hide()titleLabel;
var prependTextInfoPopup = prependTextObj.infoPopup;
if( discussionLinkInputField.getValue().trim() ) discussionLinkInputField.emit('change');
} var prependTextInputField = prependTextObj.inputField;
 
else if (nominationToggleNew.isSelected() ) {
 
if ( XFD === 'CFD') $('.newnomonly').show();
elementsToDisable.push(prependTextInputField);
if ( newNomHeaderInputField.getValue().trim() ) newNomHeaderInputField.emit('change');
} var prependTextContainer = new OO.ui.PanelLayout({
}); expanded: false
});
var actionObj = createTitleAndInputFieldWithLabel('Action', 'renaming', classes = ['newnomonly']);
if (nominationToggleOld.isSelected()) {
var actionContainer = actionObj.container;
if (discussionLinkInputField.getValue().match(config.discussionLinkRegex)) {
var sectionNameactionInputField = discussionLinkInputField.getValue()actionObj.trim()inputField;
} elementsToDisable.push(actionInputField);
actionInputField.$element.css('max-width', 'fit-content');
}
else if (nominationToggleNewnominationToggleOld.isSelected() || XFD === 'TFD') {actionContainer.$element.hide(); // make invisible until needed
prependTextContainer.$element.append(prependTextLabel.$element, prependTextInfoPopup.$element, dropdown.$element, actionContainer.$element, prependTextInputField.$element);
sectionName = newNomHeaderInputField.getValue().trim();
 
}
nominationToggle.on('select', function () {
// helper function, makes more accurate if (nominationToggleOld.isSelected()) {
$('.newnomonly').hide();
function replaceOccurence(str, find, replace) {
if (XFD ===discussionLinkInputField.getValue().trim()) discussionLinkInputField.emit('CFDchange') { ;
// last occurence }
let index = str else if (nominationToggleNew.lastIndexOfisSelected(find);) {
if (XFD === 'CFD' || XFD === 'TFD') $('.newnomonly').show();
if (newNomHeaderInputField.getValue().trim()) newNomHeaderInputField.emit('change');
if (index >= 0) {
return str.substring(0, index) + replace + str.substring(index + find.length);}
} else {});
 
return str;
} if (nominationToggleOld.isSelected()) {
if (discussionLinkInputField.getValue().match(config.discussionLinkRegex)) {
} else {
if sectionName = discussionLinkInputField.getValue(str).toLowerCasetrim().startsWithmatch('{{subst:rfd|'config.discussionLinkRegex)) {[1];
str = str.replace(/\{\{subst:rfd\|/i, '');}
return'{{subst:rfd|'+str.replace(find, replace);}
else if (nominationToggleNew.isSelected()) {
sectionName = newNomHeaderInputField.getValue().trim();
}
 
// helper function, makes more accurate.
function replaceOccurence(str, find, replace) {
 
if (XFD === 'CFD' || XFD === 'TFD') {
// last occurence
let index = str.lastIndexOf(find);
 
if (index >= 0) {
return str.substring(0, index) + replace + str.substring(index + find.length);
} else {
return str;
}
} else if (XFD === 'RFD') { // RfD has stuff after it so we can't just replace last occurence
if (str.toLowerCase().startsWith('{{subst:rfd|')) {
str = str.replace(/\{\{subst:rfd\|/i, '');
return '{{subst:rfd|' + str.replace(find, replace);
} else {
return str.replace(find, replace); // first occurence
}
}
}
 
var sectionName = sectionName || 'sectionName';
var oldSectionName = sectionName;
 
if (XFD === 'RFD') {
prependTextInputField.setValue(config.actions.prepend.replace('${sectionName}', delinkWikitext(sectionName)));
 
if (discussionLinkInputField.getValue().match(config.discussionLinkRegex)) {
let date = discussionLinkInputField.getValue().trim().match(/^Wikipedia:Redirects for discussion\/Log\/(\d\d\d\d \w+ \d\d)?#.+$/)[1];
let difference = getDateDifference(date);
if (difference !== 0) {
prependTextInputField.setValue(config.actions.prepend.replace('{{subst:rfd|${sectionName}|', `{{subst:rfd|${delinkWikitext(sectionName)}|days=${difference}|`));
} // else leave as default above
}
}
 
discussionLinkInputField.on('change', function () {
if (discussionLinkInputField.getValue().match(config.discussionLinkRegex)) {
oldSectionName = sectionName;
sectionName = discussionLinkInputField.getValue().replace(config.discussionLinkRegex, '$1').trim();
var text = prependTextInputField.getValue();
 
if (XFD === 'RFD') {
const date = discussionLinkInputField.getValue().trim().match(/^Wikipedia:Redirects for discussion\/Log\/(\d\d\d\d \w+ \d\d?)#.+$/)[1];
 
if (/(\| *days *= *)\d+/.test(text)) { // already has days=, update
text = text.replace(/(\| *days *= *)\d+/, '$1' + getDateDifference(date));
text = replaceOccurence(text, delinkWikitext(oldSectionName), delinkWikitext(sectionName));
} else {
text = replaceOccurence(text, delinkWikitext(oldSectionName), delinkWikitext(sectionName) + '|days=' + getDateDifference(date));
}
} else text = replaceOccurence(text, delinkWikitext(oldSectionName), delinkWikitext(sectionName));
 
prependTextInputField.setValue(text);
 
}
});
 
newNomHeaderInputField.on('change', function () {
if (newNomHeaderInputField.getValue().trim()) {
oldSectionName = sectionName;
sectionName = newNomHeaderInputField.getValue().trim();
var text = prependTextInputField.getValue();
text = replaceOccurence(text, delinkWikitext(oldSectionName), delinkWikitext(sectionName));
prependTextInputField.setValue(text);
}
});
 
dropdown.on('labelChange', function () {
let actionData = config.actions[dropdown.getLabel()];
prependTextInputField.setValue(actionData.prepend.replace('${sectionName}', delinkWikitext(sectionName)));
actionInputField.setValue(actionData.action);
});
 
 
 
 
var titleListObj = createTitleAndInputField(`List of titles (one per line${XFD === 'CFD' ? ', <code>Category:</code> prefix is optional' : ''})`, config.titleDemoText, info = 'You can specify targets by adding a pipe <code>|</code> and then the target, e.g. <code>Example|Target1|Target2</code>. These targets can be used in the tagging step.');
var titleList = titleListObj.container;
var titleListInputField = titleListObj.inputField;
var titleListInfoPopup = titleListObj.infoPopup;
elementsToDisable.push(titleListInputField);
let handler = handlepaste.bind(this, titleListInputField);
let textInputElement = titleListInputField.$element.get(0);
// Modern browsers. Note: 3rd argument is required for Firefox <= 6
if (textInputElement.addEventListener) {
textInputElement.addEventListener('paste', handler, false);
}
// IE <= 8
else {
textInputElement.attachEvent('onpaste', handler);
}
 
 
titleListObj.inputField.$element.on('paste', handlepaste);
 
if (XFD === 'RFD') {
// some XfDs don't need multiple actions, they're just delete. so hide unnecessary elements'
actionContainer.$element.hide();
dropdown.$element.hide();
prependTextInfoPopup.$element.hide(); // both popups give info about targets which aren't relevant here
titleListInfoPopup.$element.hide();
}
 
 
if (!first && XFD !== 'CFD') {
var removeButton = createRemoveBatchButton();
elementsToDisable.push(removeButton);
removeButton.on('click', function () {
container.$element.remove();
// filter based on the container element
actions = actions.filter(function (item) {
return item.container !== container;
});
// Reset labels
for (i = 0; i < actions.length; i++) {
actions[i].container.setLabel('Action batch #' + (i + 1));
actions[i].label = 'Action batch #' + (i + 1);
}
});
 
container.addItems([removeButton, prependTextContainer, titleList]);
 
} else {
return strcontainer.replaceaddItems(find[prependTextContainer, replacetitleList]); // first occurence
}
 
return {
titleListInputField,
prependTextInputField,
label: 'Action batch #' + count,
container,
actionInputField
};
}
} var actionsContainer = $('<div />');
bodyContent.append(actionsContainer);
var sectionName =var sectionNameactions ||= 'sectionName'[];
var oldSectionName actions.push(createActionNomination(actionsContainer, first = sectionNametrue));
if (XFD !== 'CFD') {
prependTextInputField.setValue(config.actions.prepend.replace('${sectionName}', sectionName));
}
discussionLinkInputField.on('change',function() {
if (discussionLinkInputField.getValue().match(config.discussionLinkRegex)) {
oldSectionName = sectionName;
sectionName = discussionLinkInputField.getValue().replace(config.discussionLinkRegex, '$1').trim();
var text = prependTextInputField.getValue();
text = replaceOccurence(text, oldSectionName, sectionName);
prependTextInputField.setValue(text);
}
});
newNomHeaderInputField.on('change',function() {
if ( newNomHeaderInputField.getValue().trim() ) {
oldSectionName = sectionName;
sectionName = newNomHeaderInputField.getValue().trim();
var text = prependTextInputField.getValue();
text = replaceOccurence(text, oldSectionName, sectionName);
prependTextInputField.setValue(text);
}
});
dropdown.on('labelChange',function() {
let actionData = config.actions[dropdown.getLabel()];
prependTextInputField.setValue(actionData.prepend.replace('${sectionName}', sectionName));
actionInputField.setValue(actionData.action);
});
var titleListObj = createTitleAndInputField(`List of titles (one per line${XFD === 'CFD' ? ', <code>Category:</code> prefix is optional' : ''})`, 'Title1\nTitle2\nTitle3', info='You can specify targets by adding a pipe <code>|</code> and then the target, e.g. <code>Example|Target1|Target2</code>. These targets can be used in the tagging step.');
var titleList = titleListObj.container;
var titleListInputField = titleListObj.inputField;
var titleListInfoPopup = titleListObj.infoPopup;
elementsToDisable.push(titleListInputField);
let handler = handlepaste.bind(this, titleListInputField);
let textInputElement = titleListInputField.$element.get(0);
// Modern browsers. Note: 3rd argument is required for Firefox <= 6
if (textInputElement.addEventListener) {
textInputElement.addEventListener('paste', handler, false);
}
// IE <= 8
else {
textInputElement.attachEvent('onpaste', handler);
}
titleListObj.inputField.$element.on('paste', handlepaste);
 
if (XFD !=var checkboxObj = createCheckboxWithLabel('CFDNotify users?') {;
var notifyCheckbox = checkboxObj.checkbox;
// most XfDs don't need multiple actions, they're just delete. so hide unnecessary elements'
actionContainerelementsToDisable.$element.hidepush(notifyCheckbox);
dropdownvar checkboxFieldlayout = checkboxObj.$element.hide()fieldlayout;
prependTextInfoPopupcheckboxFieldlayout.$element.hidecss('margin-bottom', '10px'); // both popups give info about targets which aren't relevant here
titleListInfoPopupbodyContent.append(checkboxFieldlayout.$element.hide();
}
 
var multiOptionButton = createMultiOptionButton();
if elementsToDisable.push(!first && XFD !== 'CFD'multiOptionButton) {;
multiOptionButton.$element.css('margin-bottom', '10px');
var removeButton = createRemoveBatchButton();
elementsToDisablebodyContent.pushappend(removeButtonmultiOptionButton.$element);
removeButtonbodyContent.onappend('click<br />',function() {;
container.$element.remove();
// filter based on the container element
actions = actions.filter(function(item) {
return item.container !== container;
});
// Reset labels
for (i=0; i<actions.length;i++) {
actions[i].container.setLabel('Action batch #'+(i+1));
actions[i].label = 'Action batch #'+(i+1);
}
});
container.addItems([removeButton, prependTextContainer, titleList]);
} else {
container.addItems([prependTextContainer, titleList]);
}
return {
titleListInputField,
prependTextInputField,
label: 'Action batch #'+count,
container,
actionInputField
};
}
var actionsContainer = $('<div />');
bodyContent.append(actionsContainer);
var actions = [];
actions.push(createActionNomination(actionsContainer, first=true));
var checkboxObj = createCheckboxWithLabel('Notify users?');
var notifyCheckbox = checkboxObj.checkbox;
elementsToDisable.push(notifyCheckbox);
var checkboxFieldlayout = checkboxObj.fieldlayout;
checkboxFieldlayout.$element.css('margin-bottom', '10px');
bodyContent.append(checkboxFieldlayout.$element);
var multiOptionButton = createMultiOptionButton();
elementsToDisable.push(multiOptionButton);
multiOptionButton.$element.css('margin-bottom', '10px');
bodyContent.append(multiOptionButton.$element);
bodyContent.append('<br />');
 
 
multiOptionButton.on('click', () => {
actions.push( createActionNomination(actionsContainer) );
});
if (XFD !== 'CFD' && XFD !== 'TFD') {
multiOptionButton.$element.hide();
} else {
var categoryTemplateDropdownObj = makeCategoryTemplateDropdown('Category template:');
categoryTemplateDropdownContainer = categoryTemplateDropdownObj.container;
categoryTemplateDropdown = categoryTemplateDropdownObj.dropdown;
categoryTemplateDropdown.$element.css(
{
'display': 'inline-block',
'max-width': 'fit-content',
'margin-bottom': '10px'
}
if (XFD === 'CFD'); {
elementsToDisable.push(categoryTemplateDropdown);
if ( nominationToggleOld.isSelected() ) categoryTemplateDropdownContainer.$element.hide();
bodyContent.append(categoryTemplateDropdownContainer.$element);
}
 
var categoryTemplateDropdownObj = makeCategoryTemplateDropdown('Category template: (used on the discussion page)');
var startButton = createStartButton();
categoryTemplateDropdownContainer = categoryTemplateDropdownObj.container;
elementsToDisable.push(startButton);
categoryTemplateDropdown = categoryTemplateDropdownObj.dropdown;
bodyContent.append(startButton.$element);
categoryTemplateDropdown.$element.css(
{
'display': 'inline-block',
startButton.on( 'clickmax-width',: function() {'fit-content',
'margin-bottom': '10px'
var isOld = nominationToggleOld.isSelected(); }
var isNew = nominationToggleNew.isSelected( );
// First check elements elementsToDisable.push(categoryTemplateDropdown);
if (nominationToggleOld.isSelected()) categoryTemplateDropdownContainer.$element.hide();
var error = false;
bodyContent.append(categoryTemplateDropdownContainer.$element);
var regex = config.discussionLinkRegex;
if (isOld) {
if ( !(discussionLinkInputField.getValue().trim()) || !regex.test(discussionLinkInputField.getValue().trim()) ) {
discussionLinkInputField.setValidityFlag(false);
error = true;
} else {
discussionLinkInputField.setValidityFlag(true);
}
} else if (isNew ) {
if ( !(newNomHeaderInputField.getValue().trim()) ) {
newNomHeaderInputField.setValidityFlag(false);
error = true;
} else {
newNomHeaderInputField.setValidityFlag(true);
}
if ( !(rationaleInputField.getValue().trim()) ) {
rationaleInputField.setValidityFlag(false);
error = true;
} else {
rationaleInputField.setValidityFlag(true);
}
}
batches = actions.map(function ({titleListInputField, prependTextInputField, label, actionInputField}) {
if ( !(prependTextInputField.getValue().trim()) || !prependTextInputField.getValue().includes('${pageText}')) {
prependTextInputField.setValidityFlag(false);
error = true;
} else {
prependTextInputField.setValidityFlag(true);
}
if (isNew && XFD === 'CFD') {
if ( !(actionInputField.getValue().trim()) ) {
actionInputField.setValidityFlag(false);
error = true;
} else {
actionInputField.setValidityFlag(true);
}
}
if ( !(titleListInputField.getValue().trim()) ) {
titleListInputField.setValidityFlag(false);
error = true;
} else {
titleListInputField.setValidityFlag(true);
}
// Retreive titles, handle dups
var titles = {};
var titleList = titleListInputField.getValue().split('\n');
function normalise(title) {
return config.normaliseFunction(title);
}
titleList.forEach(function(title) {
if (title) {
var targets = title.split('|');
var newTitle = targets.shift();
newTitle = normalise(newTitle);
if (!Object.keys(titles).includes(newTitle) ) {
titles[newTitle] = targets.map(normalise);
}
}
});
if ( !(Object.keys(titles).length) ) {
titleListInputField.setValidityFlag(false);
error = true;
} else {
titleListInputField.setValidityFlag(true);
}
return {
titles,
prependText: prependTextInputField.getValue().trim(),
label,
actionInputField
};
});
if (error) {
return;
}
for (let element of elementsToDisable) {
element.setDisabled(true);
}
$('.remove-batch-button').remove();
var abortButton = createAbortButton();
bodyContent.append(abortButton.$element);
window.abortEdits = false; // initialise
abortButton.on('click', function() {
// Set abortEdits flag to true
if (confirm('Are you sure you want to abort?')) {
abortButton.setDisabled(true);
window.abortEdits = true;
}
});
var allTitles = batches.reduce((allTitles, obj) => {
return allTitles.concat(Object.keys(obj.titles));
}, []);
 
var startButton = createStartButton();
createAuthorList(allTitles).then(function(authors) {
elementsToDisable.push(startButton);
bodyContent.append(startButton.$element);
 
function processContent(content, titles, textToModify, summary, type, doneMessage, headingLabel) {
 
if (!Array.isArray(titles)) {
 
var titlesDict = titles;
startButton.on('click', async function titles = Object.keys(titles); {
 
}
var fieldsetisOld = createFieldsetnominationToggleOld.isSelected(headingLabel);
var isNew = nominationToggleNew.isSelected();
// First content.append(fieldset.$element);check elements
var error = false;
var progressElementregex = createProgressElement()config.discussionLinkRegex;
if fieldset.addItems([progressElement]isOld); {
if (!(discussionLinkInputField.getValue().trim()) || !regex.test(discussionLinkInputField.getValue().trim())) {
var ratelimitMessage = createRatelimitMessage discussionLinkInputField.setValidityFlag(false);
ratelimitMessage.toggle(false) error = true;
fieldset.addItems([ratelimitMessage]); } else {
discussionLinkInputField.setValidityFlag(true);
var progressObj = createProgressBar(`(0 / ${titles.length}, 0 errors)`); // with label
} else varif progress(isNew) = progressObj.progressBar;{
var progressContainer =if progressObj(!(newNomHeaderInputField.fieldlayout;getValue().trim())) {
// Add margin or padding to the progress bar widgetnewNomHeaderInputField.setValidityFlag(false);
progress.$element.css('margin-top', '5px') error = true;
progress.pushPending(); } else {
fieldset newNomHeaderInputField.addItemssetValidityFlag([progressContainer]true);
}
 
let resolvedCount = 0;
let rejectedCount =if 0;(!(rationaleInputField.getValue().trim())) {
rationaleInputField.setValidityFlag(false);
function updateCounter() { error = true;
progressContainer.setLabel(`(${resolvedCount} /else ${titles.length}, ${rejectedCount} errors)`);
} rationaleInputField.setValidityFlag(true);
function updateProgress() {}
 
var percentage = (resolvedCount + rejectedCount) / titles.length * 100;
progress.setProgress(percentage);}
 
batches = actions.map(function ({ titleListInputField, prependTextInputField, label, actionInputField }) {
}
if (!(prependTextInputField.getValue().trim()) || (XFD === 'RFD' && !prependTextInputField.getValue().includes('${pageText}'))) {
function trackPromise prependTextInputField.setValidityFlag(promisefalse) {;
return new Promise((resolve, reject)error => {true;
} else promise{
prependTextInputField.thensetValidityFlag(value => {true);
 
resolvedCount++;
updateCounter();}
 
updateProgress();
if (isNew && (XFD === 'CFD' || XFD === 'TFD')) resolve(value);{
if (!(actionInputField.getValue().trim())) }){
actionInputField.catchsetValidityFlag(error => {false);
error = rejectedCount++true;
} else updateCounter();{
updateProgressactionInputField.setValidityFlag(true);
resolve(error);
});
});
}
return new Promise(async function(resolve) {
var promises = [];
for (const title of titles) {
// RfD needs special handling here, because it wraps around the whole page content
if (XFD === 'RFD' && type === 'prepend') { // prepend implicitly means page tagging, not actually prepend in this case
text = await getWikitext(title);
textToModify = textToModify.replace('${pageText}', text);
type = 'text';
}
}
var promise = editPage(title, textToModify, summary, progressElement, ratelimitMessage, progress, type, titlesDict);
 
promises.push(trackPromise(promise));
if await sleep(100!(titleListInputField.getValue().trim())); // space out calls{
await massXFDratelimitPromise; // stop if ratelimit reached titleListInputField.setValidityFlag(global variablefalse);
} error = true;
} else {
Promise titleListInputField.allSettledsetValidityFlag(promisestrue);
.then(function() {}
 
progress.toggle(false);
// Retreive titles, handle if (window.abortEdits) {dups
var abortMessagetitles = createAbortMessage(){};
var titleList = titleListInputField.getValue().split('\n');
abortMessage.setLabel( $('<span>Edits manually aborted. <a id="massxfdrevertlink" onclick="revertEdits()">Revert?</a></span>') );
function normalise(title) {
return contentconfig.appendnormaliseFunction(abortMessage.$elementtitle);
} else {
let var completedElementhasModules = createCompletedElement()false;
let hasCSSPages = completedElement.setLabel(doneMessage)false;
completedElementtitleList.$element.cssforEach('margin-bottom',function '16px'(title); {
try content.append(completedElement.$element);{
} if (title) {
resolve var targets = title.split('|');
} var newTitle = targets.shift();
 
.catch(function(error) {
console.error("Error occurred during title processing:", error newTitle = normalise(newTitle);
resolve(); // make sure all titles are in template or module namespaces
if (XFD === 'TFD') {
if (!newTitle.includes('Template:') && !newTitle.includes('Module:')) {
titleListInputField.setValidityFlag(false);
error = true;
}
}
if (!Object.keys(titles).includes(newTitle)) {
// for TfD skip modules, we deal with them elsewhere
if (XFD === "TFD") {
if (newTitle.includes('Module:')) hasModules = true;
else if (newTitle.endsWith('.css')) hasCSSPages = true;
else titles[newTitle] = targets.map(normalise).map(t => t.replace(/^Template:/, ""));
// tfd templates don't use the prefix, and the replacement is safe after normalistation
} else {
titles[newTitle] = targets.map(normalise);
}
 
 
}
}
} catch (e) {
console.error(`[MassXFD] Error parsing title "${title}": ${e}`);
titleListInputField.setValidityFlag(false);
error = true;
}
});
 
if (!(Object.keys(titles).length) && !hasModules && !hasCSSPages) {
titleListInputField.setValidityFlag(false);
error = true;
}
if (Object.keys(titles).length) {
return {
titles,
prependText: prependTextInputField.getValue().trim(),
label,
actionInputField
};
} else {
return null;
}
 
}).filter(function (item) {
return item !== null;
});
 
// for TFD, we need to remove the Module: titles, and treat them as seperate batches, one for merging, one for deleting
if (XFD === 'TFD') {
let mergingModules = {};
let deletingModules = {};
let cssPages = {};
actions.forEach(function ({ titleListInputField, prependTextInputField }) {
titleListInputField.getValue().split('\n').forEach(title => {
let targets = title.split('|');
let newTitle = targets.shift();
if (newTitle.trim().endsWith('.css')) {
newTitle = config.normaliseFunction(newTitle);
cssPages[newTitle] = targets.map(config.normaliseFunction);
}
else if ((new mw.Title(newTitle)).getNamespaceId() === NS_MODULE) {
 
newTitle = config.normaliseFunction(newTitle);
if (prependTextInputField.getValue().trim().match(/\{\{ *subst: *Tfm/i)) {
mergingModules[newTitle] = targets.map(config.normaliseFunction);
} else {
deletingModules[newTitle] = targets.map(config.normaliseFunction);
// this will be the default, even if we can't detect the action
}
}
});
});
} let sectionName = '';
let discussionPageLink = '';
const date = new Date if (nominationToggleOld.isSelected();) {
if (discussionLinkInputField.getValue().match(config.discussionLinkRegex)) {
sectionName = discussionLinkInputField.getValue().trim().match(config.discussionLinkRegex)[1];
const year = date.getUTCFullYear();
discussionPageLink = (new mw.Title(discussionLinkInputField.getValue().trim())).getUrl();
const month = date.toLocaleString('en', { month: 'long', timeZone: 'UTC' });
const day = date.getUTCDate(); }
}
var summaryDiscussionLink; else if (nominationToggleNew.isSelected()) {
sectionName = newNomHeaderInputField.getValue().trim();
var discussionPage = `${config.baseDiscussionPage}${year} ${month} ${day}`;
discussionPageLink = (new mw.Title(sectionName)).getUrl();
 
if (isOld) summaryDiscussionLink = discussionLinkInputField.getValue().trim();
else if (isNew) summaryDiscussionLink const date = `${discussionPage}#${newNomHeaderInputField.getValue().trimnew Date()}`;
 
const advSummaryyear = ' ([[User:Qwerfjkl/scripts/massXFDdate.js|via script]]getUTCFullYear()';
const month = date.toLocaleString('en', { month: 'long', timeZone: 'UTC' });
// WIP, not finished
const categorySummary = 'Tagging page for [[' +summaryDiscussionLink+']]' + advSummary const day = date.getUTCDate();
 
const userSummary = 'Notifying user about [[' +summaryDiscussionLink+']]' + advSummary;
const userNotification = `{{ subst: var discussionPage = `${config.userNotificationTemplatebaseDiscussionPage} | ${summaryDiscussionLinkyear} }${month} ~~~~${day}`;
const nominationSummary = `Adding mass nomination at [[ discussionPageLink = `${discussionPage}#${newNomHeaderInputField.getValue().trim()}]]` + advSummary;
}
var batchesToProcess = []; if (Object.keys(mergingModules).length) {
batches.unshift({
var newNomPromise = new Promise(function (resolve) { titles: Object.fromEntries(
if Object.entries(isNewmergingModules) {.map(
nominationText = `=== ([title, targets]) => [`${newNomHeaderInputFieldtitle}/doc`, targets.getValuemap()t => t.trimreplace()}/^Module:/, ====\n`;""))]
for (const batch of batches) { )
var action = batch.actionInputField.getValue().trim();,
for (const page of Object.keys(batch.titles))prependText: `{{subst:Tfm|$1|type=module|page={{subst:BASEPAGENAME}}|heading=${sectionName}}}`,
iflabel: (XFD"Merging == 'CFD' ){modules",
actionInputField: var targets = batch.titles[page].slice(); // copy arraynull
var targetText = ''});
if (targets.length) {}
if (targetsObject.keys(deletingModules).length === 2) {
targetText = ` to [[:$batches.unshift({targets[0]}]] and [[:${targets[1]}]]`;
titles: }Object.fromEntries(
else if (targetsObject.length > 2entries(deletingModules) {.map(
([title, targets]) var=> lastTarget[`${title}/doc`, targets.map(t => targetst.popreplace(/^Module:/, ""));]
targetText = ' to [[:' + targets.join(']], [[:') + ']], and [[:' + lastTarget + ']]';
} else { // 1 target),
prependText: targetText `{{subst:Tfd|type= ' to [[module|page={{subst:' + targets[0] + ']]';BASEPAGENAME}}|heading=${sectionName}}}`,
label: "Deleting }modules",
actionInputField: }null
nominationText +=`:* '''Propose ${action}''' {{${categoryTemplateDropdown.getValue()}|${page}}}${targetText}\n`;
}
if (Object.keys(cssPages).length) {
batches.unshift({
titles: cssPages, // we don't need to substitute out the prefix because targets will never be used, as the prependText is hardcoded
prependText: `/* This template is being discussed in accordance with Wikipedia's deletion policy. Help reach a consensus at its entry: ${discussionPageLink} */\n`,
label: "CSS pages",
actionInputField: null
});
}
 
}
 
 
 
if (error) {
return;
}
 
for (let element of elementsToDisable) {
element.setDisabled(true);
}
 
 
$('.remove-batch-button').remove();
 
var abortButton = createAbortButton();
bodyContent.append(abortButton.$element);
window.abortEdits = false; // initialise
abortButton.on('click', function () {
 
// Set abortEdits flag to true
if (confirm('Are you sure you want to abort?')) {
abortButton.setDisabled(true);
window.abortEdits = true;
}
});
var allTitles = batches.reduce((allTitles, obj) => {
return allTitles.concat(Object.keys(obj.titles));
}, []);
 
 
if (XFD === 'RFD') {
let fetchingRedirectsElement = createDoingElement();
fetchingRedirectsElement.setLabel('Fetching redirect targets...');
fetchingRedirectsElement.$element.css('margin-top', '16px');
bodyContent.append(fetchingRedirectsElement.$element);
 
let fetchedRedirectsElement = createCompletedElement();
fetchedRedirectsElement.setLabel('Fetched redirect targets');
fetchedRedirectsElement.$element.css('margin-top', '16px');
 
var [redirectTargets, nonredirects] = await createRedirectTargetsList(allTitles);
if (window.debuggingMode) console.log(`Redirect targets: ${JSON.stringify(redirectTargets)}`);
// console.log(Object.values(redirectTargets).map(title => {
// let page = new mw.Title(title)
// return page.getTalkPage().getPrefixedText()
// }))
// console.log([... new Set(Object.values(redirectTargets).map(title => {
// let page = new mw.Title(title)
// return page.getTalkPage().getPrefixedText()
// }))])
// window.batches=batches
batches[0].titles = Object.keys(batches[0].titles)
.filter(x => !nonredirects.includes(x))
.reduce((acc, curr) => {
acc[curr] = [];
return acc;
}, {});
 
 
 
if (!Object.keys(redirectTargets).length) {
var errorMessageElement = createErrorMessage('None of the titles are redirects, aborting.');
bodyContent.append(errorMessageElement.$element);
return;
}
if (nonredirects.length) {
let nonredirectsWarningMessage = createWarningMessage();
nonredirectsWarningMessage.$element.css({ 'max-height': '20em', 'overflow-y': 'auto' }); // normally shouldn't be needed
let nonRedirectsHTML = $('<div>').append($('<span>').text('The following pages were ignored because they are not redirects:'));
let $listElement = $('<ul>');
nonredirects.forEach(item => {
const $listItem = $('<li>').html(makeLink(item));
$listElement.append($listItem);
});
nonRedirectsHTML.append($listElement);
nonredirectsWarningMessage.setLabel(nonRedirectsHTML);
bodyContent.append(nonredirectsWarningMessage.$element);
}
 
fetchingRedirectsElement.$element.hide();
bodyContent.append(fetchedRedirectsElement.$element);
}
 
 
let fetchingAuthorsElement = createDoingElement();
fetchingAuthorsElement.setLabel('Fetching authors...')
fetchingAuthorsElement.$element.css('margin-top', '16px');
bodyContent.append(fetchingAuthorsElement.$element);
 
let fetchedAuthorsElement = createCompletedElement();
fetchedAuthorsElement.setLabel('Fetched authors')
fetchedAuthorsElement.$element.css('margin-top', '16px');
let authors;
if (redirectTargets) {
authors = await createAuthorList(Object.keys(redirectTargets));
} else {
authors = await createAuthorList(allTitles);
}
 
fetchingAuthorsElement.$element.hide();
bodyContent.append(fetchedAuthorsElement.$element);
 
 
async function processContent(options) {
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
 
 
if (!Array.isArray(options.titles)) {
options.titlesDict = options.titles; // dictionary is confusingly used for different things for prepend batches and for redirect notify batches
options.titles = Object.keys(options.titles);
} else {
options.titlesDict = {};
}
 
const fieldset = createFieldset(options.headingLabel);
bodyContent.append(fieldset.$element);
 
options.progressElement = createProgressElement();
fieldset.addItems([options.progressElement]);
 
options.ratelimitMessage = createWarningMessage();
options.ratelimitMessage.toggle(false);
fieldset.addItems([options.ratelimitMessage]);
 
const progressObj = createProgressBar(`(0 / ${options.titles.length}, 0 errors)`);
options.progress = progressObj.progressBar;
const progressContainer = progressObj.fieldlayout;
options.progress.$element.css('margin-top', '5px');
options.progress.pushPending();
fieldset.addItems([progressContainer]);
 
let resolvedCount = 0;
let rejectedCount = 0;
 
function updateCounter() {
progressContainer.setLabel(`(${resolvedCount} / ${options.titles.length}, ${rejectedCount} errors)`);
}
 
function updateProgress() {
const percentage = (resolvedCount + rejectedCount) / options.titles.length * 100;
options.progress.setProgress(percentage);
}
 
function trackPromise(promise) {
return new Promise((resolve) => {
promise
.then(value => {
resolvedCount++;
updateCounter();
updateProgress();
resolve(value);
})
.catch(error => {
rejectedCount++;
updateCounter();
updateProgress();
resolve(error);
});
});
}
 
const promises = [];
for (const title of options.titles) {
let data = deepCopy(options);
if (XFD === 'RFD' && data.type === 'prepend') {
const text = await getWikitext(title);
data.textToModify = data.textToModify.replace('${pageText}', text);
data.type = 'text';
}
 
if (data.id === 'rfd-notify-target') {
// ${redirectTitle} is a placeholder for the redirect being nominated
// this code needs a more intelligent way of checking which redirect was tagged.
data.textToModify = data.textToModify.replace('${redirectTitle}', data.titlesDict[title]);
}
 
data.title = title;
 
const promise = editPage(data);
promises.push(trackPromise(promise));
 
if (!window.abortEdits) await sleep(100); // space out calls - not needed if they're being rejected
await massXFDratelimitPromise; // stop if ratelimit reached (global variable)
}
 
await Promise.allSettled(promises);
 
options.progress.toggle(false);
 
if (window.abortEdits) {
const abortMessage = createAbortMessage();
const revertEditsLink = $('<a id="massxfdrevertlink">Revert?</a>');
revertEditsLink.on('click', revertEdits);
abortMessage.setLabel($('<span>').append('Edits manually aborted. ').append(revertEditsLink));
bodyContent.append(abortMessage.$element);
} else {
const completedElement = createCompletedElement();
completedElement.setLabel(options.doneMessage);
completedElement.$element.css('margin-bottom', '16px');
bodyContent.append(completedElement.$element);
}
}
 
 
 
const date = new Date();
 
const year = date.getUTCFullYear();
const month = date.toLocaleString('en', { month: 'long', timeZone: 'UTC' });
const day = date.getUTCDate();
 
var summaryDiscussionLink;
var discussionPage = `${config.baseDiscussionPage}${year} ${month} ${day}`;
 
if (isOld) summaryDiscussionLink = discussionLinkInputField.getValue().trim();
else if (isNew) summaryDiscussionLink = `${discussionPage}#${newNomHeaderInputField.getValue().trim()}`;
summaryDiscussionLink = delinkWikitext(summaryDiscussionLink); // links can't be nested
 
const advSummary = ' ([[User:Qwerfjkl/scripts/massXFD.js|via MassXfD.js]])';
// WIP, not finished
const taggingSummary = 'Tagging page for [[' + summaryDiscussionLink + ']]' + advSummary;
const userSummary = 'Notifying user about [[' + summaryDiscussionLink + ']]' + advSummary;
const userNotification = `{{ subst: ${config.userNotificationTemplate} | ${summaryDiscussionLink} }} ~~~~`;
const nominationSummary = `Adding mass nomination at [[#${newNomHeaderInputField.getValue().trim()}]]` + advSummary;
if (XFD === 'RFD') {
var redirectTargetNotification = `{{subst:Rfd notice|\${redirectTitle}|${newNomHeaderInputField.getValue().trim()}}} ~~~~`;
var redirectTargetNotificationSummary = `Notice of [[${summaryDiscussionLink}]]${advSummary}`;
}
var batchesToProcess = [];
 
var newNomPromise = new Promise(function (resolve) {
if (isNew) {
nominationText = `==== ${newNomHeaderInputField.getValue().trim()} ====\n`;
for (const batch of batches) {
var action = batch.actionInputField?.getValue()?.trim() || false;
for (const page of Object.keys(batch.titles)) {
if (XFD == 'CFD') {
var targets = batch.titles[page].slice(); // copy array
var targetText = '';
if (targets.length) {
if (targets.length === 2) {
targetText = ` to [[:${targets[0]}]] and [[:${targets[1]}]]`;
}
else if (targets.length > 2) {
var lastTarget = targets.pop();
targetText = ' to [[:' + targets.join(']], [[:') + ']], and [[:' + lastTarget + ']]';
} else { // 1 target
targetText = ' to [[:' + targets[0] + ']]';
}
}
nominationText += `:* '''Propose ${action}''' {{${categoryTemplateDropdown.getValue()}|${categoryTemplateDropdown.getValue() === 'cl' ? page.replace(/^ *Category:/i, '') : page}}}${targetText}\n`;
} else if (XFD === 'RFD') {
nominationText += config.displayTemplate.replaceAll('${pageName}', page).replaceAll('${redirectTarget}', redirectTargets[page]) + '\n';
} else if (XFD === 'TFD') {
let moduleText = '';
if ((new mw.Title(page)).getNamespacePrefix() === "Module:") moduleText = `|module=Module:`; // looking at the actual implementation, module can be anything that's not empty
nominationText += `* ${config.displayTemplate.replaceAll('${pageName}', (new mw.Title(page)).getMainText()).replaceAll('${moduleText}', moduleText)}\n`;
} else {
throw new Error("Unimplemented.")
}
}
}
var rationale = rationaleInputField.getValue().trim().replace(/\n/, '<br />');
nominationText += `${XFD === 'CFD' ? ":'''Nominator's rationale:''' " : ''}${rationale} ~~~~`;
if (XFD === 'TFD') nominationText += "\n"; // formatting is inconsistent accross XfDs
var newText;
 
getWikitext(discussionPage).then(function (wikitext) {
if (!wikitext.match(config.nominationReplacement[0])) {
console.log(wikitext)
console.log(config.nominationReplacement)
var nominationErrorMessage = createNominationErrorMessage();
bodyContent.append(nominationErrorMessage.$element);
} else {
nominationTextnewText += wikitext.replace(...config.displayTemplatenominationReplacement).replaceAllreplace('${pageNamenominationText}', pagenominationText) + '\n';
batchesToProcess.push({
titles: [discussionPage],
textToModify: newText,
summary: nominationSummary,
type: 'text',
doneMessage: 'Nomination added',
headingLabel: 'Creating nomination'
});
resolve();
}
}).catch(function (error) }{
} console.error('An error occurred in fetching wikitext:', error);
var rationale = rationaleInputField.getValue().trim().replace(/\n/, '<br />' resolve();
nominationText += `${XFD === 'CFD' ? ":'''Nominator's rationale:''' " : ''}${rationale} ~~~~`);
} else var newTextresolve();
});
var nominationRegex = /(?:==== ?NEW NOMINATIONS ?====\s*(?:<!-- ?Please add the newest nominations below this line ?-->)?|<noinclude>This is a list of redirects that have been proposed for deletion or other action on .+\.<\/noinclude>)/;
getWikitext(discussionPage)newNomPromise.then(async function (wikitext) {
if ( !wikitextbatches.matchforEach(nominationRegex)batch )=> {
var nominationErrorMessage = createNominationErrorMessagebatchesToProcess.push();{
titles: bodyContent.append(nominationErrorMessagebatch.$element);titles,
} else {textToModify: batch.prependText,
summary: newText = wikitext.replace(nominationRegextaggingSummary, '$&\n\n'+nominationText); // $& contains all the matched text
type: batchesToProcess.push({'prepend',
doneMessage: 'All pages content: bodyContentedited.',
headingLabel: 'Editing nominated pages' + ((batches.length > 1) ? ' ' + batch.label titles: [discussionPage],'')
textToModify: newText,});
summary: nominationSummary,});
if (XFD type:=== 'textRFD',) {
doneMessage: 'Nomination added',batchesToProcess.push({
headingLabelid: 'Creating nominationrfd-notify-target',
titles: }Object.fromEntries(Object.keys(redirectTargets);.map(title => {
resolve let page = new mw.Title(redirectTargets[title]);
} return [page.getTalkPage().getPrefixedText(), title];
})), // return a map of page we want to edit : orginal title - this will (as a dicitionary) remove duplicates, but in an unpredictable way - it seems to retain the last one
}).catch(function (error) {
console.error('An error occurredtextToModify: in fetching wikitext:'redirectTargetNotification, error);
resolve(); summary: redirectTargetNotificationSummary,
}); type: 'append',
} else resolve(); doneMessage: 'All target talk pages notified.',
}); headingLabel: 'Notifying targets'
newNomPromise.then(async function () { });
batches.forEach(batch => {}
if batchesToProcess(notifyCheckbox.pushisSelected()) {
content: bodyContent,batchesToProcess.push({
titles: batch.titlesauthors,
textToModify: batch.prependTextuserNotification,
summary: categorySummaryuserSummary,
type: 'prependappend',
doneMessage: 'All pagesusers editednotified.',
headingLabel: 'EditingNotifying nominated pages' + ((batches.length > 1) ? ' — '+batch.label : 'users')
});
});
if (notifyCheckbox let promise = Promise.isSelectedresolve()) { ;
// abort batchesToProcess.pushhandling is now only in the editPage({) function
for (const batch of batchesToProcess) content: bodyContent,{
// alert(`starting titles:batch authors,${batch.headingLabel}`)
await textToModify: userNotification,processContent(batch);
// alert(`batch summary:${batch.headingLabel} userSummary,done`)
type: 'append',}
 
doneMessage: 'All users notified.',
promise.then(() => headingLabel: 'Notifying users'{
} abortButton.setLabel('Revert');
} // All done
let promise = Promise}).resolvecatch();err => {
// abort handling is now only inconsole.error('Error theoccurred:', editPage(err) function;
for (const batch of batchesToProcess}) {;
await processContent(...Object.values(batch)});
 
}
});
promise.then((}) => {;
}
abortButton.setLabel('Revert');
// All done
}).catch(err => {
console.error('Error occurred:', err);
});
});
});
});
});
}
 
}
// Run the script when the page is ready
$(document).ready(runMassXFD);
// Run the script when the page is ready
 
$(document).ready(runMassXFD);
}());
// </nowiki>
// </nowiki>