MediaWiki:Gadget-morebits.js: Difference between revisions

Content deleted Content added
Repo at b60c1b8: Convert Morebits.wiki.page methods to json, not xml; Require matching level markers; Add YYYYMMDDHHmmss to morebits.date constructor; Fixes for internal templates/parser functions; Consolidate largely duplicated code; Fixes for unnamed parameters
Repo at ac3c1e3: replace es-x/no-array-prototype-includes with unicorn/prefer-includes (#2125)
 
(32 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 28 ⟶ 29:
* This library is maintained by the maintainers of Twinkle.
* For queries, suggestions, help, etc., head to [Wikipedia talk:Twinkle on English Wikipedia](http://en.wikipedia.org/wiki/WT:TW).
* The latest development source is available at {@link https://github.com/azatothwikimedia-gadgets/twinkle/blob/master/morebits.js|GitHub}.
*
* @namespace Morebits
*/
 
(function() {
 
(function (window, document, $) { // Wrap entire file with anonymous function
 
/** @lends Morebits */
varconst Morebits = {};
window.Morebits = Morebits; // allow global access
 
/**
* 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.
* @returnsreturn {boolean}
*/
Morebits.userIsInGroup = function (group) {
return mw.config.get('wgUserGroups').indexOfincludes(group) !== -1;
};
/**
/** Hardcodes whether the user is a sysop, used a lot.
* Hardcodes whether the user is a sysop, used a lot.
*
* @constant
* @type {boolean}
*/
Line 58 ⟶ 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/libs/IPUtilscore/+/refs/heads8eb6ac3e84ea3312d391ca96c12c49e3ad0753bb/masterincludes/srcutils/IPUtilsIP.php#214131|`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.
* @returnsreturn {string}
*/
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
address = address.trim();
ifreturn Morebits.ip.sanitizeIPv6(address === '') {;
return null;
}
if (!mw.util.isIPv6Address(address)) {
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
var 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").
var CIDRStart = address.indexOf('/');
var addressEnd = CIDRStart > -1 ? CIDRStart - 1 : address.length - 1;
// If the '::' is at the beginning...
var 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 '::')
}
var replacement = repeat;
pad -= address.split(':').length - 1;
for (var 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');
};
 
Line 116 ⟶ 163:
* detect Module:RfD, with the same failure points.
*
* @returnsreturn {boolean}
*/
Morebits.isPageRedirect = function() {
Line 129 ⟶ 176:
*/
Morebits.pageNameNorm = mw.config.get('wgPageName').replace(/_/g, ' ');
 
 
/**
* Create a string for use in regex matching a page name,. regardless ofAccounts thefor
* leading character's capitalization., underscores as spaces, and special
* characters being escaped. See also {@link Morebits.namespaceRegex}.
*
* @param {string} pageName - Page name without namespace.
* @returnsreturn {string} - For a page name `Foo bar`, returns the string `[Ff]oo[_ ]bar`.
*/
Morebits.pageNameRegex = function(pageName) {
if (pageName === '') {
return '[' + pageName[0].toUpperCase() + pageName[0].toLowerCase() + ']' + pageName.slice(1);
return '';
}
const firstChar = pageName[0],
remainder = Morebits.string.escapeRegExp(pageName.slice(1));
if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) {
return '[' + mw.Title.phpCharToUpper(firstChar) + firstChar.toLowerCase() + ']' + remainder;
}
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, '&#34;') + '">' + text + '</a>';
});
return ub.rebind();
};
 
/**
* Create a string for use in regex matching all namespace aliases, regardless
* of the capitalization and underscores/spaces. Doesn't include the optional
* leading `:`, but if there's more than one item, wraps the list in a
* non-capturing group. This means you can do `Morebits.namespaceRegex([4]) +
* ':' + Morebits.pageNameRegex('Twinkle')` to match a full page. Uses
* {@link Morebits.pageNameRegex}.
*
* @param {number[]} namespaces - Array of namespace numbers. Unused/invalid
* namespace numbers are silently discarded.
* @example
* // returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])'
* Morebits.namespaceRegex([6])
* @return {string} - Regex-suitable string of all namespace aliases.
*/
Morebits.namespaceRegex = function(namespaces) {
if (!Array.isArray(namespaces)) {
namespaces = [namespaces];
}
const aliases = [];
let regex;
$.each(mw.config.get('wgNamespaceIds'), (name, number) => {
if (namespaces.includes(number)) {
// Namespaces are completely agnostic as to case,
// and a regex string is more useful/compatible than a RegExp object,
// so we accept any casing for any letter.
aliases.push(name.split('').map((char) => Morebits.pageNameRegex(char)).join(''));
}
});
switch (aliases.length) {
case 0:
regex = '';
break;
case 1:
regex = aliases[0];
break;
default:
regex = '(?:' + aliases.join('|') + ')';
break;
}
return regex;
};
 
/* **************** Morebits.quickForm **************** */
Line 161 ⟶ 309:
*
* @memberof Morebits.quickForm
* @returnsreturn {HTMLElement}
*/
Morebits.quickForm.prototype.render = function QuickFormRender() {
varconst ret = this.root.render();
ret.names = {};
return ret;
Line 175 ⟶ 323:
* @param {(object|Morebits.quickForm.element)} data - A quickform element, or the object with which
* a quickform element is constructed.
* @returnsreturn {Morebits.quickForm.element} - Same as what is passed to the function.
*/
Morebits.quickForm.prototype.append = function QuickFormAppend(data) {
Line 185 ⟶ 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 200 ⟶ 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, maxlength, event
* - `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 218 ⟶ 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 {objectObject} data - Object representing the quickform element. Should
* specify one of the available types from the index above, as well as any
* relevant and available attributes.
Line 235 ⟶ 389:
this.data = data;
this.childs = [];
this.id = Morebits.quickForm.element.id++;
};
 
Line 250 ⟶ 403:
* @param {Morebits.quickForm.element} data - A quickForm element or the object required to
* create the quickForm element.
* @returnsreturn {Morebits.quickForm.element} The same element passed in.
*/
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) {
varlet child;
if (data instanceof Morebits.quickForm.element) {
child = data;
Line 268 ⟶ 421:
*
* @memberof Morebits.quickForm.element
* @returnsreturn {HTMLElement}
*/
Morebits.quickForm.element.prototype.render = function QuickFormElementRender(internal_subgroup_id) {
varconst currentNode = this.compute(this.data, internal_subgroup_id);
 
for (varlet i = 0; i < this.childs.length; ++i) {
// do not pass internal_subgroup_id to recursive calls
currentNode[1].appendChild(this.childs[i].render());
Line 282 ⟶ 435:
/** @memberof Morebits.quickForm.element */
Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute(data, in_id) {
varlet node;
varlet childContainderchildContainer = null;
varlet label;
varconst id = (in_id ? in_id + '_' : '') + 'node_' + thisMorebits.quickForm.element.id++;
if (data.adminonly && !Morebits.userIsSysop) {
// hell hack alpha
Line 291 ⟶ 444:
}
 
varlet i, current, subnode;
switch (data.type) {
case 'form':
Line 305 ⟶ 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 312 ⟶ 466:
label = node.appendChild(document.createElement('label'));
label.setAttribute('for', id);
label.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
label.style.marginRight = '3px';
}
var select = node.appendChild(document.createElement('select'));
Line 344 ⟶ 499:
}
}
childContainderchildContainer = select;
break;
case 'option':
Line 377 ⟶ 532:
node = document.createElement('fieldset');
label = node.appendChild(document.createElement('legend'));
label.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
if (data.name) {
node.setAttribute('name', data.name);
Line 390 ⟶ 545:
if (data.list) {
for (i = 0; i < data.list.length; ++i) {
varconst cur_id = id + '_' + i;
current = data.list[i];
var cur_div;
Line 424 ⟶ 579:
}
label = cur_div.appendChild(document.createElement('label'));
 
label.appendChild(document.createTextNode(current.label));
label.appendChild(Morebits.createHtml(current.label));
label.setAttribute('for', cur_id);
if (current.tooltip) {
Line 436 ⟶ 592:
var event;
if (current.subgroup) {
varlet tmpgroup = current.subgroup;
 
if (!Array.isArray(tmpgroup)) {
Line 446 ⟶ 602:
id: id + '_' + i + '_subgroup'
});
$.each(tmpgroup, function(idx, el) => {
varconst newEl = $.extend({}, el);
if (!newEl.type) {
newEl.type = data.type;
Line 455 ⟶ 611:
});
 
varconst subgroup = subgroupRaw.render(cur_id);
subgroup.className = 'quickformSubgroup';
subnode.subgroup = subgroup;
Line 464 ⟶ 620:
e.target.parentNode.appendChild(e.target.subgroup);
if (e.target.type === 'radio') {
varconst name = e.target.name;
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 481 ⟶ 637:
event = function(e) {
if (e.target.checked) {
varconst name = e.target.name;
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 502 ⟶ 658:
}
break;
// input is actually a text-type, so number here inherits the same stuff
case 'number':
case 'input':
node = document.createElement('div');
Line 508 ⟶ 666:
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
label.setAttribute('for', data.id || id);
label.style.marginRight = '3px';
}
 
subnode = node.appendChild(document.createElement('input'));
if (data.value) {
subnode.setAttribute('value', data.value);
}
subnode.setAttribute('name', data.name);
 
subnode.setAttribute('type', 'text');
if (data.sizetype === 'input') {
subnode.setAttribute('sizetype', data.size'text');
} else {
subnode.setAttribute('type', 'number');
if (data.disabled) {
['min', 'max', 'step', 'list'].forEach((att) => {
subnode.setAttribute('disabled', 'disabled');
if (data[att]) {
}
subnode.setAttribute(att, data[att]);
if (data.required) {
}
subnode.setAttribute('required', 'required');
});
if (data.readonly) {
subnode.setAttribute('readonly', 'readonly');
}
if (data.maxlength) {
subnode.setAttribute('maxlength', data.maxlength);
}
 
['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);
}
 
childContainder = subnode;
childContainer = subnode;
break;
case 'dyninput':
Line 545 ⟶ 708:
 
label = node.appendChild(document.createElement('h5'));
label.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
 
var listNode = node.appendChild(document.createElement('div'));
 
Line 554 ⟶ 716:
disabled: min >= max,
event: function(e) {
varconst new_node = new Morebits.quickForm.element(e.target.sublist);
e.target.area.appendChild(new_node.render());
 
Line 568 ⟶ 730:
 
var sublist = {
type: '_dyninput_element_dyninput_row',
label: data.sublabel || data.label,
name: data.name,
value: data.value,
size: data.size,
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) {
varconst elem = new Morebits.quickForm.element(sublist);
listNode.appendChild(elem.render());
}
Line 591 ⟶ 756:
moreButton.counter = 0;
break;
case '_dyninput_element_dyninput_row': // Private, similar to normal input
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 606 ⟶ 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 611 ⟶ 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';
if (data.remove) {
var remove = this.compute({
type: 'button',
label: 'remove',
event: function(e) {
var list = e.target.listnode;
var node = e.target.inputnode;
var more = e.target.morebutton;
 
list.removeChild(node);
--more.counter;
more.removeAttribute('disabled');
e.stopPropagation();
}
});
node.appendChild(remove[0]);
var removeButton = remove[1];
removeButton.inputnode = node;
removeButton.listnode = data.listnode;
removeButton.morebutton = data.morebutton;
}
break;
case 'hidden':
Line 646 ⟶ 829:
case 'header':
node = document.createElement('h5');
node.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
break;
case 'div':
Line 654 ⟶ 837:
}
if (data.label) {
const result = document.createElement('span');
if (!Array.isArray(data.label)) {
data.label = [ data.label ];
}
var result = document.createElement('span');
result.className = 'quickformDescription';
for result.appendChild(Morebits.createHtml(i = 0; i < data.label.length; ++i) {);
if (typeof data.label[i] === 'string') {
result.appendChild(document.createTextNode(data.label[i]));
} else if (data.label[i] instanceof Element) {
result.appendChild(data.label[i]);
}
}
node.appendChild(result);
}
Line 671 ⟶ 845:
case 'submit':
node = document.createElement('span');
childContainderchildContainer = node.appendChild(document.createElement('input'));
childContainderchildContainer.setAttribute('type', 'submit');
if (data.label) {
childContainderchildContainer.setAttribute('value', data.label);
}
childContainderchildContainer.setAttribute('name', data.name || 'submit');
if (data.disabled) {
childContainderchildContainer.setAttribute('disabled', 'disabled');
}
break;
case 'button':
node = document.createElement('span');
childContainderchildContainer = node.appendChild(document.createElement('input'));
childContainderchildContainer.setAttribute('type', 'button');
if (data.label) {
childContainderchildContainer.setAttribute('value', data.label);
}
childContainderchildContainer.setAttribute('name', data.name);
if (data.disabled) {
childContainderchildContainer.setAttribute('disabled', 'disabled');
}
if (data.event) {
childContainderchildContainer.addEventListener('click', data.event, false);
}
break;
Line 701 ⟶ 875:
if (data.label) {
label = node.appendChild(document.createElement('h5'));
varconst labelElement = document.createElement('label');
labelElement.textContent = appendChild(Morebits.createHtml(data.label));
labelElement.setAttribute('for', data.id || id);
label.appendChild(labelElement);
Line 726 ⟶ 900:
subnode.value = data.value;
}
childContainderchildContainer = subnode;
break;
default:
Line 732 ⟶ 906:
}
 
if (!childContainderchildContainer) {
childContainderchildContainer = node;
}
if (data.tooltip) {
Line 740 ⟶ 914:
 
if (data.extra) {
childContainderchildContainer.extra = data.extra;
}
if (data.$data) {
$(childContainer).data(data.$data);
}
if (data.style) {
childContainderchildContainer.setAttribute('style', data.style);
}
if (data.className) {
childContainderchildContainer.className = childContainderchildContainer.className ?
childContainderchildContainer.className + ' ' + data.className :
data.className;
}
childContainderchildContainer.setAttribute('id', data.id || id);
 
return [ node, childContainderchildContainer ];
};
 
Line 759 ⟶ 936:
*
* @memberof Morebits.quickForm.element
* @requires jqueryjQuery.ui
* @param {HTMLElement} node - The HTML element beside which a tooltip is to be generated.
* @param {objectObject} data - Tooltip-related configuration data.
*/
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) {
varconst tooltipButton = node.appendChild(document.createElement('span'));
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 774 ⟶ 951:
});
};
 
 
// Some utility methods for manipulating quickForms after their creation:
Line 785 ⟶ 961:
* @memberof Morebits.quickForm
* @param {HTMLFormElement} form
* @returnsreturn {objectObject} With field names as keys, input data as values.
*/
Morebits.quickForm.getInputData = function(form) {
varconst result = {};
 
for (varlet i = 0; i < form.elements.length; i++) {
varconst field = form.elements[i];
if (field.disabled || !field.name || !field.type ||
field.type === 'submit' || field.type === 'button') {
Line 799 ⟶ 975:
// For elements in subgroups, quickform prepends element names with
// name of the parent group followed by a period, get rid of that.
varconst fieldNameNorm = field.name.slice(field.name.indexOf('.') + 1);
 
switch (field.type) {
Line 822 ⟶ 998:
case 'text': // falls through
case 'textarea':
result[fieldNameNorm] =if (field.valuedataset.trim(dyninput); {
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 833 ⟶ 1,014:
return result;
};
 
 
/**
Line 841 ⟶ 1,021:
* @param {HTMLFormElement} form
* @param {string} fieldName - The name or id of the fields.
* @returnsreturn {HTMLElement[]} - Array of matching form elements.
*/
Morebits.quickForm.getElements = function QuickFormGetElements(form, fieldName) {
varconst $form = $(form);
fieldName = $.escapeSelector(fieldName); // sanitize input
varlet $elements = $form.find('[name="' + fieldName + '"]');
if ($elements.length > 0) {
return $elements.toArray();
Line 861 ⟶ 1,041:
* @param {HTMLInputElement[]} elementArray - Array of checkbox or radio elements.
* @param {string} value - Value to search for.
* @returnsreturn {HTMLInputElement}
*/
Morebits.quickForm.getCheckboxOrRadio = function QuickFormGetCheckboxOrRadio(elementArray, value) {
varconst found = $.grep(elementArray, function(el) {=> el.value === value);
return el.value === value;
});
if (found.length > 0) {
return found[0];
Line 879 ⟶ 1,057:
* @memberof Morebits.quickForm
* @param {HTMLElement} element
* @returnsreturn {HTMLElement}
*/
Morebits.quickForm.getElementContainer = function QuickFormGetElementContainer(element) {
Line 898 ⟶ 1,076:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @returnsreturn {HTMLElement}
*/
Morebits.quickForm.getElementLabelObject = function QuickFormGetElementLabelObject(element) {
Line 921 ⟶ 1,099:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @returnsreturn {string}
*/
Morebits.quickForm.getElementLabel = function QuickFormGetElementLabel(element) {
varconst labelElement = Morebits.quickForm.getElementLabelObject(element);
 
if (!labelElement) {
Line 938 ⟶ 1,116:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} labelText
* @returnsreturn {boolean} True if succeeded, false if the label element is unavailable.
*/
Morebits.quickForm.setElementLabel = function QuickFormSetElementLabel(element, labelText) {
varconst labelElement = Morebits.quickForm.getElementLabelObject(element);
 
if (!labelElement) {
Line 956 ⟶ 1,134:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} temporaryLabelText
* @returnsreturn {boolean} `true` if succeeded, `false` if the label element is unavailable.
*/
Morebits.quickForm.overrideElementLabel = function QuickFormOverrideElementLabel(element, temporaryLabelText) {
Line 970 ⟶ 1,148:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @returnsreturn {boolean} True if succeeded, false if the label element is unavailable.
*/
Morebits.quickForm.resetElementLabel = function QuickFormResetElementLabel(element) {
Line 1,000 ⟶ 1,178:
$(Morebits.quickForm.getElementContainer(element)).find('.morebits-tooltipButton').toggle(visibility);
};
 
 
 
/**
Line 1,009 ⟶ 1,185:
* Get checked items in the form.
*
* @functionmethod external:HTMLFormElement.getChecked
* @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,015 ⟶ 1,191:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @returnsreturn {string[]} - Contains the values of elements with the given name
* checked property set to true.
*/
HTMLFormElement.prototype.getChecked = function(name, type) {
varconst elements = this.elements[name];
if (!elements) {
return [];
}
varconst return_array = [];
varlet i;
if (elements instanceof HTMLSelectElement) {
varconst options = elements.options;
for (i = 0; i < options.length; ++i) {
if (options[i].selected) {
Line 1,063 ⟶ 1,239:
* Does the same as {@link HTMLFormElement.getChecked|getChecked}, but with unchecked elements.
*
* @functionmethod external:HTMLFormElement.getUnchecked
* @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,069 ⟶ 1,245:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @returnsreturn {string[]} - Contains the values of elements with the given name
* checked property set to true.
*/
HTMLFormElement.prototype.getUnchecked = function(name, type) {
varconst elements = this.elements[name];
if (!elements) {
return [];
}
varconst return_array = [];
varlet i;
if (elements instanceof HTMLSelectElement) {
varconst options = elements.options;
for (i = 0; i < options.length; ++i) {
if (!options[i].selected) {
Line 1,113 ⟶ 1,289:
return return_array;
};
 
 
/**
* Utilities to help process IP addresses.
* @external RegExp
*/
/**
* Deprecated as of September 2020, use {@link Morebits.string.escapeRegExp}
* or `mw.util.escapeRegExp`.
*
* @namespace Morebits.ip
* @function external:RegExp.escape
* @memberof Morebits
* @deprecated Use {@link Morebits.string.escapeRegExp} or `mw.util.escapeRegExp`.
* @param {string} text - String to be escaped.
* @param {boolean} [space_fix=false] - Whether to replace spaces and
* underscores with `[ _]` as they are often equivalent.
* @returns {string} - The escaped text.
*/
Morebits.ip = {
RegExp.escape = function(text, space_fix) {
/**
if (space_fix) {
* Converts an IPv6 address to the canonical form stored and used by MediaWiki.
console.error('NOTE: RegExp.escape from Morebits was deprecated September 2020, please replace it with Morebits.string.escapeRegExp'); // eslint-disable-line no-console
* JavaScript translation of the {@link https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/core/+/8eb6ac3e84ea3312d391ca96c12c49e3ad0753bb/includes/utils/IP.php#131|`IP::sanitizeIP()`}
return Morebits.string.escapeRegExp(text);
* 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');
}
console.error('NOTE: RegExp.escape from Morebits was deprecated September 2020, please replace it with mw.util.escapeRegExp'); // eslint-disable-line no-console
return mw.util.escapeRegExp(text);
};
 
 
/**
Line 1,148 ⟶ 1,420:
/**
* @param {string} str
* @returnsreturn {string}
*/
toUpperCaseFirstChar: function(str) {
str = str.toString();
return str.substrslice(0, 1).toUpperCase() + str.substrslice(1);
},
/**
* @param {string} str
* @returnsreturn {string}
*/
toLowerCaseFirstChar: function(str) {
str = str.toString();
return str.substrslice(0, 1).toLowerCase() + str.substrslice(1);
},
 
Line 1,172 ⟶ 1,444:
* @param {string} end
* @param {(string[]|string)} [skiplist]
* @returnsreturn {string[]}
* @throws If the `start` and `end` strings aren't of the same length.
* @throws If `skiplist` isn't an array or string
Line 1,180 ⟶ 1,452:
throw new Error('start marker and end marker must be of the same length');
}
varlet level = 0;
varlet initial = null;
varconst result = [];
if (!Array.isArray(skiplist)) {
if (skiplist === undefined) {
Line 1,192 ⟶ 1,464:
}
}
for (varlet i = 0; i < str.length; ++i) {
for (varlet j = 0; j < skiplist.length; ++j) {
if (str.substr(i, skiplist[j].length) === skiplist[j]) {
i += skiplist[j].length - 1;
Line 1,222 ⟶ 1,494:
* templates that are going to be substituted, (e.g. PROD, XFD, RPP).
* Handles `|` outside a nowiki tag.
* Optionally, also adds a signature if not present already.
*
* @param {string} str
* @returnsparam {stringboolean} [addSig]
* @return {string}
*/
formatReasonText: function(str, addSig) {
varlet resultreason = (str || '').toString().trim();
varconst unbinder = new Morebits.unbinder(resultreason);
// eslint-disable-next-line no-useless-concat
unbinder.unbind('<no' + 'wiki>', '</no' + 'wiki>');
unbinder.content = unbinder.content.replace(/\|/g, '{{subst:!}}');
returnreason = unbinder.rebind();
if (addSig) {
const sig = '~~~~', sigIndex = reason.lastIndexOf(sig);
if (sigIndex === -1 || sigIndex !== reason.length - sig.length) {
reason += ' ' + sig;
}
}
return reason.trim();
},
 
Line 1,240 ⟶ 1,522:
*
* @param {string} str
* @returnsreturn {string}
*/
formatReasonForLog: function(str) {
Line 1,260 ⟶ 1,542:
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @returnsreturn {string}
*/
safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) {
Line 1,273 ⟶ 1,555:
*
* @param {string} expiry
* @returnsreturn {boolean}
*/
isInfinity: function morebitsStringIsInfinity(expiry) {
return ['indefinite', 'infinity', 'infinite', 'never'].indexOfincludes(expiry) !== -1;
},
 
/**
* Escapes a string to be used in a RegExp, replacing spaces and
* underscores with `[ _ ]` as they are often equivalent.
* Replaced RegExp.escape September 2020.
*
* @param {string} text - String to be escaped.
* @returnsreturn {string} - The escaped text.
*/
escapeRegExp: function(text) {
Line 1,291 ⟶ 1,572:
}
};
 
 
/**
Line 1,304 ⟶ 1,584:
*
* @param {Array} arr
* @returnsreturn {Array} A copy of the array with duplicates removed.
* @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(function(item, idx) {=> arr.indexOf(item) === idx);
return arr.indexOf(item) === idx;
});
},
 
Line 1,320 ⟶ 1,598:
*
* @param {Array} arr
* @returnsreturn {Array} A copy of the array with the first instance of each value
* removed; subsequent instances of those values (duplicates) remain.
* @throws When provided a non-array.
Line 1,326 ⟶ 1,604:
dups: function(arr) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.dups');
}
return arr.filter(function(item, idx) {=> arr.indexOf(item) !== idx);
return arr.indexOf(item) !== idx;
});
},
 
 
/**
Line 1,339 ⟶ 1,614:
* @param {Array} arr
* @param {number} size - Size of each chunk (except the last, which could be different).
* @returnsreturn {Array[]} An array containing the smaller, chunked arrays.
* @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.
}
varconst numChunks = Math.ceil(arr.length / size);
varconst result = new Array(numChunks);
for (varlet i = 0; i < numChunks; i++) {
result[i] = arr.slice(i * size, (i + 1) * size);
}
Line 1,366 ⟶ 1,641:
* @namespace Morebits.select2
* @memberof Morebits
* @requires jqueryjQuery.select2
*/
Morebits.select2 = {
Line 1,375 ⟶ 1,650:
*/
optgroupFull: function(params, data) {
varconst originalMatcher = $.fn.select2.defaults.defaults.matcher;
varconst result = originalMatcher(params, data);
 
if (result && params.term &&
data.text.toUpperCase().indexOfincludes(params.term.toUpperCase()) !== -1) {
result.children = data.children;
}
Line 1,387 ⟶ 1,662:
/** Custom matcher that matches from the beginning of words only. */
wordBeginning: function(params, data) {
varconst originalMatcher = $.fn.select2.defaults.defaults.matcher;
varconst result = originalMatcher(params, data);
if (!params.term || (result &&
new RegExp('\\b' + mw.util.escapeRegExp(params.term), 'i').test(result.text))) {
Line 1,399 ⟶ 1,674:
/** Underline matched part of options. */
highlightSearchMatches: function(data) {
varconst searchTerm = Morebits.select2SearchQuery;
if (!searchTerm || data.loading) {
return data.text;
}
varconst idx = data.text.toUpperCase().indexOf(searchTerm.toUpperCase());
if (idx < 0) {
return data.text;
Line 1,430 ⟶ 1,705:
return;
}
varlet $target = $(ev.target).closest('.select2-container');
if (!$target.length) {
return;
}
$target = $target.prev();
$target.select2('open');
varconst search = $target.data('select2').dropdown.$search ||
$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.focus();
search[0].focus();
}
 
};
 
 
/**
Line 1,482 ⟶ 1,757:
throw new Error('Both prefix and postfix must be provided');
}
varconst re = new RegExp(prefix + '([\\s\\S]*?)' + postfix, 'g');
this.content = this.content.replace(re, Morebits.unbinder.getCallback(this));
},
Line 1,489 ⟶ 1,764:
* Restore the hidden portion of the `content` string.
*
* @returnsreturn {string} The processed output.
*/
rebind: function UnbinderRebind() {
varlet content = this.content;
content.self = this;
for (varconst current in this.history) {
if (Object.prototype.hasOwnProperty.call(this.history, current)) {
content = content.replace(current, this.history[current]);
Line 1,510 ⟶ 1,785:
Morebits.unbinder.getCallback = function UnbinderGetCallback(self) {
return function UnbinderCallback(match) {
varconst current = self.prefix + self.counter + self.postfix;
self.history[current] = match;
++self.counter;
Line 1,516 ⟶ 1,791:
};
};
 
 
 
/* **************** Morebits.date **************** */
/**
* Create a date object with enhanced processing capabilities, a la {@link
* {@link https://momentjs.com/|moment.js}. MediaWiki timestamp format is also
* acceptable, in addition to everything that JS Date() accepts.
*
Line 1,529 ⟶ 1,802:
*/
Morebits.date = function() {
varconst args = Array.prototype.slice.call(arguments);
 
// Check MediaWiki formats
Line 1,536 ⟶ 1,809:
// 14-digit string will be interpreted differently.
if (args.length === 1) {
varconst param = args[0];
if (/^\d{14}$/.test(param)) {
// YYYYMMDDHHmmss
varconst digitMatch = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(param);
if (digitMatch) {
// ..... year ... month .. date ... hour .... minute ..... second
this._dprivateDate = new Date(Date.UTC.apply(null, [digitMatch[1], digitMatch[2] - 1, digitMatch[3], digitMatch[4], digitMatch[5], digitMatch[6]]));
}
} else if (typeof param === 'string') {
// Wikitext signature timestamp
varconst dateParts = Morebits.date.localeDatal10n.signatureTimestampFormat(param);
if (dateParts) {
this._dprivateDate = new Date(Date.UTC.apply(null, dateParts));
}
}
}
 
if (!this._dprivateDate) {
// Try standard date
this._dprivateDate = new (Function.prototype.bind.apply(Date, [Date].concat(args)))();
}
 
Line 1,577 ⟶ 1,850:
*/
Morebits.date.localeData = {
// message names here correspond to MediaWiki message names
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
months: [msg('january', 'January'), msg('february', 'February'), msg('march', 'March'),
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
days: ['Sunday', msg('Mondayapril', 'TuesdayApril'), msg('Wednesdaymay_long', 'ThursdayMay'), msg('Fridayjune', 'SaturdayJune']),
daysShort: ['Sun', msg('Monjuly', 'TueJuly'), msg('Wedaugust', 'ThuAugust'), msg('Friseptember', 'SatSeptember']),
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')
},
signatureTimestampFormat: function (str) {
// HH:mm, DD Month YYYY (UTC)
var rgx = /(\d{2}):(\d{2}), (\d{1,2}) (\w+) (\d{4}) \(UTC\)/;
var match = rgx.exec(str);
if (!match) {
return null;
}
var 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]];
}
};
 
/**
* 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 = {
/** @returnsreturn {boolean} */
isValid: function() {
return !isNaN(this.getTime());
Line 1,613 ⟶ 1,908:
/**
* @param {(Date|Morebits.date)} date
* @returnsreturn {boolean}
*/
isBefore: function(date) {
Line 1,620 ⟶ 1,915:
/**
* @param {(Date|Morebits.date)} date
* @returnsreturn {boolean}
*/
isAfter: function(date) {
Line 1,626 ⟶ 1,921:
},
 
/** @returnsreturn {string} */
getUTCMonthName: function() {
return Morebits.date.localeData.months[this.getUTCMonth()];
},
/** @returnsreturn {string} */
getUTCMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getUTCMonth()];
},
/** @returnsreturn {string} */
getMonthName: function() {
return Morebits.date.localeData.months[this.getMonth()];
},
/** @returnsreturn {string} */
getMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getMonth()];
},
/** @returnsreturn {string} */
getUTCDayName: function() {
return Morebits.date.localeData.days[this.getUTCDay()];
},
/** @returnsreturn {string} */
getUTCDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getUTCDay()];
},
/** @returnsreturn {string} */
getDayName: function() {
return Morebits.date.localeData.days[this.getDay()];
},
/** @returnsreturn {string} */
getDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getDay()];
Line 1,660 ⟶ 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,666 ⟶ 1,961:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @returnsreturn {Morebits.date}
*/
add: function(number, unit) {
let num = parseInt(number, 10); // normalize
// mapping time units with getter/setter function names
varif unitMap =(isNaN(num)) {
throw new Error('Invalid number "' + number + '" provided.');
seconds: 'Seconds',
}
minutes: 'Minutes',
unit = unit.toLowerCase(); // normalize
hours: 'Hours',
const unitMap = Morebits.date.unitMap;
days: 'Date',
let unitNorm = unitMap[unit] || unitMap[unit + 's']; // so that both singular and plural forms work
months: 'Month',
years: 'FullYear'
};
var 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
this['set' + unitNorm](this['get' + unitNorm]() + number);
// 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,687 ⟶ 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,693 ⟶ 1,991:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @returnsreturn {Morebits.date}
*/
subtract: function(number, unit) {
Line 1,700 ⟶ 1,998:
 
/**
* FormatsFormat the date into a string per the given format string.
* Replacement syntax is a subset of that in moment.js:
*
Line 1,706 ⟶ 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, padded3 digits |
* | 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 (01-indexed) |
* | MM | Month number (01-indexed, padded to 2 digits) |
* | MMM | Abbreviated month name |
* | MMMM | Full month name |
Line 1,733 ⟶ 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.
* @returnsreturn {string}
*/
format: function(formatstr, zone) {
Line 1,739 ⟶ 2,037:
return 'Invalid date'; // Put the truth out, preferable to "NaNNaNNan NaN:NaN" or whatever
}
varlet udate = this;
// create a new date object that will contain the date to display as system time
if (zone === 'utc') {
Line 1,753 ⟶ 2,051:
}
 
varconst pad = function(num, len) {
len = len || 2; // Up to length of 00 + 1
return ('00' + num).toString().slice(0 - len);
};
varconst h24 = udate.getHours(), m = udate.getMinutes(), s = udate.getSeconds(), ms = udate.getMilliseconds();
varconst D = udate.getDate(), M = udate.getMonth() + 1, Y = udate.getFullYear();
varconst h12 = h24 % 12 || 12, amOrPm = h24 >= 12 ? msg('period-pm', 'PM') : msg('period-am', 'AM');
varconst replacementMap = {
'HH': pad(h24), 'H': h24, 'hh': pad(h12), 'h': h12, 'A': amOrPm,
'mm': pad(m), 'm': m,
'ss': pad(s), 's': s,
'SSS': pad(ms, 3),
'dddd': udate.getDayName(), 'ddd': udate.getDayNameAbbrev(), 'd': udate.getDay(),
'DD': pad(D), 'D': D,
'MMMM': udate.getMonthName(), 'MMM': udate.getMonthNameAbbrev(), 'MM': pad(M), 'M': M,
'YYYY': Y, 'YY': pad(Y % 100), 'Y': Y
};
 
varconst unbinder = new Morebits.unbinder(formatstr); // escape stuff between [...]
unbinder.unbind('\\[', '\\]');
unbinder.content = unbinder.content.replace(
Line 1,779 ⟶ 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,
function(match) {=> replacementMap[match]
return replacementMap[match];
}
);
return unbinder.rebind().replace(/\[(.*?)\]/g, '$1');
Line 1,792 ⟶ 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.
* @returnsreturn {string}
*/
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().
varconst dateDiff = (new Date().setHours(0, 0, 0, 0) -
new Date(this).setHours(0, 0, 0, 0)) / 8.64e7;
switch (true) {
Line 1,819 ⟶ 2,115:
* as `==December 2019==` or `=== Jan 2018 ===`.
*
* @returnsreturn {RegExp}
*/
monthHeaderRegex: function() {
Line 1,831 ⟶ 2,127:
* @param {number} [level=2] - Header level. Pass 0 for just the text
* with no wikitext markers (==).
* @returnsreturn {string}
*/
monthHeader: function(level) {
Line 1,838 ⟶ 2,134:
level = isNaN(level) ? 2 : level;
 
const header = '='.repeat(level);
var header = Array(level + 1).join('='); // String.prototype.repeat not supported in IE 11
varconst text = this.getUTCMonthName() + ' ' + this.getUTCFullYear();
 
if (header.length) { // wikitext-formatted header
Line 1,851 ⟶ 2,147:
 
// Allow native Date.prototype methods to be used on Morebits.date objects
Object.getOwnPropertyNames(Date.prototype).forEach(function(func) => {
Morebits.date.prototype[func] = function() {
// Exclude methods that collide with PageTriage's Date.js external, which clobbers native Date: [[phab:T268513]]
return this.privateDate[func].apply(this.privateDate, Array.prototype.slice.call(arguments));
if (['add', 'getDayName', 'getMonthName'].indexOf(func) === -1) {
};
Morebits.date.prototype[func] = function() {
return this._d[func].apply(this._d, Array.prototype.slice.call(arguments));
};
}
});
 
 
/* **************** Morebits.wiki **************** */
/**
* Various objects for wiki editing and API access, including {@link
* {@link Morebits.wiki.api} and {@link Morebits.wiki.page}.
*
* @namespace Morebits.wiki
Line 1,874 ⟶ 2,166:
* @deprecated in favor of Morebits.isPageRedirect as of November 2020
* @memberof Morebits.wiki
* @returnsreturn {boolean}
*/
Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() {
Line 1,880 ⟶ 2,172:
return Morebits.isPageRedirect();
};
 
 
/* **************** Morebits.wiki.actionCompleted **************** */
Line 1,942 ⟶ 2,233:
}
}
window.setTimeout(function() => {
window.___location = Morebits.wiki.actionCompleted.redirect;
}, Morebits.wiki.actionCompleted.timeOut);
Line 1,966 ⟶ 2,257:
}
};
 
 
/* **************** Morebits.wiki.api **************** */
Line 1,985 ⟶ 2,275:
* @class
* @param {string} currentAction - The current action (required).
* @param {objectObject} query - The query (required).
* @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 1,995 ⟶ 2,285:
this.query.assert = 'user';
// Enforce newer error formats, preferring html
if (!query.errorformat || !['wikitext', 'plaintext'].indexOfincludes(query.errorformat) === -1) {
this.query.errorformat = 'html';
}
Line 2,016 ⟶ 2,306:
} else if (query.format === 'json' && !query.formatversion) {
this.query.formatversion = '2';
} else if (!['xml', 'json'].indexOfincludes(query.format) === -1) {
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'].indexOfincludes(query.action) !== -1) {
delete query.tags;
} else if (!query.tags && morebitsWikiChangeTag) {
Line 2,032 ⟶ 2,322:
onSuccess: null,
onError: null,
parent: window, // use global context if there is no parent object
query: null,
response: null,
responseXML: null, // use `response` instead; retained for backwards compatibility
statelem: null, // this non-standard name kept for backwards compatibility
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,060 ⟶ 2,350:
* Carry out the request.
*
* @param {objectObject} callerAjaxParameters - Do not specify a parameter unless you really
* really want to give jQuery some extra parameters.
* @returnsreturn {promisejQuery.Promise} - A jQuery promise object that is resolved or rejected with the api object.
*/
post: function(callerAjaxParameters) {
Line 2,068 ⟶ 2,358:
++Morebits.wiki.numberOfActionsLeft;
 
varconst queryString = $.map(this.query, function(val, i) => {
if (Array.isArray(val)) {
return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|');
Line 2,077 ⟶ 2,367:
// token should always be the last item in the query string (bug TW-B-0013)
 
varconst ajaxparams = $.extend({}, {
context: this,
type: this.query.action === 'query' ? 'GET' : 'POST',
Line 2,118 ⟶ 2,408:
this.onSuccess.call(this.parent, this);
} else {
this.statelem.info(msg('done', 'done'));
}
 
Line 2,130 ⟶ 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,139 ⟶ 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(function(token) => {
this.query.token = token;
return this.post(callerAjaxParameters);
}.bind(this));
}
 
Line 2,185 ⟶ 2,475:
};
 
/** 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);
});
};
 
var morebitsWikiApiUserAgent = 'morebits.js ([[w:WT:TW]])';
/**
* CustomSet the custom user agent header, usedwhich byis WMFused for server-side logging. Set via
* Note that doing so will set the useragent for every `Morebits.wiki.api`
* {@link Morebits.wiki.api.setApiUserAgent|setApiUserAgent}.
* process performed thereafter.
*
* @see {@link https://lists.wikimedia.org/pipermail/mediawiki-api-announce/2014-November/000075.html}
Line 2,193 ⟶ 2,505:
*
* @memberof Morebits.wiki.api
* @param {string} [ua=morebits.js ([[w:WT:TW]])] - User agent. The default
* @type {string}
* value of `morebits.js ([[w:WT:TW]])` will be appended to any provided
*/
* value.
var morebitsWikiApiUserAgent = 'morebits.js ([[w:WT:TW]])';
 
/**
* Sets the custom user agent header.
*
* @memberof Morebits.wiki.api
* @param {string} [ua] - User agent.
*/
Morebits.wiki.api.setApiUserAgent = function(ua) {
morebitsWikiApiUserAgent = (ua ? ua + ' ' : '') + 'morebits.js ([[w:WT:TW]])';
};
 
 
 
/**
* Change/revision tag applied to Morebits actions when no other tags are specified.
* DefaultsUnused toby unuseddefault per {@link https://en.wikipedia.org/w/index.php?oldid=970618849#Adding_tags_to_Twinkle_edits_and_actions|EnWiki consensus}.
*
* @constant
Line 2,218 ⟶ 2,522:
*/
var morebitsWikiChangeTag = '';
 
 
/**
Line 2,224 ⟶ 2,527:
*
* @memberof Morebits.wiki.api
* @returnsreturn {string} MediaWiki CSRF token.
*/
Morebits.wiki.api.getToken = function() {
varconst tokenApi = new Morebits.wiki.api(msg('getting-token', 'Getting token'), {
action: 'query',
meta: 'tokens',
Line 2,233 ⟶ 2,536:
format: 'json'
});
return tokenApi.post().then(function(apiobj) {=> apiobj.response.query.tokens.csrftoken);
return apiobj.response.query.tokens.csrftoken;
});
};
 
 
/* **************** Morebits.wiki.page **************** */
Line 2,278 ⟶ 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,284 ⟶ 2,583:
* @param {string} pageName - The name of the page, prefixed by the namespace (if any).
* For the current page, use `mw.config.get('wgPageName')`.
* @param {string|Morebits.status} [currentActionstatus] - A string describing the action about to be undertaken.,
* or a Morebits.status object
*/
Morebits.wiki.page = function(pageName, currentActionstatus) {
 
if (!currentActionstatus) {
currentActionstatus = msg('opening-page', pageName, 'Opening page "' + pageName + '"');
}
 
Line 2,300 ⟶ 2,600:
* @private
*/
varconst ctx = {
// backing fields for public properties
pageName: pageName,
Line 2,306 ⟶ 2,606:
editSummary: null,
changeTags: null,
testActions: null, // array if any valid actions
callbackParameters: null,
statusElement: status instanceof Morebits.status ? status : new Morebits.status(currentActionstatus),
 
// - edit
pageText: null,
editMode: 'all', // save() replaces entire contents of the page by default
appendText: null, // can't reuse pageText for this because pageText is needed to follow a redirect
prependText: null, // can't reuse pageText for this because pageText is needed to follow a redirect
newSectionText: null,
newSectionTitle: null,
Line 2,344 ⟶ 2,644:
protectCreate: null,
protectCascade: null,
 
// - delete
deleteTalkPage: false,
 
// - undelete
undeleteTalkPage: false,
 
// - creation lookup
Line 2,360 ⟶ 2,666:
revertCurID: null,
revertUser: null,
watched: false,
fullyProtected: false,
suppressProtectWarning: false,
Line 2,371 ⟶ 2,678:
onSaveFailure: null,
onLookupCreationSuccess: null,
onLookupCreationFailure: null,
onMoveSuccess: null,
onMoveFailure: null,
Line 2,404 ⟶ 2,712:
};
 
varconst emptyFunction = function() { };
 
/**
Line 2,426 ⟶ 2,734:
action: 'query',
prop: 'info|revisions',
inprop: 'watched',
intestactions: 'edit', // can be expanded
curtimestamp: '',
Line 2,436 ⟶ 2,745:
 
if (ctx.editMode === 'all') {
ctx.loadQuery.rvprop = 'content|timestamp'; // get the page content at the same time, if needed
} else if (ctx.editMode === 'revert') {
ctx.loadQuery.rvprop = 'timestamp';
Line 2,444 ⟶ 2,753:
 
if (ctx.followRedirect) {
ctx.loadQuery.redirects = ''; // follow all redirects
}
if (typeof ctx.pageSection === 'number') {
Line 2,450 ⟶ 2,759:
}
if (Morebits.userIsSysop) {
ctx.loadQuery.inprop += '|protection';
}
 
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,465 ⟶ 2,774:
* previous `load()` callbacks to recover from edit conflicts! In this
* case, callers must make the same edit to the new pageText and
* reinvokere-invoke `save()`. This behavior can be disabled with
* `setMaxConflictRetries(0)`.
*
Line 2,476 ⟶ 2,785:
 
// are we getting our editing token from mw.user.tokens?
varconst canUseMwUserToken = fnCanUseMwUserToken('edit');
 
if (!ctx.pageLoaded && !canUseMwUserToken) {
Line 2,498 ⟶ 2,807:
// shouldn't happen if canUseMwUserToken === true
if (ctx.fullyProtected && !ctx.suppressProtectWarning &&
!confirm(
!confirm('You are about to make an edit to the fully protected page "' + ctx.pageName +
( ctx.fullyProtected === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + new Morebits.date(ctx.fullyProtected).calendar('utc') + ' (UTC))') +
msg('protected-indef-edit-warning', ctx.pageName,
'. \n\nClick OK to proceed with the edit, or Cancel to skip this edit.')) {
'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.'
ctx.statusElement.error('Edit to fully protected page was aborted.');
) :
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,508 ⟶ 2,825:
ctx.retries = 0;
 
varconst query = {
action: 'edit',
title: ctx.pageName,
Line 2,520 ⟶ 2,837:
}
 
if (ctx.watchlistExpiryfnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 2,532 ⟶ 2,849:
query.minor = true;
} else {
query.notminor = true; // force Twinkle config to override user preference setting for "all edits are minor"
}
 
// Set bot edit attribute. If this paramterparameter is present with any value, it is interpreted as true
if (ctx.botEdit) {
query.bot = true;
Line 2,547 ⟶ 2,864:
return;
}
query.appendtext = ctx.appendText; // use mode to append to current page contents
break;
case 'prepend':
Line 2,555 ⟶ 2,872:
return;
}
query.prependtext = ctx.prependText; // use mode to prepend to current page contents
break;
case 'new':
Line 2,564 ⟶ 2,881:
}
query.section = 'new';
query.text = ctx.newSectionText; // add a new section to current page
query.sectiontitle = ctx.newSectionTitle || ctx.editSummary; // done by the API, but non-'' values would get treated as text
break;
Line 2,584 ⟶ 2,901:
}
 
if (['recreate', 'createonly', 'nocreate'].indexOfincludes(ctx.createOption) !== -1) {
query[ctx.createOption] = '';
}
Line 2,592 ⟶ 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,598 ⟶ 2,915:
 
/**
* Adds the text provided via `setAppendText()` to the end of the page.
* page. Does not require calling `load()` first., unless a watchlist
* expiry is used.
*
* @param {Function} [onSuccess] - Callback function which is called when the method has succeeded.
Line 2,617 ⟶ 2,935:
 
/**
* Adds the text provided via `setPrependText()` to the start of the page.
* page. Does not require calling `load()` first., unless a watchlist
* expiry is used.
*
* @param {Function} [onSuccess] - Callback function which is called when the method has succeeded.
Line 2,640 ⟶ 2,959:
* If `editSummary` is provided, that will be used instead of the
* autogenerated "->Title (new section" edit summary.
* Does not require calling `load()` first., unless a watchlist expiry
* is used.
*
* @param {Function} [onSuccess] - Callback function which is called when the method has succeeded.
Line 2,657 ⟶ 2,977:
};
 
/** @returnsreturn {string} The name of the loaded page, including the namespace */
this.getPageName = function() {
return ctx.pageName;
};
 
/** @returnsreturn {string} The text of the page after a successful load() */
this.getPageText = function() {
return ctx.pageText;
Line 2,699 ⟶ 3,019:
ctx.newSectionTitle = newSectionTitle;
};
 
 
 
// Edit-related setter methods:
Line 2,724 ⟶ 3,042:
ctx.changeTags = tags;
};
 
 
/**
Line 2,734 ⟶ 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,775 ⟶ 3,091:
 
/**
* Set whether and how to watch the page, including setting an expiry.
* @param {boolean|string} [watchlistOption=false] -
*
* @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`|`'no'`: watchlist status of the page will not be changed.
* - `false`|`'defaultno'`|`'preferencesnochange'`: watchlist status of the page (including expiry) will not be changed.
* - `'default'`|`'preferences'`: watchlist status of the page will be
* be set based on the user's preference settings when the action is
* set based on the user's preference settings when the action is
* called. Ignores ability of default + expiry.
* called. Defaults to an indefinite watch unless `watchlistExpiry` is
* - `'unwatch'`: explicitly unwatch the page
* provided.
* - {string|number}: watch page until the specified time (relative or absolute datestring)
* - `'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 (!watchlistOption instanceof Morebits.date || watchlistOption ===instanceof 'no'Date) {
ctx.watchlistOption = 'nochange'watchlistOption.toISOString();
}
} else if (watchlistOption === 'default' || watchlistOption === 'preferences') {
if (typeof watchlistExpiry === 'undefined') {
ctx.watchlistOption = 'preferences';
watchlistExpiry = 'infinity';
} else if (watchlistOption === 'unwatch') {
} else if (watchlistExpiry instanceof Morebits.date || watchlistExpiry instanceof Date) {
ctx.watchlistOption = 'unwatch';
watchlistExpiry = watchlistExpiry.toISOString();
} else {
}
ctx.watchlistOption = 'watch';
 
if (typeof watchlistOption === 'number' || (typeof watchlistOption === 'string' && watchlistOption !== 'yes')) {
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;
} break;
}
};
 
/**
* Set ana watchlist expiry. setWatchlist can mostly handle this by itself if passed a
* stringitself, so this is here largely for completeness and compatibility.
* with the full suite of options.
*
* @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.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,863 ⟶ 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 retrivedretrieved.
* 2. Revisions that the user is not privileged to access
* (revdeled/suppressed) will be treated as non-redirects.
Line 2,919 ⟶ 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,926 ⟶ 3,313:
};
 
/** @returnsreturn {string} The current revision ID of the page */
this.getCurrentID = function() {
return ctx.revertCurID;
};
 
/** @returnsreturn {string} Last editor of the page */
this.getRevisionUser = function() {
return ctx.revertUser;
};
 
/** @returnsreturn {string} ISO 8601 timestamp at which the page was last edited. */
this.getLastEditTime = function() {
return ctx.lastEditTime;
Line 2,953 ⟶ 3,340:
* detected upon calling `save()`.
*
* @param {objectObject} callbackParameters
*/
this.setCallbackParameters = function(callbackParameters) {
Line 2,960 ⟶ 3,347:
 
/**
* @returnsreturn {objectObject} - The object previously set by `setCallbackParameters()`.
*/
this.getCallbackParameters = function() {
Line 2,967 ⟶ 3,354:
 
/**
* @returnsparam {Morebits.status} Status element created by the constructor.statusElement
*/
this.setStatusElement = function(statusElement) {
ctx.statusElement = statusElement;
};
 
/**
* @return {Morebits.status} Status element created by the constructor.
*/
this.getStatusElement = function() {
Line 2,983 ⟶ 3,377:
 
/**
* @returnsreturn {boolean} True if the page existed on the wiki when it was last loaded.
*/
this.exists = function() {
Line 2,990 ⟶ 3,384:
 
/**
* @returnsreturn {string} Page ID of the page loaded. 0 if the page doesn't
* exist.
*/
Line 2,998 ⟶ 3,392:
 
/**
* @returnsreturn {string} - Content model of the page. Possible values
* include (but may not be limited to): `wikitext`, `javascript`,
* `css`, `json`, `Scribunto`, `sanitized-css`, `MassMessageListContent`.
Line 3,008 ⟶ 3,402:
 
/**
* @returnsreturn {boolean|string} ISO- 8601Watched timestampstatus at whichof the page. was last loaded.Boolean
* unless it's being watched temporarily, in which case returns the
* expiry string.
*/
this.getWatched = function () {
return ctx.watched;
};
 
/**
* @return {string} ISO 8601 timestamp at which the page was last loaded.
*/
this.getLoadTime = function() {
Line 3,015 ⟶ 3,418:
 
/**
* @returnsreturn {string} The user who created the page following `lookupCreation()`.
*/
this.getCreator = function() {
Line 3,022 ⟶ 3,425:
 
/**
* @returnsreturn {string} The ISOString timestamp of page creation following `lookupCreation()`.
*/
this.getCreationTimestamp = function() {
Line 3,028 ⟶ 3,431:
};
 
/** @returnsreturn {boolean} whether or not you can edit the page */
this.canEdit = function() {
return !!ctx.testActions && ctx.testActions.indexOfincludes('edit') !== -1;
};
 
Line 3,042 ⟶ 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;
}
ctx.onLookupCreationSuccess = onSuccess;
 
varconst query = {
'action': 'query',
'prop': 'revisions',
'titles': ctx.pageName,
'rvlimit': 1,
'rvprop': 'user|timestamp',
'rvdir': 'newer',
'format': 'json'
};
 
Line 3,071 ⟶ 3,478:
 
if (ctx.followRedirect) {
query.redirects = ''; // follow all 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,122 ⟶ 3,529:
fnProcessMove.call(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('move');
 
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,146 ⟶ 3,553:
// If a link is present, don't need to check if it's patrolled
if ($('.patrollink').length) {
varconst patrolhref = $('.patrollink a').attr('href');
ctx.rcid = mw.util.getParamValue('rcid', patrolhref);
fnProcessPatrol(this, this);
} else {
varconst patrolQuery = {
action: 'query',
prop: 'info',
Line 3,163 ⟶ 3,570:
};
 
ctx.patrolApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), patrolQuery, fnProcessPatrol);
ctx.patrolApi.setParent(this);
ctx.patrolApi.post();
Line 3,179 ⟶ 3,586:
* using {@link Morebits.wiki.api} is probably preferable.
*
* Will first check if the page is queued via {@link
* {@link Morebits.wiki.page~fnProcessTriageList|fnProcessTriageList}.
*
* No error handling since we don't actually care about the errors.
Line 3,188 ⟶ 3,595:
this.triage = function() {
// Fall back to patrol if not a valid triage namespace
if (!mw.config.get('pageTriageNamespaces').indexOfincludes(new mw.Title(ctx.pageName).getNamespaceId()) === -1) {
this.patrol();
} else {
Line 3,200 ⟶ 3,607:
fnProcessTriageList(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('triage');
 
ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList);
ctx.triageApi.setParent(this);
ctx.triageApi.post();
Line 3,227 ⟶ 3,634:
fnProcessDelete.call(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('delete');
 
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,252 ⟶ 3,659:
fnProcessUndelete.call(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('undelete');
 
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,283 ⟶ 3,690:
// (absolute, not differential), we always need to request
// protection levels from the server
varconst query = fnNeedTokenInfoQuery('protect');
 
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,318 ⟶ 3,725:
fnProcessStabilize.call(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('stabilize');
 
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,332 ⟶ 3,739:
 
/**
* Determines whether we can save an API call by using the csrf token sent with the page
* sent with the page HTML, or whether we need to ask the server for
* more info (e.g. protection or watchlist expiry).
*
* Currently used for `append`, `prepend`, `newSection`, `move`,
* `stabilize`, `deletePage`, and `undeletePage`. Can'tNot useused for
* `protect` since it always needs to request protection status.
*
* @param {string} [action=edit] - The action being undertaken, e.g.
* "edit" or "delete". In practice, only "edit" or "notedit" matters.
* @returnsreturn {boolean}
*/
var fnCanUseMwUserToken = function(action = 'edit') {
// If a watchlist expiry is set, we must always load the page
action = typeof action !== 'undefined' ? action : 'edit'; // IE doesn't support default parameters
// to avoid overwriting indefinite protection. Of course, not
// needed if setting indefinite watching!
if (ctx.watchlistExpiry && !Morebits.string.isInfinity(ctx.watchlistExpiry)) {
return false;
}
 
// API-based redirect resolution only works for action=query and
Line 3,365 ⟶ 3,778:
// wgRestrictionEdit is null on non-existent pages,
// so this neatly handles nonexistent pages
varconst editRestriction = mw.config.get('wgRestrictionEdit');
if (!editRestriction || editRestriction.indexOfincludes('sysop') !== -1) {
return false;
}
Line 3,375 ⟶ 3,788:
 
/**
* When functions can't use {@link
* {@link Morebits.wiki.page~fnCanUseMwUserToken|fnCanUseMwUserToken} or
* or require checking protection or watched status, maintain the query in one place. Used
* in one place. Used for {@link Morebits.wiki.page#deletePage|delete}, {@link
* {@link Morebits.wiki.page#undeletePage|undelete}, {@link
* {@link* Morebits.wiki.page#protect|protect}, {@link
* {@link Morebits.wiki.page#stabilize|stabilize}, and {@link
* and {@link Morebits.wiki.page#move|move} (basically, just not {@link
* (basically, just not {@link Morebits.wiki.page#load|load}).
*
* @param {string} action - The action being undertaken, e.g. "edit" or
* "delete".
* @returnsreturn {objectObject} Appropriate token query.
*/
var fnNeedTokenInfoQuery = function(action) {
varconst query = {
action: 'query',
meta: 'tokens',
type: 'csrf',
titles: ctx.pageName,
prop: 'info',
inprop: 'watched',
format: 'json'
};
// Protection not checked for flagged-revs or non-sysop moves
if (action !== 'stabilize' && (action !== 'move' || Morebits.userIsSysop)) {
query.propinprop += 'info|protection';
query.inprop = 'protection';
}
if (ctx.followRedirect && action !== 'undelete') {
Line 3,415 ⟶ 3,829:
// callback from loadApi.post()
var fnLoadSuccess = function() {
varconst response = ctx.loadApi.getResponse().query;
 
if (!fnCheckPageName(response, ctx.onLoadFailure)) {
Line 3,421 ⟶ 3,835:
}
 
varconst page = response.pages[0], rev;
let rev;
ctx.pageExists = !page.missing;
if (ctx.pageExists) {
Line 3,429 ⟶ 3,844:
ctx.pageID = page.pageid;
} else {
ctx.pageText = ''; // allow for concatenation, etc.
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,446 ⟶ 3,861:
 
ctx.contentModel = page.contentmodel;
ctx.watched = page.watchlistexpiry || page.watched;
 
// extract protection info, to alert admins when they are about to edit a protected page
// Includes cascading protection
if (Morebits.userIsSysop) {
varconst editProt = page.protection.filter(function(pr) {=> pr.type === 'edit' && pr.level === 'sysop').pop();
return pr.type === 'edit' && pr.level === 'sysop';
}).pop();
if (editProt) {
ctx.fullyProtected = editProt.expiry;
Line 3,462 ⟶ 3,876:
ctx.revertCurID = page.lastrevid;
 
varconst testactions = page.actions;
ctx.testActions = []; // was null
Object.keys(testactions).forEach(function(action) => {
if (testactions[action]) {
ctx.testActions.push(action);
Line 3,479 ⟶ 3,893:
ctx.revertUser = rev && rev.user;
if (!ctx.revertUser) {
if (rev && rev.userhidden) { // username was RevDel'd or oversighted
ctx.revertUser = '<username hidden>';
} else {
Line 3,494 ⟶ 3,908:
 
// alert("Generate edit conflict now"); // for testing edit conflict recovery logic
ctx.onLoadSuccess(this); // invoke callback
};
 
Line 3,503 ⟶ 3,917:
}
 
varconst page = response.pages && response.pages[0];
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
}
 
// retrieve actual title of the page after normalization and redirects
if const resolvedName = (page.title) {;
var resolvedName = page.title;
 
if (response.redirects) {
// check for cross-namespace redirect:
varconst origNs = new mw.Title(ctx.pageName).namespace;
varconst newNs = new mw.Title(resolvedName).namespace;
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,526 ⟶ 3,940:
 
// only notify user for redirects, not normalization
new Morebits.status.info('InfoNote', msg('redirected', ctx.pageName, resolvedName, 'Redirected from ' + ctx.pageName + ' to ' + resolvedName));
}
 
Line 3,533 ⟶ 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,541 ⟶ 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'; // cancel append/prepend/newSection/revert modes
varconst response = ctx.saveApi.getResponse();
 
// see if the API thinks we were successful
Line 3,553 ⟶ 4,009:
// real success
// default on success action - display link for edited page
varconst link = document.createElement('a');
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); // invoke callback
}
return;
Line 3,568 ⟶ 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,579 ⟶ 4,035:
// callback from saveApi.post()
var fnSaveError = function() {
varconst errorCode = ctx.saveApi.getErrorCode();
 
// check for edit conflict
Line 3,585 ⟶ 4,041:
 
// edit conflicts can occur when the page needs to be purged from the server cache
varconst purgeQuery = {
action: 'purge',
titles: ctx.pageName // redirects are already resolved
};
 
varconst purgeApi = new Morebits.wiki.api(msg('editconflict-purging', 'Edit conflict detected, purging server cache'), purgeQuery, function(() => {
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
 
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,599 ⟶ 4,055:
ctx.loadApi.post(); // reload the page and reapply the edit
}
}), ctx.statusElement);
purgeApi.post();
 
Line 3,606 ⟶ 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; // allow for normal completion if retry succeeds
 
// wait for sometime for client to regain connnectivityconnectivity
sleep(2000).then(function() => {
ctx.saveApi.post(); // give it another go!
});
Line 3,616 ⟶ 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,625 ⟶ 4,084:
 
case 'abusefilter-disallowed':
ctx.statusElement.error('The edit was disallowed by the edit filter: "' + ctx.saveApi.getResponse().errorerrorData.abusefilter.description + '".');
break;
 
case 'abusefilter-warning':
ctx.statusElement.error([ 'A warning was returned by the edit filter: "', ctx.saveApi.getResponse().errorerrorData.abusefilter.description, '". If you wish to proceed with the edit, please carry it out again. This warning will not appear a second time.' ]);
// 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,636 ⟶ 4,095:
case 'spamblacklist':
// If multiple items are blacklisted, we only return the first
var spam = ctx.saveApi.getResponse().errorerrorData.spamblacklist.matches[0];
ctx.statusElement.error('Could not save the page because the URL ' + spam + ' is on the spam blacklist');
break;
Line 3,644 ⟶ 4,103:
}
 
ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes
if (ctx.onSaveFailure) {
ctx.onSaveFailure(this); // invoke callback
}
}
};
 
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() {
varconst response = ctx.lookupCreationApi.getResponse().query;
 
if (!fnCheckPageName(response, ctx.onLookupCreationFailure)) {
return; // abort
}
 
varconst rev = response.pages[0].revisions && response.pages[0].revisions[0];
if (!rev) {
ctx.statusElement.error('Could not find any revisions of ' + ctx.pageName);
ctx.onLookupCreationFailure(this);
return;
}
 
if (!ctx.lookupNonRedirectCreator || !/^\s*#redirect/i.testisTextRedirect(rev.content)) {
 
ctx.creator = rev.user;
if (!ctx.creator) {
ctx.statusElement.error('Could not find name of page creator');
ctx.onLookupCreationFailure(this);
return;
}
Line 3,674 ⟶ 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,682 ⟶ 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,690 ⟶ 4,161:
 
var fnLookupNonRedirectCreator = function() {
varconst response = ctx.ookupCreationApilookupCreationApi.getResponse().query;
varconst revs = response.pages[0].revisions;
 
for (let i = 0; i < revs.length; i++) {
revs.forEach(function(rev) {
 
if (!/^\s*#redirect/i.test(rev.textContent)) { // inaccessible revisions also check out
if (!isTextRedirect(revs[i].content)) {
ctx.creator = rev.user;
ctx.timestampcreator = revrevs[i].timestampuser;
ctx.timestamp = revs[i].timestamp;
return false; // break
break;
}
});
 
if (!ctx.creator) {
Line 3,707 ⟶ 4,179:
if (!ctx.creator) {
ctx.statusElement.error('Could not find name of page creator');
ctx.onLookupCreationFailure(this);
return;
}
Line 3,713 ⟶ 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,722 ⟶ 4,197:
/**
* Common checks for action methods. Used for move, undelete, delete,
* protect, stabilize.
*
* @param {string} action - The action being checked.
* @param {string} onFailure - Failure callback.
* @returnsreturn {boolean}
*/
var fnPreflightChecks = function(action, onFailure) {
Line 3,751 ⟶ 4,226:
* @param {string} onFailure - Failure callback.
* @param {string} response - The response document from the API call.
* @returnsreturn {boolean}
*/
varconst fnProcessChecks = function(action, onFailure, response) {
varconst missing = response.pages[0].missing;
 
// No undelete as an existing page could have deleted revisions
varconst actionMissing = missing && ['delete', 'stabilize', 'move'].indexOfincludes(action) !== -1;
varconst protectMissing = action === 'protect' && missing && (ctx.protectEdit || ctx.protectMove);
varconst saltMissing = action === 'protect' && !missing && ctx.protectCreate;
 
if (actionMissing || protectMissing || saltMissing) {
Line 3,769 ⟶ 4,244:
// Delete, undelete, move
// extract protection info
varlet editprot;
if (action === 'undelete') {
editprot = response.pages[0].protection.filter(function(pr) {=> pr.type === 'create' && pr.level === 'sysop').pop();
return pr.type === 'create' && pr.level === 'sysop';
}).pop();
} else if (action === 'delete' || action === 'move') {
editprot = response.pages[0].protection.filter(function(pr) {=> pr.type === 'edit' && pr.level === 'sysop').pop();
return pr.type === 'edit' && pr.level === 'sysop';
}).pop();
}
if (editprot && !ctx.suppressProtectWarning &&
Line 3,797 ⟶ 4,268:
 
var fnProcessMove = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('move')) {
Line 3,803 ⟶ 4,274:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.moveApi.getResponse().query;
 
if (!fnProcessChecks('move', ctx.onMoveFailure, response)) {
Line 3,810 ⟶ 4,281:
 
token = response.tokens.csrftoken;
pageTitleconst page = response.pages[0].title;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
 
varconst query = {
'action': 'move',
'from': pageTitle,
'to': ctx.moveDestination,
'token': token,
'reason': ctx.editSummary,
'watchlist': ctx.watchlistOption,
'format': 'json'
};
if (ctx.changeTags) {
Line 3,826 ⟶ 4,299:
}
 
if (ctx.watchlistExpiryfnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 3,839 ⟶ 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,845 ⟶ 4,318:
 
var fnProcessPatrol = function() {
varconst query = {
action: 'patrol',
format: 'json'
Line 3,855 ⟶ 4,328:
query.token = mw.user.tokens.get('patrolToken');
} else {
varconst response = ctx.patrolApi.getResponse().query;
 
// Don't patrol if not unpatrolled
Line 3,862 ⟶ 4,335:
}
 
varconst lastrevid = response.pages[0].lastrevid;
if (!lastrevid) {
return;
Line 3,868 ⟶ 4,341:
query.revid = lastrevid;
 
varconst token = response.tokens.csrftoken;
if (!token) {
return;
Line 3,878 ⟶ 4,351:
}
 
varconst patrolStat = new Morebits.status('Marking page as patrolled');
 
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat);
Line 3,890 ⟶ 4,363:
ctx.csrfToken = mw.user.tokens.get('csrfToken');
} else {
varconst response = ctx.triageApi.getResponse().query;
 
ctx.pageID = response.pages[0].pageid;
Line 3,903 ⟶ 4,376:
}
 
varconst query = {
action: 'pagetriagelist',
page_id: ctx.pageID,
Line 3,916 ⟶ 4,389:
// callback from triageProcessListApi.post()
var fnProcessTriage = function() {
varconst responseList = ctx.triageProcessListApi.getResponse().pagetriagelist;
// Exit if not in the queue
if (!responseList || responseList.result !== 'success') {
return;
}
varconst page = responseList.pages && responseList.pages[0];
// Do nothing if page already triaged/patrolled
if (!page || !parseInt(page.patrol_status, 10)) {
varconst query = {
action: 'pagetriageaction',
pageid: ctx.pageID,
Line 3,934 ⟶ 4,407:
format: 'json'
};
varconst triageStat = new Morebits.status('Marking page as curated');
ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, null, triageStat);
ctx.triageProcessApi.setParent(this);
Line 3,942 ⟶ 4,415:
 
var fnProcessDelete = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('delete')) {
Line 3,948 ⟶ 4,421:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.deleteApi.getResponse().query;
 
if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) {
Line 3,955 ⟶ 4,428:
 
token = response.tokens.csrftoken;
pageTitleconst page = response.pages[0].title;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
 
varconst query = {
'action': 'delete',
'title': pageTitle,
'token': token,
'reason': ctx.editSummary,
'watchlist': ctx.watchlistOption,
'format': 'json'
};
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
if (ctx.deleteTalkPage) {
query.deletetalk = 'true';
}
 
if (ctx.watchlistExpiryfnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 3,982 ⟶ 4,460:
var fnProcessDeleteError = function() {
 
varconst errorCode = ctx.deleteProcessApi.getErrorCode();
 
// 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; // allow for normal completion if retry succeeds
ctx.deleteProcessApi.post(); // give it another go!
 
Line 3,993 ⟶ 4,471:
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback
}
// hard error, give up
Line 3,999 ⟶ 4,477:
ctx.statusElement.error('Failed to delete the page: ' + ctx.deleteProcessApi.getErrorText());
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback
}
}
Line 4,005 ⟶ 4,483:
 
var fnProcessUndelete = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('undelete')) {
Line 4,011 ⟶ 4,489:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.undeleteApi.getResponse().query;
 
if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) {
Line 4,018 ⟶ 4,496:
 
token = response.tokens.csrftoken;
pageTitleconst page = response.pages[0].title;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
 
varconst query = {
'action': 'undelete',
'title': pageTitle,
'token': token,
'reason': ctx.editSummary,
'watchlist': ctx.watchlistOption,
'format': 'json'
};
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
if (ctx.undeleteTalkPage) {
query.undeletetalk = 'true';
}
 
if (ctx.watchlistExpiryfnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 4,045 ⟶ 4,528:
var fnProcessUndeleteError = function() {
 
varconst errorCode = ctx.undeleteProcessApi.getErrorCode();
 
// check for "Database query error"
Line 4,051 ⟶ 4,534:
if (ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
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); // invoke callback
}
}
Line 4,062 ⟶ 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); // invoke callback
}
// hard error, give up
Line 4,068 ⟶ 4,551:
ctx.statusElement.error('Failed to undelete the page: ' + ctx.undeleteProcessApi.getErrorText());
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback
}
}
Line 4,074 ⟶ 4,557:
 
var fnProcessProtect = function() {
varconst response = ctx.protectApi.getResponse().query;
 
if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) {
Line 4,080 ⟶ 4,563:
}
 
varconst token = response.tokens.csrftoken;
varconst pageTitlepage = response.pages[0].title;
const pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
 
// Fetch existing protection levels
varconst prs = response.pages[0].protection;
varlet editprot, moveprot, createprot;
prs.forEach(function(pr) => {
// Filter out protection from cascading
if (pr.type === 'edit' && !pr.source) {
Line 4,096 ⟶ 4,581:
}
});
 
 
// Fall back to current levels if not explicitly set
Line 4,111 ⟶ 4,595:
// Default to pre-existing cascading protection if unchanged (similar to above)
if (ctx.protectCascade === null) {
ctx.protectCascade = !!prs.filter(function(pr) {=> pr.cascade).length;
return pr.cascade;
}).length;
}
// Warn if cascading protection being applied with an invalid protection level,
Line 4,135 ⟶ 4,617:
 
// Build protection levels and expirys (expiries?) for query
varconst protections = [], expirys = [];
if (ctx.protectEdit) {
protections.push('edit=' + ctx.protectEdit.level);
Line 4,151 ⟶ 4,633:
}
 
varconst query = {
action: 'protect',
title: pageTitle,
Line 4,166 ⟶ 4,648:
}
 
if (ctx.watchlistExpiryfnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
Line 4,179 ⟶ 4,661:
 
var fnProcessStabilize = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('stabilize')) {
Line 4,185 ⟶ 4,667:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.stabilizeApi.getResponse().query;
 
// 'stabilize' as a verb not necessarily well understood
Line 4,193 ⟶ 4,675:
 
token = response.tokens.csrftoken;
pageTitleconst page = response.pages[0].title;
pageTitle = page.title;
// Doesn't support watchlist expiry [[phab:T263336]]
// ctx.watched = page.watchlistexpiry || page.watched;
}
 
varconst query = {
action: 'stabilize',
title: pageTitle,
Line 4,204 ⟶ 4,689:
// tags: ctx.changeTags, // flaggedrevs tag support: [[phab:T247721]]
reason: ctx.editSummary,
watchlist: ctx.watchlistOption, // Doesn't support watchlist expiry [[phab:T263336]]
format: 'json'
};
 
/* Doesn't support watchlist expiry [[phab:T263336]]
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
*/
 
ctx.stabilizeProcessApi = new Morebits.wiki.api('configuring stabilization settings...', query, ctx.onStabilizeSuccess, ctx.statusElement, ctx.onStabilizeFailure);
Line 4,214 ⟶ 4,705:
 
var sleep = function(milliseconds) {
varconst deferred = $.Deferred();
setTimeout(deferred.resolve, milliseconds);
return deferred;
Line 4,227 ⟶ 4,718:
* - Need to reset all parameters once done (e.g. edit summary, move destination, etc.)
*/
 
 
/* **************** Morebits.wiki.preview **************** */
Line 4,255 ⟶ 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();
 
varconst statusspan = document.createElement('span');
previewbox.appendChild(statusspan);
Morebits.status.init(statusspan);
 
varconst query = {
action: 'parse',
prop: ['text', 'modules'],
pst: 'true', // PST = pre-save transform; this makes substitution work properly
preview: true,
text: wikitext,
title: pageTitle || mw.config.get('wgPageName'),
disablelimitreport: true,
disableeditsection: true,
format: 'json'
};
Line 4,276 ⟶ 4,769:
query.sectiontitle = sectionTitle;
}
varconst renderApi = new Morebits.wiki.api('loading...', query, fnRenderSuccess, new Morebits.status('Preview'));
return renderApi.post();
};
 
var fnRenderSuccess = function(apiobj) {
varconst htmlresponse = apiobj.getResponse().parse.text;
const html = response.parse.text;
if (!html) {
apiobj.statelem.error('failed to retrieve preview, or template was blanked');
Line 4,287 ⟶ 4,781:
}
previewbox.innerHTML = html;
mw.loader.load(response.parse.modulestyles);
$(previewbox).find('a').attr('target', '_blank'); // this makes links open in new tab
mw.loader.load(response.parse.modules);
 
// this makes links open in new tab
$(previewbox).find('a').attr('target', '_blank');
};
 
Line 4,295 ⟶ 4,793:
};
};
 
 
/* **************** Morebits.wikitext **************** */
Line 4,313 ⟶ 4,810:
* @param {string} text - Wikitext containing a template.
* @param {number} [start=0] - Index noting where in the text the template begins.
* @returnsreturn {objectObject} `{name: templateName, parameters: {key: value}}`.
*/
Morebits.wikitext.parseTemplate = function(text, start) {
start = start || 0;
 
varconst countlevel = -1[]; // NumberTrack of parametershow deep we are ({{, {{{, or found[[)
varlet count = -1; // Number of parameters found
let unnamed = 0; // Keep track of what number an unnamed parameter should receive
varlet levelequals = -1; // HowAfter manyfinding levels"=" deepbefore ofa templateparameter, codethe we'reindex; inotherwise, 0-based1
let current = '';
var equals = -1; // After finding "=" before a parameter, the index; otherwise, -1
varconst currentresult = '';{
var result = {
name: '',
parameters: {}
};
varlet key, value;
 
/**
Line 4,335 ⟶ 4,832:
* parameter and we need to remove the trailing `}}`.
*/
varfunction findParam = function(final) {
// Nothing found yet, this must be the template name
if (count === -1) {
result.name = current.substringslice(2).trim();
++count;
} else {
Line 4,350 ⟶ 4,847:
} else {
// No equals, so it must be unnamed; no trim since whitespace allowed
varconst param = final ? current.substring(equals + 1, current.length - 2) : current;
if (param) {
result.parameters[++unnamed] = param;
Line 4,357 ⟶ 4,854:
}
}
};
 
for (varlet i = start; i < text.length; ++i) {
varconst test3 = text.substr(i, 3);
if (test3 === '{{{' || (test3 === '}}}' && level[level.length - 1] === 3)) {
current += test3;
i += 2;
if (test3 === '}}}{{{') ? --level : ++level;{
level.push(3);
} else {
level.pop();
}
continue;
}
varconst test2 = text.substr(i, 2);
// Entering a template (or link)
if (test2 === '{{' || test2 === '[[') {
current += test2;
++i;
if (test2 === '{{') {
++level;
continue level.push(2);
} else {
level.push('wl');
// Leaving a link
}
if (test2 === ']]') {
current += ']]';
++i;
--level;
continue;
}
// Either leaving a templatelink or an internal template/parser function
if ((test2 === '}}' && level[level.length - 1] === 2) {||
(test2 === ']]' && level[level.length - 1] === 'wl')) {
// Regardless, decrement the level
current += test2;
++i;
--level.pop();
 
// Find the final parameter if this really is the end
if (test2 === '}}' && level.length === -10) {
findParam(true);
break;
Line 4,397 ⟶ 4,895:
}
 
if (text.charAt(i) === '|' && level.length === 01) {
// Another pipe found, toplevel, so parameter coming up!
findParam();
current = '';
} else if (equals === -1 && text.charAt(i) === '=' && level.length === 01) {
// Equals found, toplevel
equals = current.length;
Line 4,430 ⟶ 4,928:
/**
* Removes links to `link_target` from the page text.
* Files and Categories become links with a leading colon
* (e.g. [[:File:Test.png]]); otherwise, allow for an optional leading
* colon (e.g. [[:User:Test]]).
*
* @param {string} link_target
* @return {Morebits.wikitext.page}
*
* @returns {Morebits.wikitext.page}
*/
removeLink: function(link_target) {
const mwTitle = mw.Title.newFromText(link_target);
var first_char = link_target.substr(0, 1);
const namespaceID = mwTitle.getNamespaceId();
var link_re_string = '[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + Morebits.string.escapeRegExp(link_target.substr(1));
const title = mwTitle.getMainText();
 
let link_regex_string = '';
if (namespaceID !== 0) {
link_regex_string = Morebits.namespaceRegex(namespaceID) + ':';
}
link_regex_string += Morebits.pageNameRegex(title);
 
// For most namespaces, unlink both [[User:Test]] and [[:User:Test]]
var special_ns_re = /^(?:[Ff]ile|[Ii]mage|[Cc]ategory):/;
// For files and categories, only unlink [[:Category:Test]]. Do not unlink [[Category:Test]]
var colon = special_ns_re.test(link_target) ? ':' : ':?';
const isFileOrCategory = [6, 14].includes(namespaceID);
const colon = isFileOrCategory ? ':' : ':?';
 
varconst link_simple_resimple_link_regex = new RegExp('\\[\\[' + colon + '(' + link_re_stringlink_regex_string + ')\\]\\]', 'g');
varconst link_named_repiped_link_regex = new RegExp('\\[\\[' + colon + link_re_stringlink_regex_string + '\\|(.+?)\\]\\]', 'g');
this.text = this.text.replace(link_simple_resimple_link_regex, '$1').replace(link_named_repiped_link_regex, '$1');
return this;
},
Line 4,456 ⟶ 4,959:
*
* @param {string} image - Image name without `File:` prefix.
* @param {string} [reason] - Reason to be included in comment, alongside the commented-out image.
* @return {Morebits.wikitext.page}
*
* @returns {Morebits.wikitext.page}
*/
commentOutImage: function(image, reason) {
varconst unbinder = new Morebits.unbinder(this.text);
unbinder.unbind('<!--', '-->');
 
reason = reason ? reason + ': ' : '';
const image_re_string = Morebits.pageNameRegex(image);
var first_char = image.substr(0, 1);
var image_re_string = '[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + Morebits.string.escapeRegExp(image.substr(1));
 
// Check for normal image links, i.e. [[File:Foobar.png|...]]
// Will eat the whole link
varconst links_re = new RegExp('\\[\\[' + Morebits.namespaceRegex(?:[Ii]mage|[Ff]ile6) + ':\\s*' + image_re_string + '\\s*[\\|(?:\\]\\])]');
varconst allLinks = Morebits.array.uniq(Morebits.string.splitWeightedByKeys(unbinder.content, '[[', ']]'));
for (varlet i = 0; i < allLinks.length; ++i) {
if (links_re.test(allLinks[i])) {
varconst replacement = '<!-- ' + reason + allLinks[i] + ' -->';
unbinder.content = unbinder.content.replace(allLinks[i], replacement, 'g');
// unbind the newly created comments
unbinder.unbind('<!--', '-->');
}
}
// 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.
varconst gallery_image_re = new RegExp('(^\\s*' + Morebits.namespaceRegex(?:[Ii]mage|[Ff]ile6) + ':\\s*' + image_re_string + '\\s*(?:\\|.*?$|$))', 'mg');
unbinder.content = unbinder.content.replace(gallery_image_re, '<!-- ' + reason + '$1 -->');
 
Line 4,490 ⟶ 4,991:
unbinder.unbind('<!--', '-->');
 
// Check free image usages, for example as template arguments, might have the File: prefix excluded, but must be preceededpreceded by an |
// Will only eat the image name and the preceedingpreceding bar and an eventual named parameter
varconst free_image_re = new RegExp('(\\|\\s*(?:[\\w\\s]+\\=)?\\s*(?:' + Morebits.namespaceRegex(?:[Ii]mage|[Ff]ile6) + ':\\s*)?' + image_re_string + ')', 'mg');
unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->');
// Rebind the content now, we are done!
Line 4,504 ⟶ 5,005:
* @param {string} image - Image name without File: prefix.
* @param {string} data - The display options.
* @return {Morebits.wikitext.page}
*
* @returns {Morebits.wikitext.page}
*/
addToImageComment: function(image, data) {
const image_re_string = Morebits.pageNameRegex(image);
var first_char = image.substr(0, 1);
const links_re = new RegExp('\\[\\[' + Morebits.namespaceRegex(6) + ':\\s*' + image_re_string + '\\s*[\\|(?:\\]\\])]');
var first_char_regex = Morebits.string.escapeRegExp(first_char);
const allLinks = Morebits.string.splitWeightedByKeys(this.text, '[[', ']]');
if (first_char.toUpperCase() !== first_char.toLowerCase()) {
for (let i = 0; i < allLinks.length; ++i) {
first_char_regex = '[' + Morebits.string.escapeRegExp(first_char.toUpperCase()) + Morebits.string.escapeRegExp(first_char.toLowerCase()) + ']';
}
var image_re_string = '(?:[Ii]mage|[Ff]ile):\\s*' + first_char_regex + Morebits.string.escapeRegExp(image.substr(1));
var links_re = new RegExp('\\[\\[' + image_re_string);
var allLinks = Morebits.array.uniq(Morebits.string.splitWeightedByKeys(this.text, '[[', ']]'));
for (var i = 0; i < allLinks.length; ++i) {
if (links_re.test(allLinks[i])) {
varlet replacement = allLinks[i];
// just put it at the end?
replacement = replacement.replace(/\]\]$/, '|' + data + ']]');
this.text = this.text.replace(allLinks[i], replacement, 'g');
}
}
varconst gallery_re = new RegExp('^(\\s*' + image_re_string + '.*?)\\|?(.*?)$', 'mg');
varconst newtext = '$1|$2 ' + data;
this.text = this.text.replace(gallery_re, newtext);
return this;
Line 4,531 ⟶ 5,026:
 
/**
* RemovesRemove all transclusions of a template from page text.
*
* @param {string} template - Page name whose transclusions are to be removed,
* include namespace prefix only if not in template namespace.
* @return {Morebits.wikitext.page}
*
* @returns {Morebits.wikitext.page}
*/
removeTemplate: function(template) {
const template_re_string = Morebits.pageNameRegex(template);
var first_char = template.substr(0, 1);
const links_re = new RegExp('\\{\\{(?:' + Morebits.namespaceRegex(10) + ':)?\\s*' + template_re_string + '\\s*[\\|(?:\\}\\})]');
var template_re_string = '(?:[Tt]emplate:)?\\s*[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + Morebits.string.escapeRegExp(template.substr(1));
const allTemplates = Morebits.string.splitWeightedByKeys(this.text, '{{', '}}', [ '{{{', '}}}' ]);
var links_re = new RegExp('\\{\\{' + template_re_string);
for (let i = 0; i < allTemplates.length; ++i) {
var allTemplates = Morebits.array.uniq(Morebits.string.splitWeightedByKeys(this.text, '{{', '}}', [ '{{{', '}}}' ]));
for (var i = 0; i < allTemplates.length; ++i) {
if (links_re.test(allTemplates[i])) {
this.text = this.text.replace(allTemplates[i], '', 'g');
}
}
Line 4,559 ⟶ 5,052:
* @param {string|string[]} regex - Templates after which to insert tag,
* given as either as a (regex-valid) string or an array to be joined by pipes.
* @param {string} [flags=i] - Regex flags to apply. `''` to provide no flags;
* other falsey values will default to `i`.
* @param {string|string[]} [preRegex] - Optional regex string or array to match
* before any template matches (i.e. before `{{`), such as html comments.
* @returnsreturn {Morebits.wikitext.page}
* @throws If no tag or regex are provided.
*/
insertAfterTemplates: function(tag, regex, flags, preRegex) {
Line 4,578 ⟶ 5,071:
}
 
flagsif =(typeof flags ||!== 'istring';) {
flags = 'i';
}
 
if (!preRegex || !preRegex.length) {
Line 4,585 ⟶ 5,080:
preRegex = preRegex.join('|');
}
 
 
// Regex is extra complicated to allow for templates with
Line 4,620 ⟶ 5,114:
* Get the manipulated wikitext.
*
* @returnsreturn {string}
*/
getText: function() {
Line 4,626 ⟶ 5,120:
}
};
 
 
/* *********** Morebits.userspaceLogger ************ */
Line 4,660 ⟶ 5,153:
* @param {string} logText - Doesn't include leading `#` or `*`.
* @param {string} summaryText - Edit summary.
* @return {jQuery.Promise}
*/
this.log = function(logText, summaryText) {
const def = $.Deferred();
if (!logText) {
return def.reject();
}
varconst page = new Morebits.wiki.page('User:' + mw.config.get('wgUserName') + '/' + logPageName,
'Adding entry to userspace log'); // make this '... to ' + logPageName ?
return page.load(function(pageobj) => {
// add blurb if log page doesn't exist or is blank
varlet text = pageobj.getPageText() || this.initialText;
 
// create monthly header if it doesn't exist already
varconst date = new Morebits.date(pageobj.getLoadTime());
if (!date.monthHeaderRegex().exec(text)) {
text += '\n\n' + date.monthHeader(this.headerLevel);
Line 4,681 ⟶ 5,176:
pageobj.setChangeTags(this.changeTags);
pageobj.setCreateOption('recreate');
pageobj.save(def.resolve, def.reject);
}.bind(this));
return def;
};
};
 
 
/* **************** Morebits.status **************** */
Line 4,704 ⟶ 5,199:
Morebits.status = function Status(text, stat, type) {
this.textRaw = text;
this.text = thisMorebits.codifycreateHtml(text);
this.type = type || 'status';
this.generate();
Line 4,741 ⟶ 5,236:
Morebits.status.errorEvent = handler;
} else {
throw new Error('Morebits.status.onError: handler is not a function');
}
};
Line 4,769 ⟶ 5,264:
this.linked = false;
}
},
 
/**
* Create a document fragment with the status text, parsing as HTML.
* Runs upon construction for text (part before colon) and upon
* render/update for status (part after colon).
*
* @param {(string|Element|Array)} obj
* @returns {DocumentFragment}
*/
codify: function(obj) {
if (!Array.isArray(obj)) {
obj = [ obj ];
}
var result;
result = document.createDocumentFragment();
for (var i = 0; i < obj.length; ++i) {
if (obj[i] instanceof Element) {
result.appendChild(obj[i]);
} else {
$.parseHTML(obj[i]).forEach(function(elem) {
result.appendChild(elem);
});
}
}
return result;
 
},
 
Line 4,803 ⟶ 5,271:
* @param {string} status - Part of status message after colon.
* @param {string} type - 'status' (blue), 'info' (green), 'warn'
* (red), or 'error' (bold red). FIXME TODO possible options
*/
update: function(status, type) {
this.statRaw = status;
this.stat = thisMorebits.codifycreateHtml(status);
if (type) {
this.type = type;
Line 4,857 ⟶ 5,325:
}
};
/**
* @memberof Morebits.status
* @param {string} text - Before colon
* @param {string} status - After colon
* @return {Morebits.status} - `status`-type (blue)
*/
Morebits.status.status = function(text, status) {
return new Morebits.status(text, status);
};
/**
* @memberof Morebits.status
* @param {string} text - Before colon
* @param {string} status - After colon
* @return {Morebits.status} - `info`-type (green)
*/
Morebits.status.info = function(text, status) {
return new Morebits.status(text, status, 'info');
};
/**
 
* @memberof Morebits.status
* @param {string} text - Before colon
* @param {string} status - After colon
* @return {Morebits.status} - `warn`-type (red)
*/
Morebits.status.warn = function(text, status) {
return new Morebits.status(text, status, 'warn');
};
/**
 
* @memberof Morebits.status
* @param {string} text - Before colon
* @param {string} status - After colon
* @return {Morebits.status} - `error`-type (bold red)
*/
Morebits.status.error = function(text, status) {
return new Morebits.status(text, status, 'error');
Line 4,877 ⟶ 5,370:
*/
Morebits.status.actionCompleted = function(text) {
varconst node = document.createElement('div');
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 4,894 ⟶ 5,387:
*/
Morebits.status.printUserText = function(comments, message) {
varconst p = document.createElement('p');
p.innerHTML = message;
varconst div = document.createElement('div');
div.className = 'toccoloursmorebits-usertext';
div.style.marginTop = '0';
div.style.whiteSpace = 'pre-wrap';
Line 4,904 ⟶ 5,397:
Morebits.status.root.appendChild(p);
};
 
 
 
/**
Line 4,913 ⟶ 5,404:
* @param {string} content - Text content.
* @param {string} [color] - Font color.
* @returnsreturn {HTMLElement}
*/
Morebits.htmlNode = function (type, content, color) {
varconst node = document.createElement(type);
if (color) {
node.style.color = color;
Line 4,923 ⟶ 5,414:
return node;
};
 
 
 
/**
Line 4,935 ⟶ 5,424:
*/
Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) {
varlet lastCheckbox = null;
 
function clickHandler(event) {
varconst thisCb = this;
if (event.shiftKey && lastCheckbox !== null) {
varconst $cbs = $(jQuerySelector, jQueryContext); // can't cache them, obviously, if we want to support resortingre-sorting
varlet index = -1, lastIndex = -1, i;
for (i = 0; i < $cbs.length; i++) {
if ($cbs[i] === thisCb) {
index = i;
if (lastIndex > -1) {
Line 4,949 ⟶ 5,438:
}
}
if ($cbs[i] === lastCheckbox) {
lastIndex = i;
if (index > -1) {
Line 4,959 ⟶ 5,448:
if (index > -1 && lastIndex > -1) {
// inspired by wikibits
varconst endState = thisCb.checked;
varlet start, finish;
if (index < lastIndex) {
start = index + 1;
Line 4,970 ⟶ 5,459:
 
for (i = start; i <= finish; i++) {
if ($cbs[i].checked !== endState) {
$cbs[i].click();
}
}
Line 4,980 ⟶ 5,469:
}
 
$(jQuerySelector, jQueryContext).clickon('click', clickHandler);
};
 
 
 
/* **************** Morebits.batchOperation **************** */
Line 5,001 ⟶ 5,488:
* `run(worker, postFinish)`: Runs the callback `worker` for each page in the
* list. The callback must call `workerSuccess` when succeeding, or
* `workerFailure` when failing. If using {@link Morebits.wiki.api} or {@link
* {@link Morebits.wiki.page}, this is easily done by passing these two functions as
* functions as parameters to the methods on those objects: for instance,
* `page.save(batchOp.workerSuccess, batchOp.workerFailure)`. Make sure the
* methods are called directly if special success/failure cases arise. If you
Line 5,024 ⟶ 5,511:
*/
Morebits.batchOperation = function(currentAction) {
varconst ctx = {
// backing fields for public properties
pageList: null,
Line 5,033 ⟶ 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,098 ⟶ 5,585:
ctx.pageChunks = [];
 
varconst total = ctx.pageList.length;
if (!total) {
ctx.statusElement.info(msg('batch-no-pages', 'no pages specified'));
ctx.running = false;
if (ctx.postFinish) {
Line 5,118 ⟶ 5,605:
 
/**
* To be called by worker before it terminates succesfullysuccessfully.
*
* @param {(Morebits.wiki.page|Morebits.wiki.api|string)} arg -
Line 5,127 ⟶ 5,614:
*/
this.workerSuccess = function(arg) {
 
var createPageLink = function(pageName) {
var link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(pageName));
link.appendChild(document.createTextNode(pageName));
return link;
};
 
if (arg instanceof Morebits.wiki.api || arg instanceof Morebits.wiki.page) {
// update or remove status line
varconst statelem = arg.getStatusElement();
if (ctx.options.preserveIndividualStatusLines) {
if (arg.getPageName || arg.pageName || (arg.query && arg.query.title)) {
// we know the page title - display a relevant message
varconst pageName = arg.getPageName ? arg.getPageName() : arg.pageName || arg.query.title;
statelem.info([msg('batch-done-page', pageName, 'completed ([[', createPageLink(+ pageName), + ']])']));
} else {
// we don't know the page title - just display a generic message
statelem.info(msg('done', 'done'));
}
} else {
Line 5,153 ⟶ 5,633:
 
} else if (typeof arg === 'string' && ctx.options.preserveIndividualStatusLines) {
new Morebits.status(arg, [msg('batch-done (-page', createPageLink(arg), ')completed ([[' + arg + ']])'));
}
 
Line 5,166 ⟶ 5,646:
// private functions
 
varconst thisProxy = this;
 
var fnStartNewChunk = function() {
varconst chunk = ctx.pageChunks[++ctx.currentChunkIndex];
if (!chunk) {
return; // done! yay
}
 
// start workers for the current chunk
ctx.countStarted += chunk.length;
chunk.forEach(function(page) => {
ctx.worker(page, thisProxy);
});
Line 5,185 ⟶ 5,665:
 
// update overall status line
varconst total = ctx.pageList.length;
if (ctx.countFinished < total) {
ctxconst progress = Math.statusElement.status(parseIntround(100 * ctx.countFinished / total, 10) + '%');
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,196 ⟶ 5,677:
}
} else if (ctx.countFinished === total) {
varconst statusString = msg('batch-progress', ctx.countFinishedSuccess, ctx.countFinished, 'Done (' + ctx.countFinishedSuccess +
'/' + ctx.countFinished + ' actions completed successfully)');
if (ctx.countFinishedSuccess < ctx.countFinished) {
ctx.statusElement.warn(statusString);
Line 5,220 ⟶ 5,701:
/**
* Given a set of asynchronous functions to run along with their dependencies,
* figurerun outthem in an efficient sequence of running them so that multiple functions
* that don't depend on each other are triggered simultaneously. Where
* dependencies exist, it ensures that the dependency functions finish running
Line 5,229 ⟶ 5,710:
* @class
*/
Morebits.taskManager = function(context) {
this.taskDependencyMap = new Map();
this.failureCallbackMap = new Map();
this.deferreds = new Map();
this.context = context || window;
this.allDeferreds = []; // Hack: IE doesn't support Map.prototype.values
 
/**
Line 5,242 ⟶ 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 || (() => {}));
var deferred = $.Deferred();
const deferred = $.Deferred();
this.deferreds.set(func, deferred);
this.allDeferreds.push(deferred);
};
 
Line 5,253 ⟶ 5,737:
* Run all the tasks. Multiple tasks may be run at once.
*
* @returnsreturn {promisejQuery.Promise} - AResolved jQueryif promiseall objecttasks that is resolved orsucceed, rejected with the api objectotherwise.
*/
this.execute = function() {
varconst self = this; // proxy for `this` for use inside functions where `this` is something else
this.taskDependencyMap.forEach(function(deps, task) => {
varconst dependencyPromisesArray = deps.map(function(dep) {=> self.deferreds.get(dep));
$.when.apply(self.context, dependencyPromisesArray).then(function() {
return self.deferreds.get(dep);
const result = task.apply(self.context, arguments);
});
if (result === undefined) { // maybe the function threw, or it didn't return anything
$.when.apply(null, dependencyPromisesArray).then(function() {
mw.log.error('Morebits.taskManager: task returned undefined');
task.apply(null, arguments).then(function() {
self.deferreds.get(task).resolvereject.apply(nullself.context, arguments);
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.allDeferredsdeferreds.values()]); // resolved when everything is done!
};
 
Line 5,277 ⟶ 5,770:
* @memberof Morebits
* @class
* @requires jqueryjQuery.ui.dialog
* @param {number} width
* @param {number} height - The maximum allowable height for the content area.
*/
Morebits.simpleWindow = function SimpleWindow(width, height) {
varconst content = document.createElement('div');
this.content = content;
content.className = 'morebits-dialog-content';
Line 5,293 ⟶ 5,786:
buttons: { 'Placeholder button': function() {} },
dialogClass: 'morebits-dialog',
width: Math.min(parseInt(window.innerWidth, 10), parseInt(width ? width :|| 800, 10)),
// give jQuery the given height value (which represents the anticipated height of the dialog) here, so
// it can position the dialog appropriately
Line 5,309 ⟶ 5,802:
}
},
resizeEndresizeStop: function() {
this.scrollbox = null;
},
Line 5,320 ⟶ 5,813:
});
 
varconst $widget = $(this.content).dialog('widget');
 
// delete the placeholder button (it's only there so the buttonpane gets created)
$widget.find('button').each(function(key, value) => {
value.parentNode.removeChild(value);
});
 
// add container for the buttons we add, and the footer links (if any)
varconst buttonspan = document.createElement('span');
buttonspan.className = 'morebits-dialog-buttons';
varconst linksspan = document.createElement('span');
linksspan.className = 'morebits-dialog-footerlinks';
$widget.find('.ui-dialog-buttonpane').append(buttonspan, linksspan);
Line 5,336 ⟶ 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,347 ⟶ 5,843:
* Focuses the dialog. This might work, or on the contrary, it might not.
*
* @returnsreturn {Morebits.simpleWindow}
*/
focus: function() {
Line 5,359 ⟶ 5,855:
*
* @param {event} [event]
* @returnsreturn {Morebits.simpleWindow}
*/
close: function(event) {
Line 5,373 ⟶ 5,869:
* might work, but it is not guaranteed.
*
* @returnsreturn {Morebits.simpleWindow}
*/
display: function() {
if (this.scriptName) {
varconst $widget = $(this.content).dialog('widget');
$widget.find('.morebits-dialog-scriptname').remove();
varconst scriptnamespan = document.createElement('span');
scriptnamespan.className = 'morebits-dialog-scriptname';
scriptnamespan.textContent = this.scriptName + ' \u00B7 '; // U+00B7 MIDDLE DOT = &middot;
$widget.find('.ui-dialog-title').prepend(scriptnamespan);
}
 
varconst dialog = $(this.content).dialog('open');
if (window.setupTooltips && window.pg && window.pg.re && window.pg.re.diff) { // tie in with NAVPOP
dialog.parent()[0].ranSetupTooltipsAlready = false;
window.setupTooltips(dialog.parent()[0]);
}
this.setHeight(this.height); // init height algorithm
return this;
},
Line 5,398 ⟶ 5,894:
*
* @param {string} title
* @returnsreturn {Morebits.simpleWindow}
*/
setTitle: function(title) {
Line 5,410 ⟶ 5,906:
*
* @param {string} name
* @returnsreturn {Morebits.simpleWindow}
*/
setScriptName: function(name) {
Line 5,421 ⟶ 5,917:
*
* @param {number} width
* @returnsreturn {Morebits.simpleWindow}
*/
setWidth: function(width) {
Line 5,433 ⟶ 5,929:
*
* @param {number} height
* @returnsreturn {Morebits.simpleWindow}
*/
setHeight: function(height) {
Line 5,459 ⟶ 5,955:
*
* @param {HTMLElement} content
* @returnsreturn {Morebits.simpleWindow}
*/
setContent: function(content) {
Line 5,471 ⟶ 5,967:
*
* @param {HTMLElement} content
* @returnsreturn {Morebits.simpleWindow}
*/
addContent: function(content) {
Line 5,477 ⟶ 5,973:
 
// look for submit buttons in the content, hide them, and add a proxy button to the button pane
varconst thisproxy = this;
$(this.content).find('input[type="submit"], button[type="submit"]').each(function(key, value) => {
value.style.display = 'none';
varconst button = document.createElement('button');
 
button.textContent = value.hasAttribute('value') ? value.getAttribute('value') : value.textContent ? value.textContent : 'Submit Query';
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', function() => {
value.click();
}, false);
Line 5,493 ⟶ 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'); // used by CSS
}
return this;
Line 5,501 ⟶ 6,005:
* Removes all contents from the dialog, barring any footer links.
*
* @returnsreturn {Morebits.simpleWindow}
*/
purgeContent: function() {
Line 5,523 ⟶ 6,027:
* @param {string} wikiPage - Link target.
* @param {boolean} [prep=false] - Set true to prepend rather than append.
* @returnsreturn {Morebits.simpleWindow}
*/
addFooterLink: function(text, wikiPage, prep) {
varconst $footerlinks = $(this.content).dialog('widget').find('.morebits-dialog-footerlinks');
if (this.hasFooterLinks) {
varconst bullet = document.createElement('span');
bullet.textContent = msg('bullet-separator', ' \u2022 '); // U+2022 BULLET
if (prep) {
$footerlinks.prepend(bullet);
Line 5,536 ⟶ 6,040:
}
}
varconst link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(wikiPage));
link.setAttribute('title', wikiPage);
Line 5,557 ⟶ 6,061:
* @param {boolean} [modal=false] - If set to true, other items on the
* page will be disabled, i.e., cannot be interacted with.
* @returnsreturn {Morebits.simpleWindow}
*/
setModality: function(modal) {
Line 5,580 ⟶ 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;
 
}());
}(window, document, jQuery)); // End wrap with anonymous function
 
 
/**
Line 5,593 ⟶ 6,110:
*/
 
if (typeof arguments === 'undefined') { // typeof is here for a reason...
/* global Morebits */
window.SimpleWindow = Morebits.simpleWindow;