MediaWiki:Gadget-morebits.js: Difference between revisions
Content deleted Content added
Amorymeltzer (talk | contribs) Repo at 97b8143: Minor jsdoc fixes and cleanup |
Repo at ac3c1e3: replace es-x/no-array-prototype-includes with unicorn/prefer-includes (#2125) |
||
(24 intermediate revisions by 5 users not shown) | |||
Line 13:
* - {@link Morebits.string} - utilities for manipulating strings
* - {@link Morebits.array} - utilities for manipulating arrays
* - {@link Morebits.ip} - utilities to help process IP addresses
*
* Dependencies:
Line 33 ⟶ 34:
*/
(function() {
/** @lends Morebits */
window.Morebits = Morebits;
/**
* i18n support for strings in Morebits
*/
Morebits.i18n = {
parser: null,
/**
* Set an i18n library to use with Morebits.
* Examples:
* Use jquery-i18n:
* Morebits.i18n.setParser({ get: $.i18n });
* Use banana-i18n or orange-i18n:
* var banana = new Banana('en');
* Morebits.i18n.setParser({ get: banana.i18n });
*
* @param {Object} parser
*/
setParser: function(parser) {
if (!parser || typeof parser.get !== 'function') {
throw new Error('Morebits.i18n: parser must implement get()');
}
Morebits.i18n.parser = parser;
},
/**
* @private
* @return {string}
*/
getMessage: function () {
const args = Array.prototype.slice.call(arguments); // array of size `n`
// 1st arg: message name
// 2nd to (n-1)th arg: message parameters
// nth arg: legacy English fallback
const msgName = args[0];
const fallback = args[args.length - 1];
if (!Morebits.i18n.parser) {
return fallback;
}
// i18n libraries are generally invoked with variable number of arguments
// as msg(msgName, ...parameters)
const i18nMessage = Morebits.i18n.parser.get.apply(null, args.slice(0, -1));
// if no i18n message exists, i18n libraries generally give back the message name
if (i18nMessage === msgName) {
return fallback;
}
return i18nMessage;
}
};
// shortcut
const msg = Morebits.i18n.getMessage;
/**
* Wiki-specific configurations for Morebits
*/
Morebits.l10n = {
/**
* Local aliases for "redirect" magic word.
* Check using api.php?action=query&format=json&meta=siteinfo&formatversion=2&siprop=magicwords
*/
redirectTagAliases: ['#REDIRECT'],
/**
* Takes a string as argument and checks if it is a timestamp or not
* If not, it returns null. If yes, it returns an array of integers
* in the format [year, month, date, hour, minute, second]
* which can be passed to Date.UTC()
*
* @param {string} str
* @return {number[] | null}
*/
signatureTimestampFormat: function (str) {
// HH:mm, DD Month YYYY (UTC)
const rgx = /(\d{2}):(\d{2}), (\d{1,2}) (\w+) (\d{4}) \(UTC\)/;
const match = rgx.exec(str);
if (!match) {
return null;
}
const month = Morebits.date.localeData.months.indexOf(match[4]);
if (month === -1) {
return null;
}
// ..... year ... month .. date ... hour .... minute
return [match[5], month, match[3], match[1], match[2]];
}
};
/**
Line 45 ⟶ 129:
*
* @param {string} group - e.g. `sysop`, `extendedconfirmed`, etc.
* @
*/
Morebits.userIsInGroup = function (group) {
return mw.config.get('wgUserGroups').
};
/**
* Hardcodes whether the user is a sysop, used a lot.
*
* @type {boolean}
Line 57 ⟶ 142:
/**
* Deprecated as of February 2021, use {@link Morebits.ip.sanitizeIPv6}.
*
* @deprecated Use {@link Morebits.ip.sanitizeIPv6}.
* Converts an IPv6 address to the canonical form stored and used by MediaWiki.
* JavaScript translation of the {@link https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/core/+/8eb6ac3e84ea3312d391ca96c12c49e3ad0753bb/includes/utils/IP.php#131|`IP::sanitizeIP()`}
* function from the IPUtils library.
* normalized, and expanded to 8 words.
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @
*/
Morebits.sanitizeIPv6 = function (address) {
console.warn('NOTE: Morebits.sanitizeIPv6 was renamed to Morebits.ip.sanitizeIPv6 in February 2021, please use that instead'); // eslint-disable-line no-console
};
Line 116 ⟶ 163:
* detect Module:RfD, with the same failure points.
*
* @
*/
Morebits.isPageRedirect = function() {
Line 129 ⟶ 176:
*/
Morebits.pageNameNorm = mw.config.get('wgPageName').replace(/_/g, ' ');
/**
Line 137 ⟶ 183:
*
* @param {string} pageName - Page name without namespace.
* @
*/
Morebits.pageNameRegex = function(pageName) {
Line 143 ⟶ 189:
return '';
}
remainder = Morebits.string.escapeRegExp(pageName.slice(1));
if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) {
Line 149 ⟶ 195:
}
return Morebits.string.escapeRegExp(firstChar) + remainder;
};
/**
* Converts string or array of DOM nodes into an HTML fragment.
* Wikilink syntax (`[[...]]`) is transformed into HTML anchor.
* Used in Morebits.quickForm and Morebits.status
*
* @internal
* @param {string|Node|(string|Node)[]} input
* @return {DocumentFragment}
*/
Morebits.createHtml = function(input) {
const fragment = document.createDocumentFragment();
if (!input) {
return fragment;
}
if (!Array.isArray(input)) {
input = [ input ];
}
for (let i = 0; i < input.length; ++i) {
if (input[i] instanceof Node) {
fragment.appendChild(input[i]);
} else {
$.parseHTML(Morebits.createHtml.renderWikilinks(input[i])).forEach((node) => {
fragment.appendChild(node);
});
}
}
return fragment;
};
/**
* Converts wikilinks to HTML anchor tags.
*
* @param text
* @return {*}
*/
Morebits.createHtml.renderWikilinks = function (text) {
const ub = new Morebits.unbinder(text);
// Don't convert wikilinks within code tags as they're used for displaying wiki-code
ub.unbind('<code>', '</code>');
ub.content = ub.content.replace(
/\[\[:?(?:([^|\]]+?)\|)?([^\]|]+?)\]\]/g,
(_, target, text) => {
if (!target) {
target = text;
}
return '<a target="_blank" href="' + mw.util.getUrl(target) +
'" title="' + target.replace(/"/g, '"') + '">' + text + '</a>';
});
return ub.rebind();
};
Line 164 ⟶ 261:
* // returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])'
* Morebits.namespaceRegex([6])
* @
*/
Morebits.namespaceRegex = function(namespaces) {
Line 170 ⟶ 267:
namespaces = [namespaces];
}
let regex; $.each(mw.config.get('wgNamespaceIds'),
if (namespaces.
// Namespaces are completely agnostic as to case,
// and a regex string is more useful/
// so we accept any casing for any letter.
aliases.push(name.split('').map(
}
});
Line 194 ⟶ 290:
return regex;
};
/* **************** Morebits.quickForm **************** */
Line 214 ⟶ 309:
*
* @memberof Morebits.quickForm
* @
*/
Morebits.quickForm.prototype.render = function QuickFormRender() {
ret.names = {};
return ret;
Line 228 ⟶ 323:
* @param {(object|Morebits.quickForm.element)} data - A quickform element, or the object with which
* a quickform element is constructed.
* @
*/
Morebits.quickForm.prototype.append = function QuickFormAppend(data) {
Line 238 ⟶ 333:
*
* Index to Morebits.quickForm.element types:
* - Global attributes: id, className, style, tooltip, extra, $data, adminonly
* - `select`: A combo box (aka drop-down).
* - Attributes: name, label, multiple, size, list, event, disabled
Line 253 ⟶ 348:
* - Attributes: name, list, event
* - Attributes (within list): name, label, value, checked, disabled, event, subgroup
* - `input`: A text input box.
* - Attributes: name, label, value, size, placeholder, maxlength, disabled, required, readonly
* - `number`: A number input box.
* - Attributes: Everything the text `input` has, as well as: min, max, step, list
* - `dyninput`: A set of text boxes with "Remove" buttons and an "Add" button.
* - Attributes: name, label, min, max, inputs, sublabel, value, size, maxlength, event
* - `hidden`: An invisible form field.
* - Attributes: name, value
Line 271 ⟶ 368:
* - `fragment`: A DocumentFragment object.
* - No attributes, and no global attributes except adminonly.
* There is some difference on how types handle the `label` attribute:
* - `div`, `select`, `field`, `checkbox`/`radio`, `input`, `textarea`, `header`, and `dyninput` can accept an array of items,
* and the label item(s) can be `Element`s.
* - `option`, `optgroup`, `_dyninput_cell`, `submit`, and `button` accept only a single string.
*
* @memberof Morebits.quickForm
* @class
* @param {
* specify one of the available types from the index above, as well as any
* relevant and available attributes.
Line 288 ⟶ 389:
this.data = data;
this.childs = [];
};
Line 303 ⟶ 403:
* @param {Morebits.quickForm.element} data - A quickForm element or the object required to
* create the quickForm element.
* @
*/
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) {
if (data instanceof Morebits.quickForm.element) {
child = data;
Line 321 ⟶ 421:
*
* @memberof Morebits.quickForm.element
* @
*/
Morebits.quickForm.element.prototype.render = function QuickFormElementRender(internal_subgroup_id) {
for (
// do not pass internal_subgroup_id to recursive calls
currentNode[1].appendChild(this.childs[i].render());
Line 335 ⟶ 435:
/** @memberof Morebits.quickForm.element */
Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute(data, in_id) {
if (data.adminonly && !Morebits.userIsSysop) {
// hell hack alpha
Line 344 ⟶ 444:
}
switch (data.type) {
case 'form':
Line 358 ⟶ 458:
// fragments can't have any attributes, so just return it straight away
return [ node, node ];
// Sometimes Twinkle uses fancy searchable "select" elements. This is powered by the third party library "select2". Activate it by creating a Morebits "select" element, then call `$('select[name=sub_group]').select2({});` or similar towards the end of your main code.
case 'select':
node = document.createElement('div');
Line 365 ⟶ 466:
label = node.appendChild(document.createElement('label'));
label.setAttribute('for', id);
label.appendChild(
label.style.marginRight = '3px';
}
var select = node.appendChild(document.createElement('select'));
Line 397 ⟶ 499:
}
}
break;
case 'option':
Line 430 ⟶ 532:
node = document.createElement('fieldset');
label = node.appendChild(document.createElement('legend'));
label.appendChild(
if (data.name) {
node.setAttribute('name', data.name);
Line 443 ⟶ 545:
if (data.list) {
for (i = 0; i < data.list.length; ++i) {
current = data.list[i];
var cur_div;
Line 477 ⟶ 579:
}
label = cur_div.appendChild(document.createElement('label'));
label.appendChild(Morebits.createHtml(current.label));
label.setAttribute('for', cur_id);
if (current.tooltip) {
Line 489 ⟶ 592:
var event;
if (current.subgroup) {
if (!Array.isArray(tmpgroup)) {
Line 499 ⟶ 602:
id: id + '_' + i + '_subgroup'
});
$.each(tmpgroup,
if (!newEl.type) {
newEl.type = data.type;
Line 508 ⟶ 611:
});
subgroup.className = 'quickformSubgroup';
subnode.subgroup = subgroup;
Line 517 ⟶ 620:
e.target.parentNode.appendChild(e.target.subgroup);
if (e.target.type === 'radio') {
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 534 ⟶ 637:
event = function(e) {
if (e.target.checked) {
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 555 ⟶ 658:
}
break;
// input is actually a text-type, so number here inherits the same stuff
case 'number':
case 'input':
node = document.createElement('div');
Line 561 ⟶ 666:
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.appendChild(
label.setAttribute('for', data.id || id);
label.style.marginRight = '3px';
}
subnode = node.appendChild(document.createElement('input'));
subnode.setAttribute('name', data.name);
if (data.
subnode.setAttribute('
} else {
subnode.setAttribute('type', 'number');
['min', 'max', 'step', 'list'].forEach((att) => {
if (data[att]) {
subnode.setAttribute(att, data[att]);
}
});
}
['value', 'size', 'placeholder', 'maxlength'].forEach((att) => {
if (data[att]) {
subnode.setAttribute(att, data[att]);
}
});
['disabled', 'required', 'readonly'].forEach((att) => {
if (data[att]) {
subnode.setAttribute(att, att);
}
});
if (data.event) {
subnode.addEventListener('keyup', data.event, false);
}
childContainer = subnode;
break;
case 'dyninput':
Line 598 ⟶ 708:
label = node.appendChild(document.createElement('h5'));
label.appendChild(
var listNode = node.appendChild(document.createElement('div'));
Line 607 ⟶ 716:
disabled: min >= max,
event: function(e) {
e.target.area.appendChild(new_node.render());
Line 621 ⟶ 730:
var sublist = {
type: '
remove: false,
maxlength: data.maxlength,
event: data.event,
inputs: data.inputs || [{
// compatibility
label: data.sublabel || data.label,
name: data.name,
value: data.value,
size: data.size
}]
};
for (i = 0; i < min; ++i) {
listNode.appendChild(elem.render());
}
Line 644 ⟶ 756:
moreButton.counter = 0;
break;
case '
node = document.createElement('div');
data.inputs.forEach((subdata) => {
const cell = new Morebits.quickForm.element($.extend(subdata, { type: '_dyninput_cell' }));
node.appendChild(cell.render());
});
if (data.remove) {
const remove = this.compute({
type: 'button',
label: 'remove',
event: function(e) {
const list = e.target.listnode;
const node = e.target.inputnode;
const more = e.target.morebutton;
list.removeChild(node);
--more.counter;
more.removeAttribute('disabled');
e.stopPropagation();
}
});
node.appendChild(remove[0]);
const removeButton = remove[1];
removeButton.inputnode = node;
removeButton.listnode = data.listnode;
removeButton.morebutton = data.morebutton;
}
break;
case '_dyninput_cell': // Private, similar to normal input
node = document.createElement('span');
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.appendChild(document.createTextNode(data.label));
label.setAttribute('for', id + '_input');
label.style.marginRight = '3px';
}
subnode = node.appendChild(document.createElement('input'));
subnode.setAttribute('id', id + '_input');
if (data.value) {
subnode.setAttribute('value', data.value);
Line 659 ⟶ 802:
subnode.setAttribute('name', data.name);
subnode.setAttribute('type', 'text');
subnode.setAttribute('data-dyninput', 'data-dyninput');
if (data.size) {
subnode.setAttribute('size', data.size);
Line 664 ⟶ 808:
if (data.maxlength) {
subnode.setAttribute('maxlength', data.maxlength);
}
if (data.required) {
subnode.setAttribute('required', 'required');
}
if (data.disabled) {
subnode.setAttribute('required', 'disabled');
}
if (data.event) {
subnode.addEventListener('keyup', data.event, false);
}
node.style.marginRight = '3px';
break;
case 'hidden':
Line 699 ⟶ 829:
case 'header':
node = document.createElement('h5');
node.appendChild(
break;
case 'div':
Line 707 ⟶ 837:
}
if (data.label) {
const result = document.createElement('span');
result.className = 'quickformDescription';
node.appendChild(result);
}
Line 724 ⟶ 845:
case 'submit':
node = document.createElement('span');
if (data.label) {
}
if (data.disabled) {
}
break;
case 'button':
node = document.createElement('span');
if (data.label) {
}
if (data.disabled) {
}
if (data.event) {
}
break;
Line 754 ⟶ 875:
if (data.label) {
label = node.appendChild(document.createElement('h5'));
labelElement.
labelElement.setAttribute('for', data.id || id);
label.appendChild(labelElement);
Line 779 ⟶ 900:
subnode.value = data.value;
}
break;
default:
Line 785 ⟶ 906:
}
if (!
}
if (data.tooltip) {
Line 793 ⟶ 914:
if (data.extra) {
}
if (data.$data) {
$(childContainer).data(data.$data);
}
if (data.style) {
}
if (data.className) {
data.className;
}
return [ node,
};
Line 812 ⟶ 936:
*
* @memberof Morebits.quickForm.element
* @requires
* @param {HTMLElement} node - The HTML element beside which a tooltip is to be generated.
* @param {
*/
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) {
tooltipButton.className = 'morebits-tooltipButton';
tooltipButton.title = data.tooltip; // Provides the content for jQuery UI
tooltipButton.appendChild(document.createTextNode(msg('tooltip-mark', '?')));
$(tooltipButton).tooltip({
position: { my: 'left top', at: 'center bottom', collision: 'flipfit' },
Line 827 ⟶ 951:
});
};
// Some utility methods for manipulating quickForms after their creation:
Line 838 ⟶ 961:
* @memberof Morebits.quickForm
* @param {HTMLFormElement} form
* @
*/
Morebits.quickForm.getInputData = function(form) {
for (
if (field.disabled || !field.name || !field.type ||
field.type === 'submit' || field.type === 'button') {
Line 852 ⟶ 975:
// For elements in subgroups, quickform prepends element names with
// name of the parent group followed by a period, get rid of that.
switch (field.type) {
Line 875 ⟶ 998:
case 'text': // falls through
case 'textarea':
result[fieldNameNorm] = result[fieldNameNorm] || [];
result[fieldNameNorm].push(field.value.trim());
} else {
result[fieldNameNorm] = field.value.trim();
}
break;
default: // could be select-one, date, number, email, etc
Line 886 ⟶ 1,014:
return result;
};
/**
Line 894 ⟶ 1,021:
* @param {HTMLFormElement} form
* @param {string} fieldName - The name or id of the fields.
* @
*/
Morebits.quickForm.getElements = function QuickFormGetElements(form, fieldName) {
fieldName = $.escapeSelector(fieldName); // sanitize input
if ($elements.length > 0) {
return $elements.toArray();
Line 914 ⟶ 1,041:
* @param {HTMLInputElement[]} elementArray - Array of checkbox or radio elements.
* @param {string} value - Value to search for.
* @
*/
Morebits.quickForm.getCheckboxOrRadio = function QuickFormGetCheckboxOrRadio(elementArray, value) {
if (found.length > 0) {
return found[0];
Line 932 ⟶ 1,057:
* @memberof Morebits.quickForm
* @param {HTMLElement} element
* @
*/
Morebits.quickForm.getElementContainer = function QuickFormGetElementContainer(element) {
Line 951 ⟶ 1,076:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.getElementLabelObject = function QuickFormGetElementLabelObject(element) {
Line 974 ⟶ 1,099:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.getElementLabel = function QuickFormGetElementLabel(element) {
if (!labelElement) {
Line 991 ⟶ 1,116:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} labelText
* @
*/
Morebits.quickForm.setElementLabel = function QuickFormSetElementLabel(element, labelText) {
if (!labelElement) {
Line 1,009 ⟶ 1,134:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} temporaryLabelText
* @
*/
Morebits.quickForm.overrideElementLabel = function QuickFormOverrideElementLabel(element, temporaryLabelText) {
Line 1,023 ⟶ 1,148:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.resetElementLabel = function QuickFormResetElementLabel(element) {
Line 1,053 ⟶ 1,178:
$(Morebits.quickForm.getElementContainer(element)).find('.morebits-tooltipButton').toggle(visibility);
};
/**
Line 1,062 ⟶ 1,185:
* Get checked items in the form.
*
* @
* @param {string} name - Find checked property of elements (i.e. a checkbox
* or a radiobutton) with the given name, or select options that have selected
Line 1,068 ⟶ 1,191:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @
* checked property set to true.
*/
HTMLFormElement.prototype.getChecked = function(name, type) {
if (!elements) {
return [];
}
if (elements instanceof HTMLSelectElement) {
for (i = 0; i < options.length; ++i) {
if (options[i].selected) {
Line 1,116 ⟶ 1,239:
* Does the same as {@link HTMLFormElement.getChecked|getChecked}, but with unchecked elements.
*
* @
* @param {string} name - Find checked property of elements (i.e. a checkbox
* or a radiobutton) with the given name, or select options that have selected
Line 1,122 ⟶ 1,245:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @
* checked property set to true.
*/
HTMLFormElement.prototype.getUnchecked = function(name, type) {
if (!elements) {
return [];
}
if (elements instanceof HTMLSelectElement) {
for (i = 0; i < options.length; ++i) {
if (!options[i].selected) {
Line 1,166 ⟶ 1,289:
return return_array;
};
/**
* Utilities to help process IP addresses.
*
* @namespace Morebits.ip
* @memberof Morebits
*/
Morebits.ip = {
/**
* Converts an IPv6 address to the canonical form stored and used by MediaWiki.
* JavaScript translation of the {@link https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/core/+/8eb6ac3e84ea3312d391ca96c12c49e3ad0753bb/includes/utils/IP.php#131|`IP::sanitizeIP()`}
* function from the IPUtils library. Addresses are verbose, uppercase,
* normalized, and expanded to 8 words.
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @return {string}
*/
sanitizeIPv6: function (address) {
address = address.trim();
if (address === '') {
return null;
}
if (!mw.util.isIPv6Address(address, true)) {
return address; // nothing else to do for IPv4 addresses or invalid ones
}
// Remove any whitespaces, convert to upper case
address = address.toUpperCase();
// Expand zero abbreviations
const abbrevPos = address.indexOf('::');
if (abbrevPos > -1) {
// We know this is valid IPv6. Find the last index of the
// address before any CIDR number (e.g. "a:b:c::/24").
const CIDRStart = address.indexOf('/');
const addressEnd = CIDRStart !== -1 ? CIDRStart - 1 : address.length - 1;
// If the '::' is at the beginning...
let repeat, extra, pad;
if (abbrevPos === 0) {
repeat = '0:';
extra = address === '::' ? '0' : ''; // for the address '::'
pad = 9; // 7+2 (due to '::')
// If the '::' is at the end...
} else if (abbrevPos === (addressEnd - 1)) {
repeat = ':0';
extra = '';
pad = 9; // 7+2 (due to '::')
// If the '::' is in the middle...
} else {
repeat = ':0';
extra = ':';
pad = 8; // 6+2 (due to '::')
}
let replacement = repeat;
pad -= address.split(':').length - 1;
for (let i = 1; i < pad; i++) {
replacement += repeat;
}
replacement += extra;
address = address.replace('::', replacement);
}
// Remove leading zeros from each bloc as needed
return address.replace(/(^|:)0+([0-9A-Fa-f]{1,4})/g, '$1$2');
},
/**
* Determine if the given IP address is a range. Just conjoins
* `mw.util.isIPAddress` with and without the `allowBlock` option.
*
* @param {string} ip
* @return {boolean} - True if given a valid IP address range, false otherwise.
*/
isRange: function (ip) {
return mw.util.isIPAddress(ip, true) && !mw.util.isIPAddress(ip);
},
/**
* Check that an IP range is within the CIDR limits. Most likely to be useful
* in conjunction with `wgRelevantUserName`. CIDR limits are hardcoded as /16
* for IPv4 and /32 for IPv6.
*
* @return {boolean} - True for valid ranges within the CIDR limits,
* otherwise false (ranges outside the limit, single IPs, non-IPs).
*/
validCIDR: function (ip) {
if (Morebits.ip.isRange(ip)) {
const subnet = parseInt(ip.match(/\/(\d{1,3})$/)[1], 10);
if (subnet) { // Should be redundant
if (mw.util.isIPv6Address(ip, true)) {
if (subnet >= 32) {
return true;
}
} else {
if (subnet >= 16) {
return true;
}
}
}
}
return false;
},
/**
* Get the /64 subnet for an IPv6 address.
*
* @param {string} ipv6 - The IPv6 address, with or without a subnet.
* @return {boolean|string} - False if not IPv6 or bigger than a 64,
* otherwise the (sanitized) /64 address.
*/
get64: function (ipv6) {
if (!ipv6 || !mw.util.isIPv6Address(ipv6, true)) {
return false;
}
const subnetMatch = ipv6.match(/\/(\d{1,3})$/);
if (subnetMatch && parseInt(subnetMatch[1], 10) < 64) {
return false;
}
ipv6 = Morebits.ip.sanitizeIPv6(ipv6);
const ip_re = /^((?:[0-9A-F]{1,4}:){4})(?:[0-9A-F]{1,4}:){3}[0-9A-F]{1,4}(?:\/\d{1,3})?$/;
// eslint-disable-next-line no-useless-concat
return ipv6.replace(ip_re, '$1' + '0:0:0:0/64');
}
};
/**
Line 1,201 ⟶ 1,420:
/**
* @param {string} str
* @
*/
toUpperCaseFirstChar: function(str) {
str = str.toString();
return str.
},
/**
* @param {string} str
* @
*/
toLowerCaseFirstChar: function(str) {
str = str.toString();
return str.
},
Line 1,225 ⟶ 1,444:
* @param {string} end
* @param {(string[]|string)} [skiplist]
* @
* @throws If the `start` and `end` strings aren't of the same length.
* @throws If `skiplist` isn't an array or string
Line 1,233 ⟶ 1,452:
throw new Error('start marker and end marker must be of the same length');
}
if (!Array.isArray(skiplist)) {
if (skiplist === undefined) {
Line 1,245 ⟶ 1,464:
}
}
for (
for (
if (str.substr(i, skiplist[j].length) === skiplist[j]) {
i += skiplist[j].length - 1;
Line 1,279 ⟶ 1,498:
* @param {string} str
* @param {boolean} [addSig]
* @
*/
formatReasonText: function(str, addSig) {
// eslint-disable-next-line no-useless-concat
unbinder.unbind('<no' + 'wiki>', '</no' + 'wiki>');
unbinder.content = unbinder.content.replace(/\|/g, '{{subst:!}}');
reason = unbinder.rebind();
if (addSig) {
if (sigIndex === -1 || sigIndex !== reason.length - sig.length) {
reason += ' ' + sig;
Line 1,302 ⟶ 1,522:
*
* @param {string} str
* @
*/
formatReasonForLog: function(str) {
Line 1,322 ⟶ 1,542:
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @
*/
safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) {
Line 1,335 ⟶ 1,555:
*
* @param {string} expiry
* @
*/
isInfinity: function morebitsStringIsInfinity(expiry) {
return ['indefinite', 'infinity', 'infinite', 'never'].
},
Line 1,344 ⟶ 1,564:
* Escapes a string to be used in a RegExp, replacing spaces and
* underscores with `[_ ]` as they are often equivalent.
*
* @param {string} text - String to be escaped.
* @
*/
escapeRegExp: function(text) {
Line 1,353 ⟶ 1,572:
}
};
/**
Line 1,366 ⟶ 1,584:
*
* @param {Array} arr
* @
* @throws When provided a non-array.
*/
uniq: function(arr) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.uniq');
}
return arr.filter(
},
Line 1,382 ⟶ 1,598:
*
* @param {Array} arr
* @
* removed; subsequent instances of those values (duplicates) remain.
* @throws When provided a non-array.
Line 1,388 ⟶ 1,604:
dups: function(arr) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.dups');
}
return arr.filter(
},
/**
Line 1,401 ⟶ 1,614:
* @param {Array} arr
* @param {number} size - Size of each chunk (except the last, which could be different).
* @
* @throws When provided a non-array.
*/
chunk: function(arr, size) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.chunk');
}
if (typeof size !== 'number' || size <= 0) { // pretty impossible to do anything :)
return [ arr ]; // we return an array consisting of this array.
}
for (
result[i] = arr.slice(i * size, (i + 1) * size);
}
Line 1,428 ⟶ 1,641:
* @namespace Morebits.select2
* @memberof Morebits
* @requires
*/
Morebits.select2 = {
Line 1,437 ⟶ 1,650:
*/
optgroupFull: function(params, data) {
if (result && params.term &&
data.text.toUpperCase().
result.children = data.children;
}
Line 1,449 ⟶ 1,662:
/** Custom matcher that matches from the beginning of words only. */
wordBeginning: function(params, data) {
if (!params.term || (result &&
new RegExp('\\b' + mw.util.escapeRegExp(params.term), 'i').test(result.text))) {
Line 1,461 ⟶ 1,674:
/** Underline matched part of options. */
highlightSearchMatches: function(data) {
if (!searchTerm || data.loading) {
return data.text;
}
if (idx < 0) {
return data.text;
Line 1,492 ⟶ 1,705:
return;
}
if (!$target.length) {
return;
}
$target = $target.prev();
$target.select2('open');
$target.data('select2').selection.$search;
// Use DOM .focus() to work around a jQuery 3.6.0 regression (https://github.com/select2/select2/issues/5993)
search[0].focus();
}
};
/**
Line 1,544 ⟶ 1,757:
throw new Error('Both prefix and postfix must be provided');
}
this.content = this.content.replace(re, Morebits.unbinder.getCallback(this));
},
Line 1,551 ⟶ 1,764:
* Restore the hidden portion of the `content` string.
*
* @
*/
rebind: function UnbinderRebind() {
content.self = this;
for (
if (Object.prototype.hasOwnProperty.call(this.history, current)) {
content = content.replace(current, this.history[current]);
Line 1,572 ⟶ 1,785:
Morebits.unbinder.getCallback = function UnbinderGetCallback(self) {
return function UnbinderCallback(match) {
self.history[current] = match;
++self.counter;
Line 1,578 ⟶ 1,791:
};
};
/* **************** Morebits.date **************** */
Line 1,591 ⟶ 1,802:
*/
Morebits.date = function() {
// Check MediaWiki formats
Line 1,598 ⟶ 1,809:
// 14-digit string will be interpreted differently.
if (args.length === 1) {
if (/^\d{14}$/.test(param)) {
// YYYYMMDDHHmmss
if (digitMatch) {
// ..... year ... month .. date ... hour .... minute ..... second
this.
}
} else if (typeof param === 'string') {
// Wikitext signature timestamp
if (dateParts) {
this.
}
}
}
if (!this.
// Try standard date
this.
}
Line 1,639 ⟶ 1,850:
*/
Morebits.date.localeData = {
// message names here correspond to MediaWiki message names
months: [msg('january', 'January'), msg('february', 'February'), msg('march', 'March'),
msg('october', 'October'), msg('november', 'November'), msg('december', 'December')],
monthsShort: [msg('jan', 'Jan'), msg('feb', 'Feb'), msg('mar', 'Mar'),
msg('apr', 'Apr'), msg('may', 'May'), msg('jun', 'Jun'),
msg('jul', 'Jul'), msg('aug', 'Aug'), msg('sep', 'Sep'),
msg('oct', 'Oct'), msg('nov', 'Nov'), msg('dec', 'Dec')],
days: [msg('sunday', 'Sunday'), msg('monday', 'Monday'), msg('tuesday', 'Tuesday'),
msg('wednesday', 'Wednesday'), msg('thursday', 'Thursday'), msg('friday', 'Friday'),
msg('saturday', 'Saturday')],
daysShort: [msg('sun', 'Sun'), msg('mon', 'Mon'), msg('tue', 'Tue'),
msg('wed', 'Wed'), msg('thu', 'Thu'), msg('fri', 'Fri'),
msg('sat', 'Sat')],
relativeTimes: {
thisDay: msg('relative-today', '[Today at] h:mm A'),
prevDay: msg('relative-prevday', '[Yesterday at] h:mm A'),
nextDay: msg('relative-nextday', '[Tomorrow at] h:mm A'),
thisWeek: msg('relative-thisweek', 'dddd [at] h:mm A'),
pastWeek: msg('relative-pastweek', '[Last] dddd [at] h:mm A'),
other: msg('relative-other', 'YYYY-MM-DD')
}
};
/**
* Map units with getter/setter function names, for `add` and `subtract`
* methods.
*
* @memberof Morebits.date
* @type {object.<string, string>}
* @property {string} seconds
* @property {string} minutes
* @property {string} hours
* @property {string} days
* @property {string} weeks
* @property {string} months
* @property {string} years
*/
Morebits.date.unitMap = {
seconds: 'Seconds',
minutes: 'Minutes',
hours: 'Hours',
days: 'Date',
weeks: 'Week', // Not a function but handled in `add` through cunning use of multiplication
months: 'Month',
years: 'FullYear'
};
Morebits.date.prototype = {
/** @
isValid: function() {
return !isNaN(this.getTime());
Line 1,675 ⟶ 1,908:
/**
* @param {(Date|Morebits.date)} date
* @
*/
isBefore: function(date) {
Line 1,682 ⟶ 1,915:
/**
* @param {(Date|Morebits.date)} date
* @
*/
isAfter: function(date) {
Line 1,688 ⟶ 1,921:
},
/** @
getUTCMonthName: function() {
return Morebits.date.localeData.months[this.getUTCMonth()];
},
/** @
getUTCMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getUTCMonth()];
},
/** @
getMonthName: function() {
return Morebits.date.localeData.months[this.getMonth()];
},
/** @
getMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getMonth()];
},
/** @
getUTCDayName: function() {
return Morebits.date.localeData.days[this.getUTCDay()];
},
/** @
getUTCDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getUTCDay()];
},
/** @
getDayName: function() {
return Morebits.date.localeData.days[this.getDay()];
},
/** @
getDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getDay()];
Line 1,722 ⟶ 1,955:
/**
* Add a given number of minutes, hours, days, weeks, months, or years to the date.
* This is done in-place. The modified date object is also returned, allowing chaining.
*
Line 1,728 ⟶ 1,961:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @
*/
add: function(number, unit) {
let num = parseInt(number, 10); // normalize
throw new Error('Invalid number "' + number + '" provided.');
}
unit = unit.toLowerCase(); // normalize
const unitMap = Morebits.date.unitMap;
let unitNorm = unitMap[unit] || unitMap[unit + 's']; // so that both singular and plural forms work
if (unitNorm) {
// No built-in week functions, so rather than build out ISO's getWeek/setWeek, just multiply
// Probably can't be used for Julian->Gregorian changeovers, etc.
if (unitNorm === 'Week') {
unitNorm = 'Date';
num *= 7;
}
this['set' + unitNorm](this['get' + unitNorm]() + num);
return this;
}
Line 1,749 ⟶ 1,985:
/**
* Subtracts a given number of minutes, hours, days, weeks, months, or years to the date.
* This is done in-place. The modified date object is also returned, allowing chaining.
*
Line 1,755 ⟶ 1,991:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @
*/
subtract: function(number, unit) {
Line 1,768 ⟶ 2,004:
* |--------|--------|
* | H | Hours (24-hour) |
* | HH | Hours (24-hour, padded to 2 digits) |
* | h | Hours (12-hour) |
* | hh | Hours (12-hour, padded to 2 digits) |
* | A | AM or PM |
* | m | Minutes |
* | mm | Minutes (padded to 2 digits) |
* | s | Seconds |
* | ss | Seconds (padded to 2 digits) |
* | SSS | Milliseconds fragment,
* | d | Day number of the week (Sun=0) |
* | ddd | Abbreviated day name |
* | dddd | Full day name |
* | D | Date |
* | DD | Date (padded to 2 digits) |
* | M | Month number (
* | MM | Month number (
* | MMM | Abbreviated month name |
* | MMMM | Full month name |
Line 1,795 ⟶ 2,031:
* @param {(string|number)} [zone=system] - `system` (for browser-default time zone),
* `utc`, or specify a time zone as number of minutes relative to UTC.
* @
*/
format: function(formatstr, zone) {
Line 1,801 ⟶ 2,037:
return 'Invalid date'; // Put the truth out, preferable to "NaNNaNNan NaN:NaN" or whatever
}
// create a new date object that will contain the date to display as system time
if (zone === 'utc') {
Line 1,815 ⟶ 2,051:
}
len = len || 2; // Up to length of 00 + 1
return ('00' + num).toString().slice(0 - len);
};
HH: pad(h24), H: h24, hh: pad(h12), h: h12, A: amOrPm,
mm: pad(m), m: m,
Line 1,833 ⟶ 2,069:
};
unbinder.unbind('\\[', '\\]');
unbinder.content = unbinder.content.replace(
Line 1,841 ⟶ 2,077:
*/
/H{1,2}|h{1,2}|m{1,2}|s{1,2}|SSS|d(d{2,3})?|D{1,2}|M{1,4}|Y{1,2}(Y{2})?|A/g,
);
return unbinder.rebind().replace(/\[(.*?)\]/g, '$1');
Line 1,854 ⟶ 2,088:
* @param {(string|number)} [zone=system] - 'system' (for browser-default time zone),
* 'utc' (for UTC), or specify a time zone as number of minutes past UTC.
* @
*/
calendar: function(zone) {
// Zero out the hours, minutes, seconds and milliseconds - keeping only the date;
// find the difference. Note that setHours() returns the same thing as getTime().
new Date(this).setHours(0, 0, 0, 0)) / 8.64e7;
switch (true) {
Line 1,881 ⟶ 2,115:
* as `==December 2019==` or `=== Jan 2018 ===`.
*
* @
*/
monthHeaderRegex: function() {
Line 1,893 ⟶ 2,127:
* @param {number} [level=2] - Header level. Pass 0 for just the text
* with no wikitext markers (==).
* @
*/
monthHeader: function(level) {
Line 1,900 ⟶ 2,134:
level = isNaN(level) ? 2 : level;
const header = '='.repeat(level);
if (header.length) { // wikitext-formatted header
Line 1,913 ⟶ 2,147:
// Allow native Date.prototype methods to be used on Morebits.date objects
Object.getOwnPropertyNames(Date.prototype).forEach(
Morebits.date.prototype[func] = function() {
return this.privateDate[func].apply(this.privateDate, Array.prototype.slice.call(arguments));
};
});
/* **************** Morebits.wiki **************** */
Line 1,936 ⟶ 2,166:
* @deprecated in favor of Morebits.isPageRedirect as of November 2020
* @memberof Morebits.wiki
* @
*/
Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() {
Line 1,942 ⟶ 2,172:
return Morebits.isPageRedirect();
};
/* **************** Morebits.wiki.actionCompleted **************** */
Line 2,004 ⟶ 2,233:
}
}
window.setTimeout(
window.___location = Morebits.wiki.actionCompleted.redirect;
}, Morebits.wiki.actionCompleted.timeOut);
Line 2,028 ⟶ 2,257:
}
};
/* **************** Morebits.wiki.api **************** */
Line 2,047 ⟶ 2,275:
* @class
* @param {string} currentAction - The current action (required).
* @param {
* @param {Function} [onSuccess] - The function to call when request is successful.
* @param {Morebits.status} [statusElement] - A Morebits.status object to use for status messages.
Line 2,057 ⟶ 2,285:
this.query.assert = 'user';
// Enforce newer error formats, preferring html
if (!query.errorformat || !['wikitext', 'plaintext'].
this.query.errorformat = 'html';
}
Line 2,078 ⟶ 2,306:
} else if (query.format === 'json' && !query.formatversion) {
this.query.formatversion = '2';
} else if (!['xml', 'json'].
this.statelem.error('Invalid API format: only xml and json are supported.');
}
// Ignore tags for queries and most common unsupported actions, produces warnings
if (query.action && ['query', 'review', 'stabilize', 'pagetriageaction', 'watch'].
delete query.tags;
} else if (!query.tags && morebitsWikiChangeTag) {
Line 2,094 ⟶ 2,322:
onSuccess: null,
onError: null,
parent: window,
query: null,
response: null,
responseXML: null,
statelem: null,
statusText: null, // result received from the API, normally "success" or "error"
errorCode: null, // short text error code, if any, as documented in the MediaWiki API
Line 2,122 ⟶ 2,350:
* Carry out the request.
*
* @param {
* really want to give jQuery some extra parameters.
* @
*/
post: function(callerAjaxParameters) {
Line 2,130 ⟶ 2,358:
++Morebits.wiki.numberOfActionsLeft;
if (Array.isArray(val)) {
return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|');
Line 2,139 ⟶ 2,367:
// token should always be the last item in the query string (bug TW-B-0013)
context: this,
type: this.query.action === 'query' ? 'GET' : 'POST',
Line 2,180 ⟶ 2,408:
this.onSuccess.call(this.parent, this);
} else {
this.statelem.info(msg('done', 'done'));
}
Line 2,192 ⟶ 2,420:
this.statusText = statusText;
this.errorThrown = errorThrown; // frequently undefined
this.errorText = msg('api-error', statusText, jqXHR.statusText, statusText + ' "' + jqXHR.statusText + '" occurred while contacting the API.');
return this.returnError();
}
Line 2,201 ⟶ 2,429:
returnError: function(callerAjaxParameters) {
if (this.errorCode === 'badtoken' && !this.badtokenRetry) {
this.statelem.warn(msg('invalid-token-retrying', 'Invalid token. Getting a new token and retrying...'));
this.badtokenRetry = true;
// Get a new CSRF token and retry. If the original action needs a different
// type of action than CSRF, we do one pointless retry before bailing out
return Morebits.wiki.api.getToken().then(
this.query.token = token;
return this.post(callerAjaxParameters);
}
}
Line 2,245 ⟶ 2,473:
}
};
/** Retrieves wikitext from a page. Caching enabled, duration 1 day. */
Morebits.wiki.getCachedJson = function(title) {
const query = {
action: 'query',
prop: 'revisions',
titles: title,
rvslots: '*',
rvprop: 'content',
format: 'json',
smaxage: '86400', // cache for 1 day
maxage: '86400' // cache for 1 day
};
return new Morebits.wiki.api('', query).post().then((apiobj) => {
apiobj.getStatusElement().unlink();
const response = apiobj.getResponse();
const wikitext = response.query.pages[0].revisions[0].slots.main.content;
return JSON.parse(wikitext);
});
};
Line 2,264 ⟶ 2,512:
morebitsWikiApiUserAgent = (ua ? ua + ' ' : '') + 'morebits.js ([[w:WT:TW]])';
};
/**
Line 2,276 ⟶ 2,522:
*/
var morebitsWikiChangeTag = '';
/**
Line 2,282 ⟶ 2,527:
*
* @memberof Morebits.wiki.api
* @
*/
Morebits.wiki.api.getToken = function() {
action: 'query',
meta: 'tokens',
Line 2,291 ⟶ 2,536:
format: 'json'
});
return tokenApi.post().then(
};
/* **************** Morebits.wiki.page **************** */
Line 2,336 ⟶ 2,578:
* 2. The sequence for append/prepend/newSection could be slightly shortened,
* but it would require significant duplication of code for little benefit.
*
* @memberof Morebits.wiki
Line 2,348 ⟶ 2,589:
if (!status) {
status = msg('opening-page', pageName, 'Opening page "' + pageName + '"');
}
Line 2,359 ⟶ 2,600:
* @private
*/
// backing fields for public properties
pageName: pageName,
Line 2,365 ⟶ 2,606:
editSummary: null,
changeTags: null,
testActions: null,
callbackParameters: null,
statusElement: status instanceof Morebits.status ? status : new Morebits.status(status),
Line 2,371 ⟶ 2,612:
// - edit
pageText: null,
editMode: 'all',
appendText: null,
prependText: null,
newSectionText: null,
newSectionTitle: null,
Line 2,403 ⟶ 2,644:
protectCreate: null,
protectCascade: null,
// - delete
deleteTalkPage: false,
// - undelete
undeleteTalkPage: false,
// - creation lookup
Line 2,431 ⟶ 2,678:
onSaveFailure: null,
onLookupCreationSuccess: null,
onLookupCreationFailure: null,
onMoveSuccess: null,
onMoveFailure: null,
Line 2,464 ⟶ 2,712:
};
/**
Line 2,497 ⟶ 2,745:
if (ctx.editMode === 'all') {
ctx.loadQuery.rvprop = 'content|timestamp';
} else if (ctx.editMode === 'revert') {
ctx.loadQuery.rvprop = 'timestamp';
Line 2,505 ⟶ 2,753:
if (ctx.followRedirect) {
ctx.loadQuery.redirects = '';
}
if (typeof ctx.pageSection === 'number') {
Line 2,514 ⟶ 2,762:
}
ctx.loadApi = new Morebits.wiki.api(msg('retrieving-page', 'Retrieving page...'), ctx.loadQuery, fnLoadSuccess, ctx.statusElement, ctx.onLoadFailure);
ctx.loadApi.setParent(this);
ctx.loadApi.post();
Line 2,526 ⟶ 2,774:
* previous `load()` callbacks to recover from edit conflicts! In this
* case, callers must make the same edit to the new pageText and
*
* `setMaxConflictRetries(0)`.
*
Line 2,537 ⟶ 2,785:
// are we getting our editing token from mw.user.tokens?
if (!ctx.pageLoaded && !canUseMwUserToken) {
Line 2,559 ⟶ 2,807:
// shouldn't happen if canUseMwUserToken === true
if (ctx.fullyProtected && !ctx.suppressProtectWarning &&
!confirm(
msg('protected-indef-edit-warning', ctx.pageName,
'You are about to make an edit to the fully protected page "' + ctx.pageName + '" (protected indefinitely). \n\nClick OK to proceed with the edit, or Cancel to skip this edit.'
) :
msg('protected-edit-warning', ctx.pageName, ctx.fullyProtected,
'You are about to make an edit to the fully protected page "' + ctx.pageName +
'" (protection expiring ' + new Morebits.date(ctx.fullyProtected).calendar('utc') + ' (UTC)). \n\nClick OK to proceed with the edit, or Cancel to skip this edit.'
)
)
) {
ctx.statusElement.error(msg('protected-aborted', 'Edit to fully protected page was aborted.'));
ctx.onSaveFailure(this);
return;
Line 2,569 ⟶ 2,825:
ctx.retries = 0;
action: 'edit',
title: ctx.pageName,
Line 2,581 ⟶ 2,837:
}
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 2,593 ⟶ 2,849:
query.minor = true;
} else {
query.notminor = true;
}
// Set bot edit attribute. If this
if (ctx.botEdit) {
query.bot = true;
Line 2,608 ⟶ 2,864:
return;
}
query.appendtext = ctx.appendText;
break;
case 'prepend':
Line 2,616 ⟶ 2,872:
return;
}
query.prependtext = ctx.prependText;
break;
case 'new':
Line 2,625 ⟶ 2,881:
}
query.section = 'new';
query.text = ctx.newSectionText;
query.sectiontitle = ctx.newSectionTitle || ctx.editSummary; // done by the API, but non-'' values would get treated as text
break;
Line 2,645 ⟶ 2,901:
}
if (['recreate', 'createonly', 'nocreate'].
query[ctx.createOption] = '';
}
Line 2,653 ⟶ 2,909:
}
ctx.saveApi = new Morebits.wiki.api(msg('saving-page', 'Saving page...'), query, fnSaveSuccess, ctx.statusElement, fnSaveError);
ctx.saveApi.setParent(this);
ctx.saveApi.post();
Line 2,721 ⟶ 2,977:
};
/** @
this.getPageName = function() {
return ctx.pageName;
};
/** @
this.getPageText = function() {
return ctx.pageText;
Line 2,763 ⟶ 3,019:
ctx.newSectionTitle = newSectionTitle;
};
// Edit-related setter methods:
Line 2,788 ⟶ 3,042:
ctx.changeTags = tags;
};
/**
Line 2,798 ⟶ 3,051:
* - `null`: create the page if it does not exist, unless it was deleted
* in the moment between loading the page and saving the edit (default).
*/
this.setCreateOption = function(createOption) {
Line 2,839 ⟶ 3,091:
/**
* Set whether and how to watch the page, including setting an expiry.
*
* @param {boolean|string|Morebits.date|Date} [watchlistOption=false] -
* Basically a mix of MW API and Twinkley options available pre-expiry:
* - `true`|`'yes'`|`'watch'`: page will be added to the user's
* watchlist when the action is called. Defaults to an indefinite * watch unless `watchlistExpiry` is provided.
* - `false`|`'
* - `'default'`|`'preferences'`: watchlist status of the page will be
* set based on the user's preference settings when the action is
* called. Defaults to an indefinite watch unless `watchlistExpiry` is
* provided.
* - `'unwatch'`: explicitly unwatch the page.
* - Any other `string` or `number`, or a `Morebits.date` or `Date`
* object: watch page until the specified time, deferring to
* `watchlistExpiry` if provided.
* @param {string|number|Morebits.date|Date} [watchlistExpiry=infinity] -
* A date-like string or number, or a date object. If a string or number,
* can be relative (2 weeks) or other similarly date-like (i.e. NOT "potato"):
* ISO 8601: 2038-01-09T03:14:07Z
* MediaWiki: 20380109031407
* UNIX: 2147483647
* SQL: 2038-01-09 03:14:07
* Can also be `infinity` or infinity-like (`infinite`, `indefinite`, and `never`).
* See {@link https://phabricator.wikimedia.org/source/mediawiki-libs-Timestamp/browse/master/src/ConvertibleTimestamp.php;4e53b859a9580c55958078f46dd4f3a44d0fcaa0$57-109?as=source&blame=off}
*/
this.setWatchlist = function(watchlistOption, watchlistExpiry) {
if (
}
if (typeof watchlistExpiry === 'undefined') {
watchlistExpiry = 'infinity';
} else if (watchlistExpiry instanceof Morebits.date || watchlistExpiry instanceof Date) {
watchlistExpiry = watchlistExpiry.toISOString();
}
switch (watchlistOption) {
case 'nochange':
case 'no':
case false:
case undefined:
ctx.watchlistOption = 'nochange';
// The MW API allows for changing expiry with nochange (as "nochange" refers to the binary status),
// but by keeping this null it will default to any existing expiry, ensure there is actually "no change."
ctx.watchlistExpiry = null;
break;
case 'unwatch':
// expiry unimportant
ctx.watchlistOption = 'unwatch';
break;
case 'preferences':
case 'default':
ctx.watchlistOption = 'preferences';
// The API allows an expiry here, but there is as of yet (T265716)
// no expiry preference option, so it's a bit devoid of context.
ctx.watchlistExpiry = watchlistExpiry;
break;
case 'watch':
case 'yes':
case true:
ctx.watchlistOption = 'watch';
ctx.watchlistExpiry = watchlistExpiry;
break;
default: // Not really a "default" per se but catches "any other string"
ctx.watchlistOption = 'watch';
ctx.watchlistExpiry = watchlistOption;
}
};
/**
* Set
*
* with the full suite of options.
*
* @param {string|number|Morebits.date|Date} [watchlistExpiry=infinity] -
*
* can be relative (2 weeks) or other similarly date-like (i.e. NOT "potato"):
* ISO 8601: 2038-01-09T03:14:07Z
* MediaWiki: 20380109031407
Line 2,878 ⟶ 3,177:
*/
this.setWatchlistExpiry = function(watchlistExpiry) {
if (typeof watchlistExpiry === 'undefined') {
watchlistExpiry = 'infinity';
} else if (watchlistExpiry instanceof Morebits.date || watchlistExpiry instanceof Date) {
watchlistExpiry = watchlistExpiry.toISOString();
}
ctx.watchlistExpiry = watchlistExpiry;
};
Line 2,934 ⟶ 3,238:
* 1. If there are no revisions among the first 50 that are
* non-redirects, or if there are less 50 revisions and all are
* redirects, the original creation is
* 2. Revisions that the user is not privileged to access
* (revdeled/suppressed) will be treated as non-redirects.
Line 2,990 ⟶ 3,294:
this.suppressProtectWarning = function() {
ctx.suppressProtectWarning = true;
};
// Delete-related setter
/** @param {boolean} flag */
this.setDeleteTalkPage = function (flag) {
ctx.deleteTalkPage = !!flag;
};
// Undelete-related setter
/** @param {boolean} flag */
this.setUndeleteTalkPage = function (flag) {
ctx.undeleteTalkPage = !!flag;
};
Line 2,997 ⟶ 3,313:
};
/** @
this.getCurrentID = function() {
return ctx.revertCurID;
};
/** @
this.getRevisionUser = function() {
return ctx.revertUser;
};
/** @
this.getLastEditTime = function() {
return ctx.lastEditTime;
Line 3,024 ⟶ 3,340:
* detected upon calling `save()`.
*
* @param {
*/
this.setCallbackParameters = function(callbackParameters) {
Line 3,031 ⟶ 3,347:
/**
* @
*/
this.getCallbackParameters = function() {
Line 3,045 ⟶ 3,361:
/**
* @
*/
this.getStatusElement = function() {
Line 3,061 ⟶ 3,377:
/**
* @
*/
this.exists = function() {
Line 3,068 ⟶ 3,384:
/**
* @
* exist.
*/
Line 3,076 ⟶ 3,392:
/**
* @
* include (but may not be limited to): `wikitext`, `javascript`,
* `css`, `json`, `Scribunto`, `sanitized-css`, `MassMessageListContent`.
Line 3,086 ⟶ 3,402:
/**
* @
* unless it's being watched temporarily, in which case returns the
* expiry string.
Line 3,095 ⟶ 3,411:
/**
* @
*/
this.getLoadTime = function() {
Line 3,102 ⟶ 3,418:
/**
* @
*/
this.getCreator = function() {
Line 3,109 ⟶ 3,425:
/**
* @
*/
this.getCreationTimestamp = function() {
Line 3,115 ⟶ 3,431:
};
/** @
this.canEdit = function() {
return !!ctx.testActions && ctx.testActions.
};
Line 3,129 ⟶ 3,445:
* @param {Function} onSuccess - Callback function to be called when
* the username and timestamp are found within the callback.
* @param {Function} [onFailure] - Callback function to be called when
* the lookup fails
*/
this.lookupCreation = function(onSuccess, onFailure) {
ctx.onLookupCreationSuccess = onSuccess;
ctx.onLookupCreationFailure = onFailure || emptyFunction;
if (!onSuccess) {
ctx.statusElement.error('Internal error: no onSuccess callback provided to lookupCreation()!');
ctx.onLookupCreationFailure(this);
return;
}
action: 'query',
prop: 'revisions',
Line 3,158 ⟶ 3,478:
if (ctx.followRedirect) {
query.redirects = '';
}
ctx.lookupCreationApi = new Morebits.wiki.api(msg('getting-creator', 'Retrieving page creation information'), query, fnLookupCreationSuccess, ctx.statusElement, ctx.onLookupCreationFailure);
ctx.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
Line 3,209 ⟶ 3,529:
fnProcessMove.call(this, this);
} else {
ctx.moveApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
ctx.moveApi.setParent(this);
ctx.moveApi.post();
Line 3,233 ⟶ 3,553:
// If a link is present, don't need to check if it's patrolled
if ($('.patrollink').length) {
ctx.rcid = mw.util.getParamValue('rcid', patrolhref);
fnProcessPatrol(this, this);
} else {
action: 'query',
prop: 'info',
Line 3,250 ⟶ 3,570:
};
ctx.patrolApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), patrolQuery, fnProcessPatrol);
ctx.patrolApi.setParent(this);
ctx.patrolApi.post();
Line 3,275 ⟶ 3,595:
this.triage = function() {
// Fall back to patrol if not a valid triage namespace
if (!mw.config.get('pageTriageNamespaces').
this.patrol();
} else {
Line 3,287 ⟶ 3,607:
fnProcessTriageList(this, this);
} else {
ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList);
ctx.triageApi.setParent(this);
ctx.triageApi.post();
Line 3,314 ⟶ 3,634:
fnProcessDelete.call(this, this);
} else {
ctx.deleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure);
ctx.deleteApi.setParent(this);
ctx.deleteApi.post();
Line 3,339 ⟶ 3,659:
fnProcessUndelete.call(this, this);
} else {
ctx.undeleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure);
ctx.undeleteApi.setParent(this);
ctx.undeleteApi.post();
Line 3,370 ⟶ 3,690:
// (absolute, not differential), we always need to request
// protection levels from the server
ctx.protectApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure);
ctx.protectApi.setParent(this);
ctx.protectApi.post();
Line 3,405 ⟶ 3,725:
fnProcessStabilize.call(this, this);
} else {
ctx.stabilizeApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure);
ctx.stabilizeApi.setParent(this);
ctx.stabilizeApi.post();
Line 3,429 ⟶ 3,749:
* @param {string} [action=edit] - The action being undertaken, e.g.
* "edit" or "delete". In practice, only "edit" or "notedit" matters.
* @
*/
var fnCanUseMwUserToken = function(action = 'edit') {
// If a watchlist expiry is set, we must always load the page
// to avoid overwriting indefinite protection. Of course, not
// needed if setting indefinite watching!
if (ctx.watchlistExpiry && !Morebits.string.isInfinity(ctx.watchlistExpiry)) {
return false;
}
Line 3,459 ⟶ 3,778:
// wgRestrictionEdit is null on non-existent pages,
// so this neatly handles nonexistent pages
if (!editRestriction || editRestriction.
return false;
}
Line 3,481 ⟶ 3,800:
* @param {string} action - The action being undertaken, e.g. "edit" or
* "delete".
* @
*/
var fnNeedTokenInfoQuery = function(action) {
action: 'query',
meta: 'tokens',
Line 3,510 ⟶ 3,829:
// callback from loadApi.post()
var fnLoadSuccess = function() {
if (!fnCheckPageName(response, ctx.onLoadFailure)) {
Line 3,516 ⟶ 3,835:
}
let rev;
ctx.pageExists = !page.missing;
if (ctx.pageExists) {
Line 3,524 ⟶ 3,844:
ctx.pageID = page.pageid;
} else {
ctx.pageText = '';
ctx.pageID = 0; // nonexistent in response, matches wgArticleId
}
ctx.csrfToken = response.tokens.csrftoken;
if (!ctx.csrfToken) {
ctx.statusElement.error(msg('token-fetch-fail', 'Failed to retrieve edit token.'));
ctx.onLoadFailure(this);
return;
Line 3,546 ⟶ 3,866:
// Includes cascading protection
if (Morebits.userIsSysop) {
if (editProt) {
ctx.fullyProtected = editProt.expiry;
Line 3,558 ⟶ 3,876:
ctx.revertCurID = page.lastrevid;
ctx.testActions = []; // was null
Object.keys(testactions).forEach(
if (testactions[action]) {
ctx.testActions.push(action);
Line 3,575 ⟶ 3,893:
ctx.revertUser = rev && rev.user;
if (!ctx.revertUser) {
if (rev && rev.userhidden) {
ctx.revertUser = '<username hidden>';
} else {
Line 3,590 ⟶ 3,908:
// alert("Generate edit conflict now"); // for testing edit conflict recovery logic
ctx.onLoadSuccess(this);
};
Line 3,599 ⟶ 3,917:
}
if (page) {
// check for invalid titles
if (page.invalid) {
ctx.statusElement.error(msg('invalid-title', ctx.pageName, 'The page title is invalid: ' + ctx.pageName));
onFailure(this);
return false; // abort
Line 3,609 ⟶ 3,927:
// retrieve actual title of the page after normalization and redirects
if (response.redirects) {
// check for cross-namespace redirect:
if (origNs !== newNs && !ctx.followCrossNsRedirect) {
ctx.statusElement.error(msg('cross-redirect-abort', ctx.pageName, resolvedName, ctx.pageName + ' is a cross-namespace redirect to ' + resolvedName + ', aborted'));
onFailure(this);
return false;
Line 3,622 ⟶ 3,940:
// only notify user for redirects, not normalization
new Morebits.status('Note', msg('redirected', ctx.pageName, resolvedName, 'Redirected from ' + ctx.pageName + ' to ' + resolvedName));
}
Line 3,629 ⟶ 3,947:
} else {
// could be a circular redirect or other problem
ctx.statusElement.error(msg('redirect-resolution-fail', ctx.pageName, 'Could not resolve redirects for: ' + ctx.pageName));
onFailure(this);
Line 3,637 ⟶ 3,955:
}
return true; // all OK
};
/**
* Determine whether we should provide a watchlist expiry. Will not
* do so if the page is currently permanently watched, or the current
* expiry is *after* the new, provided expiry. Only handles strings
* recognized by {@link Morebits.date} or relative timeframes with
* unit it can process. Relies on the fact that fnCanUseMwUserToken
* requires page loading if a watchlistexpiry is provided, so we are
* ensured of knowing the watch status by the use of this.
*
* @return {boolean}
*/
var fnApplyWatchlistExpiry = function() {
if (ctx.watchlistExpiry) {
if (!ctx.watched || Morebits.string.isInfinity(ctx.watchlistExpiry)) {
return true;
} else if (typeof ctx.watched === 'string') {
let newExpiry;
// Attempt to determine if the new expiry is a
// relative (e.g. `1 month`) or absolute datetime
const rel = ctx.watchlistExpiry.split(' ');
try {
newExpiry = new Morebits.date().add(rel[0], rel[1]);
} catch (e) {
newExpiry = new Morebits.date(ctx.watchlistExpiry);
}
// If the date is valid, only use it if it extends the current expiry
if (newExpiry.isValid()) {
if (newExpiry.isAfter(new Morebits.date(ctx.watched))) {
return true;
}
} else {
// If it's still not valid, hope it's a valid MW expiry format that
// Morebits.date doesn't recognize, so just default to using it.
// This will also include minor typos.
return true;
}
}
}
return false;
};
// callback from saveApi.post()
var fnSaveSuccess = function() {
ctx.editMode = 'all';
// see if the API thinks we were successful
Line 3,649 ⟶ 4,009:
// real success
// default on success action - display link for edited page
link.setAttribute('href', mw.util.getUrl(ctx.pageName));
link.appendChild(document.createTextNode(ctx.pageName));
ctx.statusElement.info(['completed (', link, ')']);
if (ctx.onSaveSuccess) {
ctx.onSaveSuccess(this);
}
return;
Line 3,664 ⟶ 4,024:
ctx.statusElement.error('Could not save the page because the wiki server wanted you to fill out a CAPTCHA.');
} else {
ctx.statusElement.error(msg('api-error-unknown', 'Unknown error received from API while saving page'));
}
Line 3,675 ⟶ 4,035:
// callback from saveApi.post()
var fnSaveError = function() {
// check for edit conflict
Line 3,681 ⟶ 4,041:
// edit conflicts can occur when the page needs to be purged from the server cache
action: 'purge',
titles: ctx.pageName
};
--Morebits.wiki.numberOfActionsLeft;
ctx.statusElement.info(msg('editconflict-retrying', 'Edit conflict detected, reapplying edit'));
if (fnCanUseMwUserToken('edit')) {
ctx.saveApi.post(); // necessarily append, prepend, or newSection, so this should work as desired
Line 3,695 ⟶ 4,055:
ctx.loadApi.post(); // reload the page and reapply the edit
}
}), ctx.statusElement);
purgeApi.post();
Line 3,702 ⟶ 4,062:
// the error might be transient, so try again
ctx.statusElement.info(msg('save-failed-retrying', 2, 'Save failed, retrying in 2 seconds ...'));
--Morebits.wiki.numberOfActionsLeft;
// wait for sometime for client to regain
sleep(2000).then(
ctx.saveApi.post(); // give it another go!
});
Line 3,712 ⟶ 4,072:
// hard error, give up
} else {
const response = ctx.saveApi.getResponse();
const errorData = response.error || // bc error format
response.errors[0].data; // html/wikitext/plaintext error format
switch (errorCode) {
Line 3,721 ⟶ 4,084:
case 'abusefilter-disallowed':
ctx.statusElement.error('The edit was disallowed by the edit filter: "' +
break;
case 'abusefilter-warning':
ctx.statusElement.error([ 'A warning was returned by the edit filter: "',
// We should provide the user with a way to automatically retry the action if they so choose -
// I can't see how to do this without creating a UI dependency on Morebits.wiki.page though -- TTO
Line 3,732 ⟶ 4,095:
case 'spamblacklist':
// If multiple items are blacklisted, we only return the first
var spam =
ctx.statusElement.error('Could not save the page because the URL ' + spam + ' is on the spam blacklist');
break;
Line 3,740 ⟶ 4,103:
}
ctx.editMode = 'all';
if (ctx.onSaveFailure) {
ctx.onSaveFailure(this);
}
}
};
const isTextRedirect = function(text) {
if (!text) { // no text - content empty or inaccessible (revdelled or suppressed)
return false;
}
return Morebits.l10n.redirectTagAliases.some((tag) => new RegExp('^\\s*' + tag + '\\W', 'i').test(text));
};
var fnLookupCreationSuccess = function() {
if (!fnCheckPageName(response, ctx.onLookupCreationFailure)) {
return; // abort
}
if (!rev) {
ctx.statusElement.error('Could not find any revisions of ' + ctx.pageName);
ctx.onLookupCreationFailure(this);
return;
}
if (!ctx.lookupNonRedirectCreator || !
ctx.creator = rev.user;
if (!ctx.creator) {
ctx.statusElement.error('Could not find name of page creator');
ctx.onLookupCreationFailure(this);
return;
}
Line 3,770 ⟶ 4,142:
if (!ctx.timestamp) {
ctx.statusElement.error('Could not find timestamp of page creation');
ctx.onLookupCreationFailure(this);
return;
}
ctx.statusElement.info('retrieved page creation information');
ctx.onLookupCreationSuccess(this);
Line 3,778 ⟶ 4,153:
ctx.lookupCreationApi.query.titles = ctx.pageName; // update pageName if redirect resolution took place in earlier query
ctx.lookupCreationApi = new Morebits.wiki.api('Retrieving page creation information', ctx.lookupCreationApi.query, fnLookupNonRedirectCreator, ctx.statusElement, ctx.onLookupCreationFailure);
ctx.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
Line 3,786 ⟶ 4,161:
var fnLookupNonRedirectCreator = function() {
for (
if (!isTextRedirect(revs[i].content)) {
ctx.creator = revs[i].user;
ctx.timestamp = revs[i].timestamp;
Line 3,803 ⟶ 4,179:
if (!ctx.creator) {
ctx.statusElement.error('Could not find name of page creator');
ctx.onLookupCreationFailure(this);
return;
}
Line 3,809 ⟶ 4,186:
if (!ctx.timestamp) {
ctx.statusElement.error('Could not find timestamp of page creation');
ctx.onLookupCreationFailure(this);
return;
}
ctx.statusElement.info('retrieved page creation information');
ctx.onLookupCreationSuccess(this);
Line 3,822 ⟶ 4,201:
* @param {string} action - The action being checked.
* @param {string} onFailure - Failure callback.
* @
*/
var fnPreflightChecks = function(action, onFailure) {
Line 3,847 ⟶ 4,226:
* @param {string} onFailure - Failure callback.
* @param {string} response - The response document from the API call.
* @
*/
// No undelete as an existing page could have deleted revisions
if (actionMissing || protectMissing || saltMissing) {
Line 3,865 ⟶ 4,244:
// Delete, undelete, move
// extract protection info
if (action === 'undelete') {
editprot = response.pages[0].protection.filter(
} else if (action === 'delete' || action === 'move') {
editprot = response.pages[0].protection.filter(
}
if (editprot && !ctx.suppressProtectWarning &&
Line 3,893 ⟶ 4,268:
var fnProcessMove = function() {
if (fnCanUseMwUserToken('move')) {
Line 3,899 ⟶ 4,274:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('move', ctx.onMoveFailure, response)) {
Line 3,906 ⟶ 4,281:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'move',
from: pageTitle,
Line 3,924 ⟶ 4,299:
}
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 3,937 ⟶ 4,312:
}
ctx.moveProcessApi = new Morebits.wiki.api(msg('moving-page', 'moving page...'), query, ctx.onMoveSuccess, ctx.statusElement, ctx.onMoveFailure);
ctx.moveProcessApi.setParent(this);
ctx.moveProcessApi.post();
Line 3,943 ⟶ 4,318:
var fnProcessPatrol = function() {
action: 'patrol',
format: 'json'
Line 3,953 ⟶ 4,328:
query.token = mw.user.tokens.get('patrolToken');
} else {
// Don't patrol if not unpatrolled
Line 3,960 ⟶ 4,335:
}
if (!lastrevid) {
return;
Line 3,966 ⟶ 4,341:
query.revid = lastrevid;
if (!token) {
return;
Line 3,976 ⟶ 4,351:
}
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat);
Line 3,988 ⟶ 4,363:
ctx.csrfToken = mw.user.tokens.get('csrfToken');
} else {
ctx.pageID = response.pages[0].pageid;
Line 4,001 ⟶ 4,376:
}
action: 'pagetriagelist',
page_id: ctx.pageID,
Line 4,014 ⟶ 4,389:
// callback from triageProcessListApi.post()
var fnProcessTriage = function() {
// Exit if not in the queue
if (!responseList || responseList.result !== 'success') {
return;
}
// Do nothing if page already triaged/patrolled
if (!page || !parseInt(page.patrol_status, 10)) {
action: 'pagetriageaction',
pageid: ctx.pageID,
Line 4,032 ⟶ 4,407:
format: 'json'
};
ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, null, triageStat);
ctx.triageProcessApi.setParent(this);
Line 4,040 ⟶ 4,415:
var fnProcessDelete = function() {
if (fnCanUseMwUserToken('delete')) {
Line 4,046 ⟶ 4,421:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) {
Line 4,053 ⟶ 4,428:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'delete',
title: pageTitle,
Line 4,068 ⟶ 4,443:
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
if (ctx.deleteTalkPage) {
query.deletetalk = 'true';
}
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 4,082 ⟶ 4,460:
var fnProcessDeleteError = function() {
// check for "Database query error"
if (errorCode === 'internal_api_error_DBQueryError' && ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
--Morebits.wiki.numberOfActionsLeft;
ctx.deleteProcessApi.post(); // give it another go!
Line 4,093 ⟶ 4,471:
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi);
}
// hard error, give up
Line 4,099 ⟶ 4,477:
ctx.statusElement.error('Failed to delete the page: ' + ctx.deleteProcessApi.getErrorText());
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi);
}
}
Line 4,105 ⟶ 4,483:
var fnProcessUndelete = function() {
if (fnCanUseMwUserToken('undelete')) {
Line 4,111 ⟶ 4,489:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) {
Line 4,118 ⟶ 4,496:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'undelete',
title: pageTitle,
Line 4,133 ⟶ 4,511:
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
if (ctx.undeleteTalkPage) {
query.undeletetalk = 'true';
}
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 4,147 ⟶ 4,528:
var fnProcessUndeleteError = function() {
// check for "Database query error"
Line 4,153 ⟶ 4,534:
if (ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
--Morebits.wiki.numberOfActionsLeft;
ctx.undeleteProcessApi.post(); // give it another go!
} else {
ctx.statusElement.error('Repeated database query error, please try again');
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi);
}
}
Line 4,164 ⟶ 4,545:
ctx.statusElement.error('Cannot undelete the page, either because there are no revisions to undelete or because it has already been undeleted');
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi);
}
// hard error, give up
Line 4,170 ⟶ 4,551:
ctx.statusElement.error('Failed to undelete the page: ' + ctx.undeleteProcessApi.getErrorText());
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi);
}
}
Line 4,176 ⟶ 4,557:
var fnProcessProtect = function() {
if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) {
Line 4,182 ⟶ 4,563:
}
ctx.watched = page.watchlistexpiry || page.watched;
// Fetch existing protection levels
prs.forEach(
// Filter out protection from cascading
if (pr.type === 'edit' && !pr.source) {
Line 4,200 ⟶ 4,581:
}
});
// Fall back to current levels if not explicitly set
Line 4,215 ⟶ 4,595:
// Default to pre-existing cascading protection if unchanged (similar to above)
if (ctx.protectCascade === null) {
ctx.protectCascade = !!prs.filter(
}
// Warn if cascading protection being applied with an invalid protection level,
Line 4,239 ⟶ 4,617:
// Build protection levels and expirys (expiries?) for query
if (ctx.protectEdit) {
protections.push('edit=' + ctx.protectEdit.level);
Line 4,255 ⟶ 4,633:
}
action: 'protect',
title: pageTitle,
Line 4,270 ⟶ 4,648:
}
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 4,283 ⟶ 4,661:
var fnProcessStabilize = function() {
if (fnCanUseMwUserToken('stabilize')) {
Line 4,289 ⟶ 4,667:
pageTitle = ctx.pageName;
} else {
// 'stabilize' as a verb not necessarily well understood
Line 4,297 ⟶ 4,675:
token = response.tokens.csrftoken;
pageTitle = page.title;
// Doesn't support watchlist expiry [[phab:T263336]]
Line 4,303 ⟶ 4,681:
}
action: 'stabilize',
title: pageTitle,
Line 4,316 ⟶ 4,694:
/* Doesn't support watchlist expiry [[phab:T263336]]
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 4,327 ⟶ 4,705:
var sleep = function(milliseconds) {
setTimeout(deferred.resolve, milliseconds);
return deferred;
Line 4,340 ⟶ 4,718:
* - Need to reset all parameters once done (e.g. edit summary, move destination, etc.)
*/
/* **************** Morebits.wiki.preview **************** */
Line 4,368 ⟶ 4,745:
* @param {string} [pageTitle] - Optional parameter for the page this should be rendered as being on, if omitted it is taken as the current page.
* @param {string} [sectionTitle] - If provided, render the text as a new section using this as the title.
* @return {jQuery.promise}
*/
this.beginRender = function(wikitext, pageTitle, sectionTitle) {
$(previewbox).show();
previewbox.appendChild(statusspan);
Morebits.status.init(statusspan);
action: 'parse',
prop: ['text', 'modules'],
pst:
preview: true,
text: wikitext,
title: pageTitle || mw.config.get('wgPageName'),
disablelimitreport: true,
disableeditsection: true,
format: 'json'
};
Line 4,389 ⟶ 4,769:
query.sectiontitle = sectionTitle;
}
return renderApi.post();
};
var fnRenderSuccess = function(apiobj) {
const html = response.parse.text;
if (!html) {
apiobj.statelem.error('failed to retrieve preview, or template was blanked');
Line 4,400 ⟶ 4,781:
}
previewbox.innerHTML = html;
mw.loader.load(response.parse.modulestyles);
mw.loader.load(response.parse.modules);
// this makes links open in new tab
$(previewbox).find('a').attr('target', '_blank');
};
Line 4,408 ⟶ 4,793:
};
};
/* **************** Morebits.wikitext **************** */
Line 4,426 ⟶ 4,810:
* @param {string} text - Wikitext containing a template.
* @param {number} [start=0] - Index noting where in the text the template begins.
* @
*/
Morebits.wikitext.parseTemplate = function(text, start) {
start = start || 0;
name: '',
parameters: {}
};
/**
Line 4,451 ⟶ 4,835:
// Nothing found yet, this must be the template name
if (count === -1) {
result.name = current.
++count;
} else {
Line 4,463 ⟶ 4,847:
} else {
// No equals, so it must be unnamed; no trim since whitespace allowed
if (param) {
result.parameters[++unnamed] = param;
Line 4,472 ⟶ 4,856:
}
for (
if (test3 === '{{{' || (test3 === '}}}' && level[level.length - 1] === 3)) {
current += test3;
Line 4,484 ⟶ 4,868:
continue;
}
// Entering a template (or link)
if (test2 === '{{' || test2 === '[[') {
Line 4,546 ⟶ 4,930:
*
* @param {string} link_target
* @
*/
removeLink: function(link_target) {
const mwTitle = mw.Title.newFromText(link_target);
const namespaceID = mwTitle.getNamespaceId();
let link_regex_string = '';
if (namespaceID !== 0) {
link_regex_string = Morebits.namespaceRegex(namespaceID) + ':';
}
//
//
const isFileOrCategory = [6, 14].includes(namespaceID);
const colon = isFileOrCategory ? ':' : ':?';
this.text = this.text.replace(
return this;
},
Line 4,580 ⟶ 4,960:
* @param {string} image - Image name without `File:` prefix.
* @param {string} [reason] - Reason to be included in comment, alongside the commented-out image.
* @
*/
commentOutImage: function(image, reason) {
unbinder.unbind('<!--', '-->');
reason = reason ? reason + ': ' : '';
// Check for normal image links, i.e. [[File:Foobar.png|...]]
// Will eat the whole link
for (
if (links_re.test(allLinks[i])) {
unbinder.content = unbinder.content.replace(allLinks[i], replacement);
// unbind the newly created comments
unbinder.unbind('<!--', '-->');
}
}
// Check for gallery images, i.e. instances that must start on a new line,
// eventually preceded with some space, and must include File: prefix
// Will eat the whole line.
unbinder.content = unbinder.content.replace(gallery_image_re, '<!-- ' + reason + '$1 -->');
Line 4,611 ⟶ 4,991:
unbinder.unbind('<!--', '-->');
// Check free image usages, for example as template arguments, might have the File: prefix excluded, but must be
// Will only eat the image name and the
unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->');
// Rebind the content now, we are done!
Line 4,625 ⟶ 5,005:
* @param {string} image - Image name without File: prefix.
* @param {string} data - The display options.
* @
*/
addToImageComment: function(image, data) {
for (
if (links_re.test(allLinks[i])) {
// just put it at the end?
replacement = replacement.replace(/\]\]$/, '|' + data + ']]');
Line 4,639 ⟶ 5,019:
}
}
this.text = this.text.replace(gallery_re, newtext);
return this;
Line 4,650 ⟶ 5,030:
* @param {string} template - Page name whose transclusions are to be removed,
* include namespace prefix only if not in template namespace.
* @
*/
removeTemplate: function(template) {
for (
if (links_re.test(allTemplates[i])) {
this.text = this.text.replace(allTemplates[i], '');
Line 4,676 ⟶ 5,056:
* @param {string|string[]} [preRegex] - Optional regex string or array to match
* before any template matches (i.e. before `{{`), such as html comments.
* @
*/
insertAfterTemplates: function(tag, regex, flags, preRegex) {
Line 4,700 ⟶ 5,080:
preRegex = preRegex.join('|');
}
// Regex is extra complicated to allow for templates with
Line 4,735 ⟶ 5,114:
* Get the manipulated wikitext.
*
* @
*/
getText: function() {
Line 4,741 ⟶ 5,120:
}
};
/* *********** Morebits.userspaceLogger ************ */
Line 4,775 ⟶ 5,153:
* @param {string} logText - Doesn't include leading `#` or `*`.
* @param {string} summaryText - Edit summary.
* @
*/
this.log = function(logText, summaryText) {
if (!logText) {
return def.reject();
}
'Adding entry to userspace log'); // make this '... to ' + logPageName ?
page.load(
// add blurb if log page doesn't exist or is blank
// create monthly header if it doesn't exist already
if (!date.monthHeaderRegex().exec(text)) {
text += '\n\n' + date.monthHeader(this.headerLevel);
Line 4,799 ⟶ 5,177:
pageobj.setCreateOption('recreate');
pageobj.save(def.resolve, def.reject);
}
return def;
};
};
/* **************** Morebits.status **************** */
Line 4,822 ⟶ 5,199:
Morebits.status = function Status(text, stat, type) {
this.textRaw = text;
this.text =
this.type = type || 'status';
this.generate();
Line 4,859 ⟶ 5,236:
Morebits.status.errorEvent = handler;
} else {
throw new Error('Morebits.status.onError: handler is not a function');
}
};
Line 4,887 ⟶ 5,264:
this.linked = false;
}
},
Line 4,925 ⟶ 5,275:
update: function(status, type) {
this.statRaw = status;
this.stat =
if (type) {
this.type = type;
Line 4,979 ⟶ 5,329:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.status = function(text, status) {
Line 4,988 ⟶ 5,338:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.info = function(text, status) {
Line 4,997 ⟶ 5,347:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.warn = function(text, status) {
Line 5,006 ⟶ 5,356:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.error = function(text, status) {
Line 5,020 ⟶ 5,370:
*/
Morebits.status.actionCompleted = function(text) {
node.appendChild(document.createElement('b')).appendChild(document.createTextNode(text));
node.className = 'morebits_status_info morebits_action_complete';
if (Morebits.status.root) {
Morebits.status.root.appendChild(node);
Line 5,037 ⟶ 5,387:
*/
Morebits.status.printUserText = function(comments, message) {
p.innerHTML = message;
div.className = '
div.style.marginTop = '0';
div.style.whiteSpace = 'pre-wrap';
Line 5,047 ⟶ 5,397:
Morebits.status.root.appendChild(p);
};
/**
Line 5,056 ⟶ 5,404:
* @param {string} content - Text content.
* @param {string} [color] - Font color.
* @
*/
Morebits.htmlNode = function (type, content, color) {
if (color) {
node.style.color = color;
Line 5,066 ⟶ 5,414:
return node;
};
/**
Line 5,078 ⟶ 5,424:
*/
Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) {
function clickHandler(event) {
if (event.shiftKey && lastCheckbox !== null) {
for (i = 0; i < $cbs.length; i++) {
if ($cbs[i] === thisCb) {
index = i;
if (lastIndex > -1) {
Line 5,092 ⟶ 5,438:
}
}
if ($cbs[i] === lastCheckbox) {
lastIndex = i;
if (index > -1) {
Line 5,102 ⟶ 5,448:
if (index > -1 && lastIndex > -1) {
// inspired by wikibits
if (index < lastIndex) {
start = index + 1;
Line 5,113 ⟶ 5,459:
for (i = start; i <= finish; i++) {
if ($cbs[i].checked !== endState) {
$cbs[i].click();
}
}
Line 5,123 ⟶ 5,469:
}
$(jQuerySelector, jQueryContext).
};
/* **************** Morebits.batchOperation **************** */
Line 5,167 ⟶ 5,511:
*/
Morebits.batchOperation = function(currentAction) {
// backing fields for public properties
pageList: null,
Line 5,176 ⟶ 5,520:
// internal counters, etc.
statusElement: new Morebits.status(currentAction || msg('batch-starting', 'Performing batch operation')),
worker: null, // function that executes for each item in pageList
postFinish: null, // function that executes when the whole batch has been processed
Line 5,241 ⟶ 5,585:
ctx.pageChunks = [];
if (!total) {
ctx.statusElement.info(msg('batch-no-pages', 'no pages specified'));
ctx.running = false;
if (ctx.postFinish) {
Line 5,261 ⟶ 5,605:
/**
* To be called by worker before it terminates
*
* @param {(Morebits.wiki.page|Morebits.wiki.api|string)} arg -
Line 5,270 ⟶ 5,614:
*/
this.workerSuccess = function(arg) {
if (arg instanceof Morebits.wiki.api || arg instanceof Morebits.wiki.page) {
// update or remove status line
if (ctx.options.preserveIndividualStatusLines) {
if (arg.getPageName || arg.pageName || (arg.query && arg.query.title)) {
// we know the page title - display a relevant message
statelem.info(
} else {
// we don't know the page title - just display a generic message
statelem.info(msg('done', 'done'));
}
} else {
Line 5,296 ⟶ 5,633:
} else if (typeof arg === 'string' && ctx.options.preserveIndividualStatusLines) {
new Morebits.status(arg,
}
Line 5,309 ⟶ 5,646:
// private functions
var fnStartNewChunk = function() {
if (!chunk) {
return;
}
// start workers for the current chunk
ctx.countStarted += chunk.length;
chunk.forEach(
ctx.worker(page, thisProxy);
});
Line 5,328 ⟶ 5,665:
// update overall status line
if (ctx.countFinished < total) {
ctx.statusElement.status(msg('percent', progress, progress + '%'));
// start a new chunk if we're close enough to the end of the previous chunk, and
Line 5,339 ⟶ 5,677:
}
} else if (ctx.countFinished === total) {
'/' + ctx.countFinished + ' actions completed successfully)');
if (ctx.countFinishedSuccess < ctx.countFinished) {
ctx.statusElement.warn(statusString);
Line 5,363 ⟶ 5,701:
/**
* Given a set of asynchronous functions to run along with their dependencies,
*
* that don't depend on each other are triggered simultaneously. Where
* dependencies exist, it ensures that the dependency functions finish running
Line 5,372 ⟶ 5,710:
* @class
*/
Morebits.taskManager = function(context) {
this.taskDependencyMap = new Map();
this.failureCallbackMap = new Map();
this.deferreds = new Map();
this.context = context || window;
/**
Line 5,385 ⟶ 5,724:
* @param {Function} func - A task.
* @param {Function[]} deps - Its dependencies.
* @param {Function} [onFailure] - a failure callback that's run if the task or any one
* of its dependencies fail.
*/
this.add = function(func, deps, onFailure) {
this.taskDependencyMap.set(func, deps);
this.failureCallbackMap.set(func, onFailure || (() => {}));
const deferred = $.Deferred();
this.deferreds.set(func, deferred);
};
Line 5,396 ⟶ 5,737:
* Run all the tasks. Multiple tasks may be run at once.
*
* @
*/
this.execute = function() {
this.taskDependencyMap.forEach(
$.when.apply(self.context, dependencyPromisesArray).then(function() {
const result = task.apply(self.context, arguments);
if (result === undefined) { // maybe the function threw, or it didn't return anything
mw.log.error('Morebits.taskManager: task returned undefined');
self.deferreds.get(task).
self.failureCallbackMap.get(task).apply(self.context, []);
}
result.then(function() {
self.deferreds.get(task).resolve.apply(self.context, arguments);
}, function() { // task failed
self.deferreds.get(task).reject.apply(self.context, arguments);
self.failureCallbackMap.get(task).apply(self.context, arguments);
});
}, function() { // one or more of the dependencies failed
self.failureCallbackMap.get(task).apply(self.context, arguments);
});
});
return $.when.apply(null, [...this.
};
Line 5,420 ⟶ 5,770:
* @memberof Morebits
* @class
* @requires
* @param {number} width
* @param {number} height - The maximum allowable height for the content area.
*/
Morebits.simpleWindow = function SimpleWindow(width, height) {
this.content = content;
content.className = 'morebits-dialog-content';
Line 5,436 ⟶ 5,786:
buttons: { 'Placeholder button': function() {} },
dialogClass: 'morebits-dialog',
width: Math.min(parseInt(window.innerWidth, 10), parseInt(width
// give jQuery the given height value (which represents the anticipated height of the dialog) here, so
// it can position the dialog appropriately
Line 5,452 ⟶ 5,802:
}
},
this.scrollbox = null;
},
Line 5,463 ⟶ 5,813:
});
// delete the placeholder button (it's only there so the buttonpane gets created)
$widget.find('button').each(
value.parentNode.removeChild(value);
});
// add container for the buttons we add, and the footer links (if any)
buttonspan.className = 'morebits-dialog-buttons';
linksspan.className = 'morebits-dialog-footerlinks';
$widget.find('.ui-dialog-buttonpane').append(buttonspan, linksspan);
Line 5,479 ⟶ 5,829:
// resize the scrollbox with the dialog, if one is present
$widget.resizable('option', 'alsoResize', '#' + this.content.id + ' .morebits-scrollbox, #' + this.content.id);
// add skin-invert to "close" button
$('.morebits-dialog .ui-dialog-titlebar-close').addClass('skin-invert');
};
Line 5,490 ⟶ 5,843:
* Focuses the dialog. This might work, or on the contrary, it might not.
*
* @
*/
focus: function() {
Line 5,502 ⟶ 5,855:
*
* @param {event} [event]
* @
*/
close: function(event) {
Line 5,516 ⟶ 5,869:
* might work, but it is not guaranteed.
*
* @
*/
display: function() {
if (this.scriptName) {
$widget.find('.morebits-dialog-scriptname').remove();
scriptnamespan.className = 'morebits-dialog-scriptname';
scriptnamespan.textContent = this.scriptName + ' \u00B7 ';
$widget.find('.ui-dialog-title').prepend(scriptnamespan);
}
if (window.setupTooltips && window.pg && window.pg.re && window.pg.re.diff) {
dialog.parent()[0].ranSetupTooltipsAlready = false;
window.setupTooltips(dialog.parent()[0]);
}
this.setHeight(this.height);
return this;
},
Line 5,541 ⟶ 5,894:
*
* @param {string} title
* @
*/
setTitle: function(title) {
Line 5,553 ⟶ 5,906:
*
* @param {string} name
* @
*/
setScriptName: function(name) {
Line 5,564 ⟶ 5,917:
*
* @param {number} width
* @
*/
setWidth: function(width) {
Line 5,576 ⟶ 5,929:
*
* @param {number} height
* @
*/
setHeight: function(height) {
Line 5,602 ⟶ 5,955:
*
* @param {HTMLElement} content
* @
*/
setContent: function(content) {
Line 5,614 ⟶ 5,967:
*
* @param {HTMLElement} content
* @
*/
addContent: function(content) {
Line 5,620 ⟶ 5,973:
// look for submit buttons in the content, hide them, and add a proxy button to the button pane
$(this.content).find('input[type="submit"], button[type="submit"]').each(
value.style.display = 'none';
if (value.hasAttribute('value')) {
button.textContent = value.getAttribute('value');
} else if (value.textContent) {
button.textContent = value.textContent;
} else {
button.textContent = msg('submit', 'Submit');
}
button.className = value.className || 'submitButtonProxy';
// here is an instance of cheap coding, probably a memory-usage hit in using a closure here
button.addEventListener('click',
value.click();
}, false);
Line 5,636 ⟶ 5,997:
$(this.content).dialog('widget').find('.morebits-dialog-buttons').empty().append(this.buttons)[0].removeAttribute('data-empty');
} else {
$(this.content).dialog('widget').find('.morebits-dialog-buttons')[0].setAttribute('data-empty', 'data-empty');
}
return this;
Line 5,644 ⟶ 6,005:
* Removes all contents from the dialog, barring any footer links.
*
* @
*/
purgeContent: function() {
Line 5,666 ⟶ 6,027:
* @param {string} wikiPage - Link target.
* @param {boolean} [prep=false] - Set true to prepend rather than append.
* @
*/
addFooterLink: function(text, wikiPage, prep) {
if (this.hasFooterLinks) {
bullet.textContent = msg('bullet-separator', ' \u2022 ');
if (prep) {
$footerlinks.prepend(bullet);
Line 5,679 ⟶ 6,040:
}
}
link.setAttribute('href', mw.util.getUrl(wikiPage));
link.setAttribute('title', wikiPage);
Line 5,700 ⟶ 6,061:
* @param {boolean} [modal=false] - If set to true, other items on the
* page will be disabled, i.e., cannot be interacted with.
* @
*/
setModality: function(modal) {
Line 5,723 ⟶ 6,084:
};
// Create capital letter aliases for all Morebits @classes (functions that work with the `new` keyword), to follow the coding convention that classes should start with an uppercase letter. This will let us start fixing ESLint `new-cap` errors in other files.
Morebits.BatchOperation = Morebits.batchOperation;
Morebits.Date = Morebits.date;
Morebits.QuickForm = Morebits.quickForm;
Morebits.QuickForm.Element = Morebits.quickForm.element;
Morebits.SimpleWindow = Morebits.simpleWindow;
Morebits.Status = Morebits.status;
Morebits.TaskManager = Morebits.taskManager;
Morebits.Unbinder = Morebits.unbinder;
Morebits.UserspaceLogger = Morebits.userspaceLogger;
Morebits.wiki.Api = Morebits.wiki.api;
Morebits.wiki.Page = Morebits.wiki.page;
Morebits.wiki.Preview = Morebits.wiki.preview;
Morebits.wikitext.Page = Morebits.wikitext.page;
}());
/**
Line 5,736 ⟶ 6,110:
*/
if (typeof arguments === 'undefined') {
/* global Morebits */
window.SimpleWindow = Morebits.simpleWindow;
|