MediaWiki:Gadget-morebits.js: Difference between revisions
Content deleted Content added
MusikAnimal (talk | contribs) Repo at 49207b0: Revert "morebits.date: Don't import methods that collide with PageTriage (T268513)" (#1619); fix handling of hard errors (#1651) |
Repo at ac3c1e3: replace es-x/no-array-prototype-includes with unicorn/prefer-includes (#2125) |
||
(10 intermediate revisions by 3 users not shown) | |||
Line 34:
*/
(function() {
/** @lends Morebits */
window.Morebits = Morebits;
/**
Line 50 ⟶ 49:
* Examples:
* Use jquery-i18n:
*
* Use banana-i18n or orange-i18n:
*
*
*
* @param {Object} parser
*/
Line 64:
/**
* @private
* @
*/
getMessage: function () {
// 1st arg: message name
// 2nd to (n-1)th arg: message parameters
// nth arg: legacy English fallback
if (!Morebits.i18n.parser) {
return fallback;
Line 78:
// i18n libraries are generally invoked with variable number of arguments
// as msg(msgName, ...parameters)
// if no i18n message exists, i18n libraries generally give back the message name
if (i18nMessage === msgName) {
Line 88:
// shortcut
/**
Line 106 ⟶ 105:
* in the format [year, month, date, hour, minute, second]
* which can be passed to Date.UTC()
*
* @param {string} str
* @
*/
signatureTimestampFormat: function (str) {
// HH:mm, DD Month YYYY (UTC)
if (!match) {
return null;
}
if (month === -1) {
return null;
Line 124:
}
};
/**
Line 130 ⟶ 129:
*
* @param {string} group - e.g. `sysop`, `extendedconfirmed`, etc.
* @
*/
Morebits.userIsInGroup = function (group) {
return mw.config.get('wgUserGroups').
};
/**
* Hardcodes whether the user is a sysop, used a lot.
*
* @type {boolean}
Line 151:
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @
*/
Morebits.sanitizeIPv6 = function (address) {
Line 163:
* detect Module:RfD, with the same failure points.
*
* @
*/
Morebits.isPageRedirect = function() {
Line 176:
*/
Morebits.pageNameNorm = mw.config.get('wgPageName').replace(/_/g, ' ');
/**
Line 184 ⟶ 183:
*
* @param {string} pageName - Page name without namespace.
* @
*/
Morebits.pageNameRegex = function(pageName) {
Line 190 ⟶ 189:
return '';
}
remainder = Morebits.string.escapeRegExp(pageName.slice(1));
if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) {
Line 202 ⟶ 201:
* Wikilink syntax (`[[...]]`) is transformed into HTML anchor.
* Used in Morebits.quickForm and Morebits.status
*
* @internal
* @param {string|Node|(string|Node)[]} input
* @
*/
Morebits.createHtml = function(input) {
if (!input) {
return fragment;
Line 214:
input = [ input ];
}
for (
if (input[i] instanceof Node) {
fragment.appendChild(input[i]);
} else {
$.parseHTML(Morebits.createHtml.renderWikilinks(input[i])).forEach(
fragment.appendChild(node);
});
Line 228:
/**
* Converts wikilinks to HTML anchor tags.
*
* @param text
* @
*/
Morebits.createHtml.renderWikilinks = function (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,
if (!target) {
target = text;
Line 260 ⟶ 261:
* // returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])'
* Morebits.namespaceRegex([6])
* @
*/
Morebits.namespaceRegex = function(namespaces) {
Line 266 ⟶ 267:
namespaces = [namespaces];
}
let regex; $.each(mw.config.get('wgNamespaceIds'),
if (namespaces.
// Namespaces are completely agnostic as to case,
// and a regex string is more useful/compatible than a RegExp object,
// so we accept any casing for any letter.
aliases.push(name.split('').map(
}
});
Line 290:
return regex;
};
/* **************** Morebits.quickForm **************** */
Line 310 ⟶ 309:
*
* @memberof Morebits.quickForm
* @
*/
Morebits.quickForm.prototype.render = function QuickFormRender() {
ret.names = {};
return ret;
Line 324 ⟶ 323:
* @param {(object|Morebits.quickForm.element)} data - A quickform element, or the object with which
* a quickform element is constructed.
* @
*/
Morebits.quickForm.prototype.append = function QuickFormAppend(data) {
Line 354 ⟶ 353:
* - 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 372 ⟶ 371:
* - `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`, `
*
* @memberof Morebits.quickForm
* @class
* @param {
* specify one of the available types from the index above, as well as any
* relevant and available attributes.
Line 404 ⟶ 403:
* @param {Morebits.quickForm.element} data - A quickForm element or the object required to
* create the quickForm element.
* @
*/
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) {
if (data instanceof Morebits.quickForm.element) {
child = data;
Line 422 ⟶ 421:
*
* @memberof Morebits.quickForm.element
* @
*/
Morebits.quickForm.element.prototype.render = function QuickFormElementRender(internal_subgroup_id) {
for (
// do not pass internal_subgroup_id to recursive calls
currentNode[1].appendChild(this.childs[i].render());
Line 433 ⟶ 432:
return currentNode[0];
};
/** @memberof Morebits.quickForm.element */
Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute(data, in_id) {
if (data.adminonly && !Morebits.userIsSysop) {
// hell hack alpha
Line 446 ⟶ 444:
}
switch (data.type) {
case 'form':
Line 460 ⟶ 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 546 ⟶ 545:
if (data.list) {
for (i = 0; i < data.list.length; ++i) {
current = data.list[i];
var cur_div;
Line 593 ⟶ 592:
var event;
if (current.subgroup) {
if (!Array.isArray(tmpgroup)) {
Line 603 ⟶ 602:
id: id + '_' + i + '_subgroup'
});
$.each(tmpgroup,
if (!newEl.type) {
newEl.type = data.type;
Line 612 ⟶ 611:
});
subgroup.className = 'quickformSubgroup';
subnode.subgroup = subgroup;
Line 621 ⟶ 620:
e.target.parentNode.appendChild(e.target.subgroup);
if (e.target.type === 'radio') {
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 638 ⟶ 637:
event = function(e) {
if (e.target.checked) {
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 679 ⟶ 678:
} else {
subnode.setAttribute('type', 'number');
['min', 'max', 'step', 'list'].forEach(
if (data[att]) {
subnode.setAttribute(att, data[att]);
Line 686 ⟶ 685:
}
['value', 'size', 'placeholder', 'maxlength'].forEach(
if (data[att]) {
subnode.setAttribute(att, data[att]);
}
});
['disabled', 'required', 'readonly'].forEach(
if (data[att]) {
subnode.setAttribute(att, att);
Line 717 ⟶ 716:
disabled: min >= max,
event: function(e) {
e.target.area.appendChild(new_node.render());
Line 731 ⟶ 730:
var sublist = {
type: '
remove: false,
maxlength: data.maxlength,
event: data.event,
inputs: data.inputs || [{
// compatibility
label: data.sublabel || data.label,
name: data.name,
value: data.value,
size: data.size
}]
};
for (i = 0; i < min; ++i) {
listNode.appendChild(elem.render());
}
Line 754 ⟶ 756:
moreButton.counter = 0;
break;
case '
node = document.createElement('div');
data.inputs.forEach((subdata) => {
const cell = new Morebits.quickForm.element($.extend(subdata, { type: '_dyninput_cell' }));
node.appendChild(cell.render());
});
if (data.remove) {
const remove = this.compute({
type: 'button',
label: 'remove',
event: function(e) {
const list = e.target.listnode;
const node = e.target.inputnode;
const more = e.target.morebutton;
list.removeChild(node);
--more.counter;
more.removeAttribute('disabled');
e.stopPropagation();
}
});
node.appendChild(remove[0]);
const removeButton = remove[1];
removeButton.inputnode = node;
removeButton.listnode = data.listnode;
removeButton.morebutton = data.morebutton;
}
break;
case '_dyninput_cell': // Private, similar to normal input
node = document.createElement('span');
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.appendChild(document.createTextNode(data.label));
label.setAttribute('for', id + '_input');
label.style.marginRight = '3px';
}
subnode = node.appendChild(document.createElement('input'));
subnode.setAttribute('id', id + '_input');
if (data.value) {
subnode.setAttribute('value', data.value);
Line 770 ⟶ 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 775 ⟶ 808:
if (data.maxlength) {
subnode.setAttribute('maxlength', data.maxlength);
}
if (data.required) {
subnode.setAttribute('required', 'required');
}
if (data.disabled) {
subnode.setAttribute('required', 'disabled');
}
if (data.event) {
subnode.addEventListener('keyup', data.event, false);
}
node.style.marginRight = '3px';
break;
case 'hidden':
Line 818 ⟶ 837:
}
if (data.label) {
result.className = 'quickformDescription';
result.appendChild(Morebits.createHtml(data.label));
Line 856 ⟶ 875:
if (data.label) {
label = node.appendChild(document.createElement('h5'));
labelElement.appendChild(Morebits.createHtml(data.label));
labelElement.setAttribute('for', data.id || id);
Line 917 ⟶ 936:
*
* @memberof Morebits.quickForm.element
* @requires
* @param {HTMLElement} node - The HTML element beside which a tooltip is to be generated.
* @param {
*/
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) {
tooltipButton.className = 'morebits-tooltipButton';
tooltipButton.title = data.tooltip; // Provides the content for jQuery UI
Line 932 ⟶ 951:
});
};
// Some utility methods for manipulating quickForms after their creation:
Line 943 ⟶ 961:
* @memberof Morebits.quickForm
* @param {HTMLFormElement} form
* @
*/
Morebits.quickForm.getInputData = function(form) {
for (
if (field.disabled || !field.name || !field.type ||
field.type === 'submit' || field.type === 'button') {
Line 957 ⟶ 975:
// For elements in subgroups, quickform prepends element names with
// name of the parent group followed by a period, get rid of that.
switch (field.type) {
Line 980 ⟶ 998:
case 'text': // falls through
case 'textarea':
result[fieldNameNorm] = result[fieldNameNorm] || [];
result[fieldNameNorm].push(field.value.trim());
} else {
result[fieldNameNorm] = field.value.trim();
}
break;
default: // could be select-one, date, number, email, etc
Line 991 ⟶ 1,014:
return result;
};
/**
Line 999 ⟶ 1,021:
* @param {HTMLFormElement} form
* @param {string} fieldName - The name or id of the fields.
* @
*/
Morebits.quickForm.getElements = function QuickFormGetElements(form, fieldName) {
fieldName = $.escapeSelector(fieldName); // sanitize input
if ($elements.length > 0) {
return $elements.toArray();
Line 1,019 ⟶ 1,041:
* @param {HTMLInputElement[]} elementArray - Array of checkbox or radio elements.
* @param {string} value - Value to search for.
* @
*/
Morebits.quickForm.getCheckboxOrRadio = function QuickFormGetCheckboxOrRadio(elementArray, value) {
if (found.length > 0) {
return found[0];
Line 1,037 ⟶ 1,057:
* @memberof Morebits.quickForm
* @param {HTMLElement} element
* @
*/
Morebits.quickForm.getElementContainer = function QuickFormGetElementContainer(element) {
Line 1,056 ⟶ 1,076:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.getElementLabelObject = function QuickFormGetElementLabelObject(element) {
Line 1,079 ⟶ 1,099:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.getElementLabel = function QuickFormGetElementLabel(element) {
if (!labelElement) {
Line 1,096 ⟶ 1,116:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} labelText
* @
*/
Morebits.quickForm.setElementLabel = function QuickFormSetElementLabel(element, labelText) {
if (!labelElement) {
Line 1,114 ⟶ 1,134:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} temporaryLabelText
* @
*/
Morebits.quickForm.overrideElementLabel = function QuickFormOverrideElementLabel(element, temporaryLabelText) {
Line 1,128 ⟶ 1,148:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.resetElementLabel = function QuickFormResetElementLabel(element) {
Line 1,158 ⟶ 1,178:
$(Morebits.quickForm.getElementContainer(element)).find('.morebits-tooltipButton').toggle(visibility);
};
/**
Line 1,167 ⟶ 1,185:
* Get checked items in the form.
*
* @
* @param {string} name - Find checked property of elements (i.e. a checkbox
* or a radiobutton) with the given name, or select options that have selected
Line 1,173 ⟶ 1,191:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @
* checked property set to true.
*/
HTMLFormElement.prototype.getChecked = function(name, type) {
if (!elements) {
return [];
}
if (elements instanceof HTMLSelectElement) {
for (i = 0; i < options.length; ++i) {
if (options[i].selected) {
Line 1,221 ⟶ 1,239:
* Does the same as {@link HTMLFormElement.getChecked|getChecked}, but with unchecked elements.
*
* @
* @param {string} name - Find checked property of elements (i.e. a checkbox
* or a radiobutton) with the given name, or select options that have selected
Line 1,227 ⟶ 1,245:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @
* checked property set to true.
*/
HTMLFormElement.prototype.getUnchecked = function(name, type) {
if (!elements) {
return [];
}
if (elements instanceof HTMLSelectElement) {
for (i = 0; i < options.length; ++i) {
if (!options[i].selected) {
Line 1,286 ⟶ 1,304:
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @
*/
sanitizeIPv6: function (address) {
Line 1,299 ⟶ 1,317:
address = address.toUpperCase();
// Expand zero abbreviations
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").
// If the '::' is at the beginning...
if (abbrevPos === 0) {
repeat = '0:';
Line 1,322 ⟶ 1,340:
pad = 8; // 6+2 (due to '::')
}
pad -= address.split(':').length - 1;
for (
replacement += repeat;
}
Line 1,339 ⟶ 1,357:
*
* @param {string} ip
* @
*/
isRange: function (ip) {
Line 1,350 ⟶ 1,368:
* for IPv4 and /32 for IPv6.
*
* @
* otherwise false (ranges outside the limit, single IPs, non-IPs).
*/
validCIDR: function (ip) {
if (Morebits.ip.isRange(ip)) {
if (subnet) { // Should be redundant
if (mw.util.isIPv6Address(ip, true)) {
Line 1,375 ⟶ 1,393:
*
* @param {string} ipv6 - The IPv6 address, with or without a subnet.
* @
* otherwise the (sanitized) /64 address.
*/
Line 1,382 ⟶ 1,400:
return false;
}
if (subnetMatch && parseInt(subnetMatch[1], 10) < 64) {
return false;
}
ipv6 = Morebits.ip.sanitizeIPv6(ipv6);
// eslint-disable-next-line no-useless-concat
return ipv6.replace(ip_re, '$1' + '0:0:0:0/64');
}
};
/**
Line 1,402 ⟶ 1,420:
/**
* @param {string} str
* @
*/
toUpperCaseFirstChar: function(str) {
str = str.toString();
return str.
},
/**
* @param {string} str
* @
*/
toLowerCaseFirstChar: function(str) {
str = str.toString();
return str.
},
Line 1,426 ⟶ 1,444:
* @param {string} end
* @param {(string[]|string)} [skiplist]
* @
* @throws If the `start` and `end` strings aren't of the same length.
* @throws If `skiplist` isn't an array or string
Line 1,434 ⟶ 1,452:
throw new Error('start marker and end marker must be of the same length');
}
if (!Array.isArray(skiplist)) {
if (skiplist === undefined) {
Line 1,446 ⟶ 1,464:
}
}
for (
for (
if (str.substr(i, skiplist[j].length) === skiplist[j]) {
i += skiplist[j].length - 1;
Line 1,480 ⟶ 1,498:
* @param {string} str
* @param {boolean} [addSig]
* @
*/
formatReasonText: function(str, addSig) {
// eslint-disable-next-line no-useless-concat
unbinder.unbind('<no' + 'wiki>', '</no' + 'wiki>');
unbinder.content = unbinder.content.replace(/\|/g, '{{subst:!}}');
reason = unbinder.rebind();
if (addSig) {
if (sigIndex === -1 || sigIndex !== reason.length - sig.length) {
reason += ' ' + sig;
Line 1,503 ⟶ 1,522:
*
* @param {string} str
* @
*/
formatReasonForLog: function(str) {
Line 1,523 ⟶ 1,542:
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @
*/
safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) {
Line 1,536 ⟶ 1,555:
*
* @param {string} expiry
* @
*/
isInfinity: function morebitsStringIsInfinity(expiry) {
return ['indefinite', 'infinity', 'infinite', 'never'].
},
Line 1,547 ⟶ 1,566:
*
* @param {string} text - String to be escaped.
* @
*/
escapeRegExp: function(text) {
Line 1,553 ⟶ 1,572:
}
};
/**
Line 1,566 ⟶ 1,584:
*
* @param {Array} arr
* @
* @throws When provided a non-array.
*/
uniq: function(arr) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.uniq');
}
return arr.filter(
},
Line 1,582 ⟶ 1,598:
*
* @param {Array} arr
* @
* removed; subsequent instances of those values (duplicates) remain.
* @throws When provided a non-array.
Line 1,588 ⟶ 1,604:
dups: function(arr) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.dups');
}
return arr.filter(
},
/**
Line 1,601 ⟶ 1,614:
* @param {Array} arr
* @param {number} size - Size of each chunk (except the last, which could be different).
* @
* @throws When provided a non-array.
*/
chunk: function(arr, size) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.chunk');
}
if (typeof size !== 'number' || size <= 0) { // pretty impossible to do anything :)
return [ arr ]; // we return an array consisting of this array.
}
for (
result[i] = arr.slice(i * size, (i + 1) * size);
}
Line 1,628 ⟶ 1,641:
* @namespace Morebits.select2
* @memberof Morebits
* @requires
*/
Morebits.select2 = {
Line 1,637 ⟶ 1,650:
*/
optgroupFull: function(params, data) {
if (result && params.term &&
data.text.toUpperCase().
result.children = data.children;
}
Line 1,649 ⟶ 1,662:
/** Custom matcher that matches from the beginning of words only. */
wordBeginning: function(params, data) {
if (!params.term || (result &&
new RegExp('\\b' + mw.util.escapeRegExp(params.term), 'i').test(result.text))) {
Line 1,661 ⟶ 1,674:
/** Underline matched part of options. */
highlightSearchMatches: function(data) {
if (!searchTerm || data.loading) {
return data.text;
}
if (idx < 0) {
return data.text;
Line 1,692 ⟶ 1,705:
return;
}
if (!$target.length) {
return;
}
$target = $target.prev();
$target.select2('open');
$target.data('select2').selection.$search;
// Use DOM .focus() to work around a jQuery 3.6.0 regression (https://github.com/select2/select2/issues/5993)
search[0].focus();
Line 1,705 ⟶ 1,718:
};
/**
Line 1,745 ⟶ 1,757:
throw new Error('Both prefix and postfix must be provided');
}
this.content = this.content.replace(re, Morebits.unbinder.getCallback(this));
},
Line 1,752 ⟶ 1,764:
* Restore the hidden portion of the `content` string.
*
* @
*/
rebind: function UnbinderRebind() {
content.self = this;
for (
if (Object.prototype.hasOwnProperty.call(this.history, current)) {
content = content.replace(current, this.history[current]);
Line 1,773 ⟶ 1,785:
Morebits.unbinder.getCallback = function UnbinderGetCallback(self) {
return function UnbinderCallback(match) {
self.history[current] = match;
++self.counter;
Line 1,779 ⟶ 1,791:
};
};
/* **************** Morebits.date **************** */
Line 1,792 ⟶ 1,802:
*/
Morebits.date = function() {
// Check MediaWiki formats
Line 1,799 ⟶ 1,809:
// 14-digit string will be interpreted differently.
if (args.length === 1) {
if (/^\d{14}$/.test(param)) {
// YYYYMMDDHHmmss
if (digitMatch) {
// ..... year ... month .. date ... hour .... minute ..... second
this.
}
} else if (typeof param === 'string') {
// Wikitext signature timestamp
if (dateParts) {
this.
}
}
}
if (!this.
// Try standard date
this.
}
Line 1,891 ⟶ 1,901:
Morebits.date.prototype = {
/** @
isValid: function() {
return !isNaN(this.getTime());
Line 1,898 ⟶ 1,908:
/**
* @param {(Date|Morebits.date)} date
* @
*/
isBefore: function(date) {
Line 1,905 ⟶ 1,915:
/**
* @param {(Date|Morebits.date)} date
* @
*/
isAfter: function(date) {
Line 1,911 ⟶ 1,921:
},
/** @
getUTCMonthName: function() {
return Morebits.date.localeData.months[this.getUTCMonth()];
},
/** @
getUTCMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getUTCMonth()];
},
/** @
getMonthName: function() {
return Morebits.date.localeData.months[this.getMonth()];
},
/** @
getMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getMonth()];
},
/** @
getUTCDayName: function() {
return Morebits.date.localeData.days[this.getUTCDay()];
},
/** @
getUTCDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getUTCDay()];
},
/** @
getDayName: function() {
return Morebits.date.localeData.days[this.getDay()];
},
/** @
getDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getDay()];
Line 1,951 ⟶ 1,961:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @
*/
add: function(number, unit) {
if (isNaN(num)) {
throw new Error('Invalid number "' + number + '" provided.');
}
unit = unit.toLowerCase(); // normalize
if (unitNorm) {
// No built-in week functions, so rather than build out ISO's getWeek/setWeek, just multiply
// Probably can't be used for Julian->Gregorian changeovers, etc.
if (unitNorm === 'Week') {
unitNorm = 'Date'
num *= 7; }
this['set' + unitNorm](this['get' + unitNorm]() + num);
Line 1,980 ⟶ 1,991:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @
*/
subtract: function(number, unit) {
Line 2,020 ⟶ 2,031:
* @param {(string|number)} [zone=system] - `system` (for browser-default time zone),
* `utc`, or specify a time zone as number of minutes relative to UTC.
* @
*/
format: function(formatstr, zone) {
Line 2,026 ⟶ 2,037:
return 'Invalid date'; // Put the truth out, preferable to "NaNNaNNan NaN:NaN" or whatever
}
// create a new date object that will contain the date to display as system time
if (zone === 'utc') {
Line 2,040 ⟶ 2,051:
}
len = len || 2; // Up to length of 00 + 1
return ('00' + num).toString().slice(0 - len);
};
HH: pad(h24), H: h24, hh: pad(h12), h: h12, A: amOrPm,
mm: pad(m), m: m,
Line 2,058 ⟶ 2,069:
};
unbinder.unbind('\\[', '\\]');
unbinder.content = unbinder.content.replace(
Line 2,066 ⟶ 2,077:
*/
/H{1,2}|h{1,2}|m{1,2}|s{1,2}|SSS|d(d{2,3})?|D{1,2}|M{1,4}|Y{1,2}(Y{2})?|A/g,
);
return unbinder.rebind().replace(/\[(.*?)\]/g, '$1');
Line 2,079 ⟶ 2,088:
* @param {(string|number)} [zone=system] - 'system' (for browser-default time zone),
* 'utc' (for UTC), or specify a time zone as number of minutes past UTC.
* @
*/
calendar: function(zone) {
// Zero out the hours, minutes, seconds and milliseconds - keeping only the date;
// find the difference. Note that setHours() returns the same thing as getTime().
new Date(this).setHours(0, 0, 0, 0)) / 8.64e7;
switch (true) {
Line 2,106 ⟶ 2,115:
* as `==December 2019==` or `=== Jan 2018 ===`.
*
* @
*/
monthHeaderRegex: function() {
Line 2,118 ⟶ 2,127:
* @param {number} [level=2] - Header level. Pass 0 for just the text
* with no wikitext markers (==).
* @
*/
monthHeader: function(level) {
Line 2,125 ⟶ 2,134:
level = isNaN(level) ? 2 : level;
const header = '='.repeat(level);
if (header.length) { // wikitext-formatted header
Line 2,138 ⟶ 2,147:
// Allow native Date.prototype methods to be used on Morebits.date objects
Object.getOwnPropertyNames(Date.prototype).forEach(
Morebits.date.prototype[func] = function() {
return this.
};
});
/* **************** Morebits.wiki **************** */
Line 2,158 ⟶ 2,166:
* @deprecated in favor of Morebits.isPageRedirect as of November 2020
* @memberof Morebits.wiki
* @
*/
Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() {
Line 2,164 ⟶ 2,172:
return Morebits.isPageRedirect();
};
/* **************** Morebits.wiki.actionCompleted **************** */
Line 2,226 ⟶ 2,233:
}
}
window.setTimeout(
window.___location = Morebits.wiki.actionCompleted.redirect;
}, Morebits.wiki.actionCompleted.timeOut);
Line 2,250 ⟶ 2,257:
}
};
/* **************** Morebits.wiki.api **************** */
Line 2,269 ⟶ 2,275:
* @class
* @param {string} currentAction - The current action (required).
* @param {
* @param {Function} [onSuccess] - The function to call when request is successful.
* @param {Morebits.status} [statusElement] - A Morebits.status object to use for status messages.
Line 2,279 ⟶ 2,285:
this.query.assert = 'user';
// Enforce newer error formats, preferring html
if (!query.errorformat || !['wikitext', 'plaintext'].
this.query.errorformat = 'html';
}
Line 2,300 ⟶ 2,306:
} else if (query.format === 'json' && !query.formatversion) {
this.query.formatversion = '2';
} else if (!['xml', 'json'].
this.statelem.error('Invalid API format: only xml and json are supported.');
}
// Ignore tags for queries and most common unsupported actions, produces warnings
if (query.action && ['query', 'review', 'stabilize', 'pagetriageaction', 'watch'].
delete query.tags;
} else if (!query.tags && morebitsWikiChangeTag) {
Line 2,316 ⟶ 2,322:
onSuccess: null,
onError: null,
parent: window,
query: null,
response: null,
responseXML: null,
statelem: null,
statusText: null, // result received from the API, normally "success" or "error"
errorCode: null, // short text error code, if any, as documented in the MediaWiki API
Line 2,344 ⟶ 2,350:
* Carry out the request.
*
* @param {
* really want to give jQuery some extra parameters.
* @
*/
post: function(callerAjaxParameters) {
Line 2,352 ⟶ 2,358:
++Morebits.wiki.numberOfActionsLeft;
if (Array.isArray(val)) {
return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|');
Line 2,361 ⟶ 2,367:
// token should always be the last item in the query string (bug TW-B-0013)
context: this,
type: this.query.action === 'query' ? 'GET' : 'POST',
Line 2,427 ⟶ 2,433:
// Get a new CSRF token and retry. If the original action needs a different
// type of action than CSRF, we do one pointless retry before bailing out
return Morebits.wiki.api.getToken().then(
this.query.token = token;
return this.post(callerAjaxParameters);
}
}
Line 2,471 ⟶ 2,477:
/** Retrieves wikitext from a page. Caching enabled, duration 1 day. */
Morebits.wiki.getCachedJson = function(title) {
action: 'query',
prop: 'revisions',
Line 2,481 ⟶ 2,487:
maxage: '86400' // cache for 1 day
};
return new Morebits.wiki.api('', query).post().then(
apiobj.getStatusElement().unlink();
return JSON.parse(wikitext);
});
Line 2,506 ⟶ 2,512:
morebitsWikiApiUserAgent = (ua ? ua + ' ' : '') + 'morebits.js ([[w:WT:TW]])';
};
/**
Line 2,518 ⟶ 2,522:
*/
var morebitsWikiChangeTag = '';
/**
Line 2,524 ⟶ 2,527:
*
* @memberof Morebits.wiki.api
* @
*/
Morebits.wiki.api.getToken = function() {
action: 'query',
meta: 'tokens',
Line 2,533 ⟶ 2,536:
format: 'json'
});
return tokenApi.post().then(
};
/* **************** Morebits.wiki.page **************** */
Line 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,601 ⟶ 2,600:
* @private
*/
// backing fields for public properties
pageName: pageName,
Line 2,607 ⟶ 2,606:
editSummary: null,
changeTags: null,
testActions: null,
callbackParameters: null,
statusElement: status instanceof Morebits.status ? status : new Morebits.status(status),
Line 2,613 ⟶ 2,612:
// - edit
pageText: null,
editMode: 'all',
appendText: null,
prependText: null,
newSectionText: null,
newSectionTitle: null,
Line 2,645 ⟶ 2,644:
protectCreate: null,
protectCascade: null,
// - delete
deleteTalkPage: false,
// - undelete
undeleteTalkPage: false,
// - creation lookup
Line 2,707 ⟶ 2,712:
};
/**
Line 2,740 ⟶ 2,745:
if (ctx.editMode === 'all') {
ctx.loadQuery.rvprop = 'content|timestamp';
} else if (ctx.editMode === 'revert') {
ctx.loadQuery.rvprop = 'timestamp';
Line 2,748 ⟶ 2,753:
if (ctx.followRedirect) {
ctx.loadQuery.redirects = '';
}
if (typeof ctx.pageSection === 'number') {
Line 2,780 ⟶ 2,785:
// are we getting our editing token from mw.user.tokens?
if (!ctx.pageLoaded && !canUseMwUserToken) {
Line 2,803 ⟶ 2,808:
if (ctx.fullyProtected && !ctx.suppressProtectWarning &&
!confirm(
ctx.fullyProtected === 'infinity' ?
'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.'
) :
'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.'
Line 2,820 ⟶ 2,825:
ctx.retries = 0;
action: 'edit',
title: ctx.pageName,
Line 2,844 ⟶ 2,849:
query.minor = true;
} else {
query.notminor = true;
}
Line 2,859 ⟶ 2,864:
return;
}
query.appendtext = ctx.appendText;
break;
case 'prepend':
Line 2,867 ⟶ 2,872:
return;
}
query.prependtext = ctx.prependText;
break;
case 'new':
Line 2,876 ⟶ 2,881:
}
query.section = 'new';
query.text = ctx.newSectionText;
query.sectiontitle = ctx.newSectionTitle || ctx.editSummary; // done by the API, but non-'' values would get treated as text
break;
Line 2,896 ⟶ 2,901:
}
if (['recreate', 'createonly', 'nocreate'].
query[ctx.createOption] = '';
}
Line 2,972 ⟶ 2,977:
};
/** @
this.getPageName = function() {
return ctx.pageName;
};
/** @
this.getPageText = function() {
return ctx.pageText;
Line 3,014 ⟶ 3,019:
ctx.newSectionTitle = newSectionTitle;
};
// Edit-related setter methods:
Line 3,039 ⟶ 3,042:
ctx.changeTags = tags;
};
/**
Line 3,049 ⟶ 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 3,293 ⟶ 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 3,300 ⟶ 3,313:
};
/** @
this.getCurrentID = function() {
return ctx.revertCurID;
};
/** @
this.getRevisionUser = function() {
return ctx.revertUser;
};
/** @
this.getLastEditTime = function() {
return ctx.lastEditTime;
Line 3,327 ⟶ 3,340:
* detected upon calling `save()`.
*
* @param {
*/
this.setCallbackParameters = function(callbackParameters) {
Line 3,334 ⟶ 3,347:
/**
* @
*/
this.getCallbackParameters = function() {
Line 3,348 ⟶ 3,361:
/**
* @
*/
this.getStatusElement = function() {
Line 3,364 ⟶ 3,377:
/**
* @
*/
this.exists = function() {
Line 3,371 ⟶ 3,384:
/**
* @
* exist.
*/
Line 3,379 ⟶ 3,392:
/**
* @
* include (but may not be limited to): `wikitext`, `javascript`,
* `css`, `json`, `Scribunto`, `sanitized-css`, `MassMessageListContent`.
Line 3,389 ⟶ 3,402:
/**
* @
* unless it's being watched temporarily, in which case returns the
* expiry string.
Line 3,398 ⟶ 3,411:
/**
* @
*/
this.getLoadTime = function() {
Line 3,405 ⟶ 3,418:
/**
* @
*/
this.getCreator = function() {
Line 3,412 ⟶ 3,425:
/**
* @
*/
this.getCreationTimestamp = function() {
Line 3,418 ⟶ 3,431:
};
/** @
this.canEdit = function() {
return !!ctx.testActions && ctx.testActions.
};
Line 3,444 ⟶ 3,457:
}
action: 'query',
prop: 'revisions',
Line 3,465 ⟶ 3,478:
if (ctx.followRedirect) {
query.redirects = '';
}
Line 3,516 ⟶ 3,529:
fnProcessMove.call(this, this);
} else {
ctx.moveApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
Line 3,540 ⟶ 3,553:
// If a link is present, don't need to check if it's patrolled
if ($('.patrollink').length) {
ctx.rcid = mw.util.getParamValue('rcid', patrolhref);
fnProcessPatrol(this, this);
} else {
action: 'query',
prop: 'info',
Line 3,582 ⟶ 3,595:
this.triage = function() {
// Fall back to patrol if not a valid triage namespace
if (!mw.config.get('pageTriageNamespaces').
this.patrol();
} else {
Line 3,594 ⟶ 3,607:
fnProcessTriageList(this, this);
} else {
ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList);
Line 3,621 ⟶ 3,634:
fnProcessDelete.call(this, this);
} else {
ctx.deleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure);
Line 3,646 ⟶ 3,659:
fnProcessUndelete.call(this, this);
} else {
ctx.undeleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure);
Line 3,677 ⟶ 3,690:
// (absolute, not differential), we always need to request
// protection levels from the server
ctx.protectApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure);
Line 3,712 ⟶ 3,725:
fnProcessStabilize.call(this, this);
} else {
ctx.stabilizeApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure);
Line 3,736 ⟶ 3,749:
* @param {string} [action=edit] - The action being undertaken, e.g.
* "edit" or "delete". In practice, only "edit" or "notedit" matters.
* @
*/
var fnCanUseMwUserToken = function(action = 'edit') {
// If a watchlist expiry is set, we must always load the page
// to avoid overwriting indefinite protection. Of course, not
Line 3,767 ⟶ 3,778:
// wgRestrictionEdit is null on non-existent pages,
// so this neatly handles nonexistent pages
if (!editRestriction || editRestriction.
return false;
}
Line 3,789 ⟶ 3,800:
* @param {string} action - The action being undertaken, e.g. "edit" or
* "delete".
* @
*/
var fnNeedTokenInfoQuery = function(action) {
action: 'query',
meta: 'tokens',
Line 3,818 ⟶ 3,829:
// callback from loadApi.post()
var fnLoadSuccess = function() {
if (!fnCheckPageName(response, ctx.onLoadFailure)) {
Line 3,824 ⟶ 3,835:
}
let rev;
ctx.pageExists = !page.missing;
if (ctx.pageExists) {
Line 3,832 ⟶ 3,844:
ctx.pageID = page.pageid;
} else {
ctx.pageText = '';
ctx.pageID = 0; // nonexistent in response, matches wgArticleId
}
Line 3,854 ⟶ 3,866:
// Includes cascading protection
if (Morebits.userIsSysop) {
if (editProt) {
ctx.fullyProtected = editProt.expiry;
Line 3,866 ⟶ 3,876:
ctx.revertCurID = page.lastrevid;
ctx.testActions = []; // was null
Object.keys(testactions).forEach(
if (testactions[action]) {
ctx.testActions.push(action);
Line 3,883 ⟶ 3,893:
ctx.revertUser = rev && rev.user;
if (!ctx.revertUser) {
if (rev && rev.userhidden) {
ctx.revertUser = '<username hidden>';
} else {
Line 3,898 ⟶ 3,908:
// alert("Generate edit conflict now"); // for testing edit conflict recovery logic
ctx.onLoadSuccess(this);
};
Line 3,907 ⟶ 3,917:
}
if (page) {
// check for invalid titles
Line 3,917 ⟶ 3,927:
// retrieve actual title of the page after normalization and redirects
if (response.redirects) {
// check for cross-namespace redirect:
if (origNs !== newNs && !ctx.followCrossNsRedirect) {
ctx.statusElement.error(msg('cross-redirect-abort', ctx.pageName, resolvedName, ctx.pageName + ' is a cross-namespace redirect to ' + resolvedName + ', aborted'));
Line 3,956 ⟶ 3,966:
* ensured of knowing the watch status by the use of this.
*
* @
*/
var fnApplyWatchlistExpiry = function() {
Line 3,963 ⟶ 3,973:
return true;
} else if (typeof ctx.watched === 'string') {
// Attempt to determine if the new expiry is a
// relative (e.g. `1 month`) or absolute datetime
try {
newExpiry = new Morebits.date().add(rel[0], rel[1]);
Line 3,991 ⟶ 4,001:
// callback from saveApi.post()
var fnSaveSuccess = function() {
ctx.editMode = 'all';
// see if the API thinks we were successful
Line 3,999 ⟶ 4,009:
// real success
// default on success action - display link for edited page
link.setAttribute('href', mw.util.getUrl(ctx.pageName));
link.appendChild(document.createTextNode(ctx.pageName));
ctx.statusElement.info(['completed (', link, ')']);
if (ctx.onSaveSuccess) {
ctx.onSaveSuccess(this);
}
return;
Line 4,025 ⟶ 4,035:
// callback from saveApi.post()
var fnSaveError = function() {
// check for edit conflict
Line 4,031 ⟶ 4,041:
// edit conflicts can occur when the page needs to be purged from the server cache
action: 'purge',
titles: ctx.pageName
};
--Morebits.wiki.numberOfActionsLeft;
ctx.statusElement.info(msg('editconflict-retrying', 'Edit conflict detected, reapplying edit'));
Line 4,045 ⟶ 4,055:
ctx.loadApi.post(); // reload the page and reapply the edit
}
}), ctx.statusElement);
purgeApi.post();
Line 4,053 ⟶ 4,063:
// the error might be transient, so try again
ctx.statusElement.info(msg('save-failed-retrying', 2, 'Save failed, retrying in 2 seconds ...'));
--Morebits.wiki.numberOfActionsLeft;
// wait for sometime for client to regain connectivity
sleep(2000).then(
ctx.saveApi.post(); // give it another go!
});
Line 4,062 ⟶ 4,072:
// hard error, give up
} else {
response.errors[0].data; // html/wikitext/plaintext error format
Line 4,093 ⟶ 4,103:
}
ctx.editMode = 'all';
if (ctx.onSaveFailure) {
ctx.onSaveFailure(this);
}
}
};
if (!text) { // no text - content empty or inaccessible (revdelled or suppressed)
return false;
}
return Morebits.l10n.redirectTagAliases.some(
};
var fnLookupCreationSuccess = function() {
if (!fnCheckPageName(response, ctx.onLookupCreationFailure)) {
Line 4,116 ⟶ 4,124:
}
if (!rev) {
ctx.statusElement.error('Could not find any revisions of ' + ctx.pageName);
Line 4,153 ⟶ 4,161:
var fnLookupNonRedirectCreator = function() {
for (
if (!isTextRedirect(revs[i].content)) {
Line 4,193 ⟶ 4,201:
* @param {string} action - The action being checked.
* @param {string} onFailure - Failure callback.
* @
*/
var fnPreflightChecks = function(action, onFailure) {
Line 4,218 ⟶ 4,226:
* @param {string} onFailure - Failure callback.
* @param {string} response - The response document from the API call.
* @
*/
// No undelete as an existing page could have deleted revisions
if (actionMissing || protectMissing || saltMissing) {
Line 4,236 ⟶ 4,244:
// Delete, undelete, move
// extract protection info
if (action === 'undelete') {
editprot = response.pages[0].protection.filter(
} else if (action === 'delete' || action === 'move') {
editprot = response.pages[0].protection.filter(
}
if (editprot && !ctx.suppressProtectWarning &&
Line 4,264 ⟶ 4,268:
var fnProcessMove = function() {
if (fnCanUseMwUserToken('move')) {
Line 4,270 ⟶ 4,274:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('move', ctx.onMoveFailure, response)) {
Line 4,277 ⟶ 4,281:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'move',
from: pageTitle,
Line 4,314 ⟶ 4,318:
var fnProcessPatrol = function() {
action: 'patrol',
format: 'json'
Line 4,324 ⟶ 4,328:
query.token = mw.user.tokens.get('patrolToken');
} else {
// Don't patrol if not unpatrolled
Line 4,331 ⟶ 4,335:
}
if (!lastrevid) {
return;
Line 4,337 ⟶ 4,341:
query.revid = lastrevid;
if (!token) {
return;
Line 4,347 ⟶ 4,351:
}
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat);
Line 4,359 ⟶ 4,363:
ctx.csrfToken = mw.user.tokens.get('csrfToken');
} else {
ctx.pageID = response.pages[0].pageid;
Line 4,372 ⟶ 4,376:
}
action: 'pagetriagelist',
page_id: ctx.pageID,
Line 4,385 ⟶ 4,389:
// callback from triageProcessListApi.post()
var fnProcessTriage = function() {
// Exit if not in the queue
if (!responseList || responseList.result !== 'success') {
return;
}
// Do nothing if page already triaged/patrolled
if (!page || !parseInt(page.patrol_status, 10)) {
action: 'pagetriageaction',
pageid: ctx.pageID,
Line 4,403 ⟶ 4,407:
format: 'json'
};
ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, null, triageStat);
ctx.triageProcessApi.setParent(this);
Line 4,411 ⟶ 4,415:
var fnProcessDelete = function() {
if (fnCanUseMwUserToken('delete')) {
Line 4,417 ⟶ 4,421:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) {
Line 4,424 ⟶ 4,428:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'delete',
title: pageTitle,
Line 4,439 ⟶ 4,443:
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
if (ctx.deleteTalkPage) {
query.deletetalk = 'true';
}
Line 4,453 ⟶ 4,460:
var fnProcessDeleteError = function() {
// check for "Database query error"
if (errorCode === 'internal_api_error_DBQueryError' && ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
--Morebits.wiki.numberOfActionsLeft;
ctx.deleteProcessApi.post(); // give it another go!
Line 4,464 ⟶ 4,471:
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi);
}
// hard error, give up
Line 4,470 ⟶ 4,477:
ctx.statusElement.error('Failed to delete the page: ' + ctx.deleteProcessApi.getErrorText());
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi);
}
}
Line 4,476 ⟶ 4,483:
var fnProcessUndelete = function() {
if (fnCanUseMwUserToken('undelete')) {
Line 4,482 ⟶ 4,489:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) {
Line 4,489 ⟶ 4,496:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'undelete',
title: pageTitle,
Line 4,504 ⟶ 4,511:
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
if (ctx.undeleteTalkPage) {
query.undeletetalk = 'true';
}
Line 4,518 ⟶ 4,528:
var fnProcessUndeleteError = function() {
// check for "Database query error"
Line 4,524 ⟶ 4,534:
if (ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
--Morebits.wiki.numberOfActionsLeft;
ctx.undeleteProcessApi.post(); // give it another go!
} else {
ctx.statusElement.error('Repeated database query error, please try again');
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi);
}
}
Line 4,535 ⟶ 4,545:
ctx.statusElement.error('Cannot undelete the page, either because there are no revisions to undelete or because it has already been undeleted');
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi);
}
// hard error, give up
Line 4,541 ⟶ 4,551:
ctx.statusElement.error('Failed to undelete the page: ' + ctx.undeleteProcessApi.getErrorText());
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi);
}
}
Line 4,547 ⟶ 4,557:
var fnProcessProtect = function() {
if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) {
Line 4,553 ⟶ 4,563:
}
ctx.watched = page.watchlistexpiry || page.watched;
// Fetch existing protection levels
prs.forEach(
// Filter out protection from cascading
if (pr.type === 'edit' && !pr.source) {
Line 4,571 ⟶ 4,581:
}
});
// Fall back to current levels if not explicitly set
Line 4,586 ⟶ 4,595:
// Default to pre-existing cascading protection if unchanged (similar to above)
if (ctx.protectCascade === null) {
ctx.protectCascade = !!prs.filter(
}
// Warn if cascading protection being applied with an invalid protection level,
Line 4,610 ⟶ 4,617:
// Build protection levels and expirys (expiries?) for query
if (ctx.protectEdit) {
protections.push('edit=' + ctx.protectEdit.level);
Line 4,626 ⟶ 4,633:
}
action: 'protect',
title: pageTitle,
Line 4,654 ⟶ 4,661:
var fnProcessStabilize = function() {
if (fnCanUseMwUserToken('stabilize')) {
Line 4,660 ⟶ 4,667:
pageTitle = ctx.pageName;
} else {
// 'stabilize' as a verb not necessarily well understood
Line 4,668 ⟶ 4,675:
token = response.tokens.csrftoken;
pageTitle = page.title;
// Doesn't support watchlist expiry [[phab:T263336]]
Line 4,674 ⟶ 4,681:
}
action: 'stabilize',
title: pageTitle,
Line 4,698 ⟶ 4,705:
var sleep = function(milliseconds) {
setTimeout(deferred.resolve, milliseconds);
return deferred;
Line 4,711 ⟶ 4,718:
* - Need to reset all parameters once done (e.g. edit summary, move destination, etc.)
*/
/* **************** Morebits.wiki.preview **************** */
Line 4,739 ⟶ 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.
* @
*/
this.beginRender = function(wikitext, pageTitle, sectionTitle) {
$(previewbox).show();
previewbox.appendChild(statusspan);
Morebits.status.init(statusspan);
action: 'parse',
prop: ['text', 'modules'],
pst: true,
preview: true,
text: wikitext,
Line 4,763 ⟶ 4,769:
query.sectiontitle = sectionTitle;
}
return renderApi.post();
};
var fnRenderSuccess = function(apiobj) {
if (!html) {
apiobj.statelem.error('failed to retrieve preview, or template was blanked');
Line 4,787 ⟶ 4,793:
};
};
/* **************** Morebits.wikitext **************** */
Line 4,805 ⟶ 4,810:
* @param {string} text - Wikitext containing a template.
* @param {number} [start=0] - Index noting where in the text the template begins.
* @
*/
Morebits.wikitext.parseTemplate = function(text, start) {
start = start || 0;
name: '',
parameters: {}
};
/**
Line 4,830 ⟶ 4,835:
// Nothing found yet, this must be the template name
if (count === -1) {
result.name = current.
++count;
} else {
Line 4,842 ⟶ 4,847:
} else {
// No equals, so it must be unnamed; no trim since whitespace allowed
if (param) {
result.parameters[++unnamed] = param;
Line 4,851 ⟶ 4,856:
}
for (
if (test3 === '{{{' || (test3 === '}}}' && level[level.length - 1] === 3)) {
current += test3;
Line 4,863 ⟶ 4,868:
continue;
}
// Entering a template (or link)
if (test2 === '{{' || test2 === '[[') {
Line 4,925 ⟶ 4,930:
*
* @param {string} link_target
* @
*/
removeLink: function(link_target) {
if (namespaceID !== 0) {
link_regex_string = Morebits.namespaceRegex(namespaceID) + ':';
Line 4,940 ⟶ 4,945:
// For most namespaces, unlink both [[User:Test]] and [[:User:Test]]
// For files and categories, only unlink [[:Category:Test]]. Do not unlink [[Category:Test]]
this.text = this.text.replace(simple_link_regex, '$1').replace(piped_link_regex, '$1');
return this;
Line 4,955 ⟶ 4,960:
* @param {string} image - Image name without `File:` prefix.
* @param {string} [reason] - Reason to be included in comment, alongside the commented-out image.
* @
*/
commentOutImage: function(image, reason) {
unbinder.unbind('<!--', '-->');
reason = reason ? reason + ': ' : '';
// Check for normal image links, i.e. [[File:Foobar.png|...]]
// Will eat the whole link
for (
if (links_re.test(allLinks[i])) {
unbinder.content = unbinder.content.replace(allLinks[i], replacement);
// unbind the newly created comments
Line 4,980 ⟶ 4,985:
// eventually preceded with some space, and must include File: prefix
// Will eat the whole line.
unbinder.content = unbinder.content.replace(gallery_image_re, '<!-- ' + reason + '$1 -->');
Line 4,988 ⟶ 4,993:
// Check free image usages, for example as template arguments, might have the File: prefix excluded, but must be preceded by an |
// Will only eat the image name and the preceding bar and an eventual named parameter
unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->');
// Rebind the content now, we are done!
Line 5,000 ⟶ 5,005:
* @param {string} image - Image name without File: prefix.
* @param {string} data - The display options.
* @
*/
addToImageComment: function(image, data) {
for (
if (links_re.test(allLinks[i])) {
// just put it at the end?
replacement = replacement.replace(/\]\]$/, '|' + data + ']]');
Line 5,014 ⟶ 5,019:
}
}
this.text = this.text.replace(gallery_re, newtext);
return this;
Line 5,025 ⟶ 5,030:
* @param {string} template - Page name whose transclusions are to be removed,
* include namespace prefix only if not in template namespace.
* @
*/
removeTemplate: function(template) {
for (
if (links_re.test(allTemplates[i])) {
this.text = this.text.replace(allTemplates[i], '');
Line 5,051 ⟶ 5,056:
* @param {string|string[]} [preRegex] - Optional regex string or array to match
* before any template matches (i.e. before `{{`), such as html comments.
* @
*/
insertAfterTemplates: function(tag, regex, flags, preRegex) {
Line 5,075 ⟶ 5,080:
preRegex = preRegex.join('|');
}
// Regex is extra complicated to allow for templates with
Line 5,110 ⟶ 5,114:
* Get the manipulated wikitext.
*
* @
*/
getText: function() {
Line 5,116 ⟶ 5,120:
}
};
/* *********** Morebits.userspaceLogger ************ */
Line 5,150 ⟶ 5,153:
* @param {string} logText - Doesn't include leading `#` or `*`.
* @param {string} summaryText - Edit summary.
* @
*/
this.log = function(logText, summaryText) {
if (!logText) {
return def.reject();
}
'Adding entry to userspace log'); // make this '... to ' + logPageName ?
page.load(
// add blurb if log page doesn't exist or is blank
// create monthly header if it doesn't exist already
if (!date.monthHeaderRegex().exec(text)) {
text += '\n\n' + date.monthHeader(this.headerLevel);
Line 5,174 ⟶ 5,177:
pageobj.setCreateOption('recreate');
pageobj.save(def.resolve, def.reject);
}
return def;
};
};
/* **************** Morebits.status **************** */
Line 5,234 ⟶ 5,236:
Morebits.status.errorEvent = handler;
} else {
throw new Error('Morebits.status.onError: handler is not a function');
}
};
Line 5,327 ⟶ 5,329:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.status = function(text, status) {
Line 5,336 ⟶ 5,338:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.info = function(text, status) {
Line 5,345 ⟶ 5,347:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.warn = function(text, status) {
Line 5,354 ⟶ 5,356:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.error = function(text, status) {
Line 5,368 ⟶ 5,370:
*/
Morebits.status.actionCompleted = function(text) {
node.appendChild(document.createElement('b')).appendChild(document.createTextNode(text));
node.className = 'morebits_status_info morebits_action_complete';
Line 5,385 ⟶ 5,387:
*/
Morebits.status.printUserText = function(comments, message) {
p.innerHTML = message;
div.className = '
div.style.marginTop = '0';
div.style.whiteSpace = 'pre-wrap';
Line 5,395 ⟶ 5,397:
Morebits.status.root.appendChild(p);
};
/**
Line 5,404:
* @param {string} content - Text content.
* @param {string} [color] - Font color.
* @
*/
Morebits.htmlNode = function (type, content, color) {
if (color) {
node.style.color = color;
Line 5,414:
return node;
};
/**
Line 5,426 ⟶ 5,424:
*/
Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) {
function clickHandler(event) {
if (event.shiftKey && lastCheckbox !== null) {
for (i = 0; i < $cbs.length; i++) {
if ($cbs[i] === thisCb) {
index = i;
if (lastIndex > -1) {
Line 5,440 ⟶ 5,438:
}
}
if ($cbs[i] === lastCheckbox) {
lastIndex = i;
if (index > -1) {
Line 5,450 ⟶ 5,448:
if (index > -1 && lastIndex > -1) {
// inspired by wikibits
if (index < lastIndex) {
start = index + 1;
Line 5,461 ⟶ 5,459:
for (i = start; i <= finish; i++) {
if ($cbs[i].checked !== endState) {
$cbs[i].click();
}
}
Line 5,471 ⟶ 5,469:
}
$(jQuerySelector, jQueryContext).
};
/* **************** Morebits.batchOperation **************** */
Line 5,515 ⟶ 5,511:
*/
Morebits.batchOperation = function(currentAction) {
// backing fields for public properties
pageList: null,
Line 5,589 ⟶ 5,585:
ctx.pageChunks = [];
if (!total) {
ctx.statusElement.info(msg('batch-no-pages', 'no pages specified'));
Line 5,621 ⟶ 5,617:
if (arg instanceof Morebits.wiki.api || arg instanceof Morebits.wiki.page) {
// update or remove status line
if (ctx.options.preserveIndividualStatusLines) {
if (arg.getPageName || arg.pageName || (arg.query && arg.query.title)) {
// we know the page title - display a relevant message
statelem.info(msg('batch-done-page', pageName, 'completed ([[' + pageName + ']])'));
} else {
Line 5,650 ⟶ 5,646:
// private functions
var fnStartNewChunk = function() {
if (!chunk) {
return;
}
// start workers for the current chunk
ctx.countStarted += chunk.length;
chunk.forEach(
ctx.worker(page, thisProxy);
});
Line 5,669 ⟶ 5,665:
// update overall status line
if (ctx.countFinished < total) {
ctx.statusElement.status(msg('percent', progress, progress + '%'));
Line 5,681 ⟶ 5,677:
}
} else if (ctx.countFinished === total) {
'/' + ctx.countFinished + ' actions completed successfully)');
if (ctx.countFinishedSuccess < ctx.countFinished) {
Line 5,718 ⟶ 5,714:
this.failureCallbackMap = new Map();
this.deferreds = new Map();
this.context = context || window;
Line 5,734 ⟶ 5,729:
this.add = function(func, deps, onFailure) {
this.taskDependencyMap.set(func, deps);
this.failureCallbackMap.set(func, onFailure ||
this.deferreds.set(func, deferred);
};
Line 5,743 ⟶ 5,737:
* Run all the tasks. Multiple tasks may be run at once.
*
* @
*/
this.execute = function() {
this.taskDependencyMap.forEach(
$.when.apply(self.context, dependencyPromisesArray).then(function() {
if (result === undefined) { // maybe the function threw, or it didn't return anything
mw.log.error('Morebits.taskManager: task returned undefined');
Line 5,768 ⟶ 5,760:
});
});
return $.when.apply(null, [...this.
};
Line 5,778 ⟶ 5,770:
* @memberof Morebits
* @class
* @requires
* @param {number} width
* @param {number} height - The maximum allowable height for the content area.
*/
Morebits.simpleWindow = function SimpleWindow(width, height) {
this.content = content;
content.className = 'morebits-dialog-content';
Line 5,794 ⟶ 5,786:
buttons: { 'Placeholder button': function() {} },
dialogClass: 'morebits-dialog',
width: Math.min(parseInt(window.innerWidth, 10), parseInt(width
// give jQuery the given height value (which represents the anticipated height of the dialog) here, so
// it can position the dialog appropriately
Line 5,821 ⟶ 5,813:
});
// delete the placeholder button (it's only there so the buttonpane gets created)
$widget.find('button').each(
value.parentNode.removeChild(value);
});
// add container for the buttons we add, and the footer links (if any)
buttonspan.className = 'morebits-dialog-buttons';
linksspan.className = 'morebits-dialog-footerlinks';
$widget.find('.ui-dialog-buttonpane').append(buttonspan, linksspan);
Line 5,837 ⟶ 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,848 ⟶ 5,843:
* Focuses the dialog. This might work, or on the contrary, it might not.
*
* @
*/
focus: function() {
Line 5,860 ⟶ 5,855:
*
* @param {event} [event]
* @
*/
close: function(event) {
Line 5,874 ⟶ 5,869:
* might work, but it is not guaranteed.
*
* @
*/
display: function() {
if (this.scriptName) {
$widget.find('.morebits-dialog-scriptname').remove();
scriptnamespan.className = 'morebits-dialog-scriptname';
scriptnamespan.textContent = this.scriptName + ' \u00B7 ';
$widget.find('.ui-dialog-title').prepend(scriptnamespan);
}
if (window.setupTooltips && window.pg && window.pg.re && window.pg.re.diff) {
dialog.parent()[0].ranSetupTooltipsAlready = false;
window.setupTooltips(dialog.parent()[0]);
}
this.setHeight(this.height);
return this;
},
Line 5,899 ⟶ 5,894:
*
* @param {string} title
* @
*/
setTitle: function(title) {
Line 5,911 ⟶ 5,906:
*
* @param {string} name
* @
*/
setScriptName: function(name) {
Line 5,922 ⟶ 5,917:
*
* @param {number} width
* @
*/
setWidth: function(width) {
Line 5,934 ⟶ 5,929:
*
* @param {number} height
* @
*/
setHeight: function(height) {
Line 5,960 ⟶ 5,955:
*
* @param {HTMLElement} content
* @
*/
setContent: function(content) {
Line 5,972 ⟶ 5,967:
*
* @param {HTMLElement} content
* @
*/
addContent: function(content) {
Line 5,978 ⟶ 5,973:
// look for submit buttons in the content, hide them, and add a proxy button to the button pane
$(this.content).find('input[type="submit"], button[type="submit"]').each(
value.style.display = 'none';
if (value.hasAttribute('value')) {
button.textContent = value.getAttribute('value');
} else if (value.textContent) {
button.textContent = value.textContent;
} else {
button.textContent = msg('submit', 'Submit');
}
button.className = value.className || 'submitButtonProxy';
// here is an instance of cheap coding, probably a memory-usage hit in using a closure here
button.addEventListener('click',
value.click();
}, false);
Line 5,994 ⟶ 5,997:
$(this.content).dialog('widget').find('.morebits-dialog-buttons').empty().append(this.buttons)[0].removeAttribute('data-empty');
} else {
$(this.content).dialog('widget').find('.morebits-dialog-buttons')[0].setAttribute('data-empty', 'data-empty');
}
return this;
Line 6,002 ⟶ 6,005:
* Removes all contents from the dialog, barring any footer links.
*
* @
*/
purgeContent: function() {
Line 6,024 ⟶ 6,027:
* @param {string} wikiPage - Link target.
* @param {boolean} [prep=false] - Set true to prepend rather than append.
* @
*/
addFooterLink: function(text, wikiPage, prep) {
if (this.hasFooterLinks) {
bullet.textContent = msg('bullet-separator', ' \u2022 ');
if (prep) {
$footerlinks.prepend(bullet);
Line 6,037 ⟶ 6,040:
}
}
link.setAttribute('href', mw.util.getUrl(wikiPage));
link.setAttribute('title', wikiPage);
Line 6,058 ⟶ 6,061:
* @param {boolean} [modal=false] - If set to true, other items on the
* page will be disabled, i.e., cannot be interacted with.
* @
*/
setModality: function(modal) {
Line 6,081 ⟶ 6,084:
};
// Create capital letter aliases for all Morebits @classes (functions that work with the `new` keyword), to follow the coding convention that classes should start with an uppercase letter. This will let us start fixing ESLint `new-cap` errors in other files.
Morebits.BatchOperation = Morebits.batchOperation;
Morebits.Date = Morebits.date;
Morebits.QuickForm = Morebits.quickForm;
Morebits.QuickForm.Element = Morebits.quickForm.element;
Morebits.SimpleWindow = Morebits.simpleWindow;
Morebits.Status = Morebits.status;
Morebits.TaskManager = Morebits.taskManager;
Morebits.Unbinder = Morebits.unbinder;
Morebits.UserspaceLogger = Morebits.userspaceLogger;
Morebits.wiki.Api = Morebits.wiki.api;
Morebits.wiki.Page = Morebits.wiki.page;
Morebits.wiki.Preview = Morebits.wiki.preview;
Morebits.wikitext.Page = Morebits.wikitext.page;
}());
/**
Line 6,094 ⟶ 6,110:
*/
if (typeof arguments === 'undefined') {
/* global Morebits */
window.SimpleWindow = Morebits.simpleWindow;
|