MediaWiki:Gadget-morebits.js: Difference between revisions
Created page with "// <nowiki> /** * A library full of lots of goodness for user scripts on MediaWiki wikis, including Wikipedia. * * The highlights include: * - {@link Morebits.wiki.api} - make calls to the MediaWiki API * - {@link Morebits.wiki.page} - modify pages on the wiki (edit, revert, delete, etc.) * - {@link Morebits.date} - enhanced date object processing, sort of a light moment.js * - {@link Morebits.quickForm} - generate quick HTML forms on the fly * - {@link Morebits...." |
No edit summary |
||
Line 6: | Line 6: | ||
* - {@link Morebits.wiki.api} - make calls to the MediaWiki API | * - {@link Morebits.wiki.api} - make calls to the MediaWiki API | ||
* - {@link Morebits.wiki.page} - modify pages on the wiki (edit, revert, delete, etc.) | * - {@link Morebits.wiki.page} - modify pages on the wiki (edit, revert, delete, etc.) | ||
* - {@link Morebits.wiki.user} - get information on and process users (block, change user groups, etc.) | |||
* - {@link Morebits.date} - enhanced date object processing, sort of a light moment.js | * - {@link Morebits.date} - enhanced date object processing, sort of a light moment.js | ||
* - {@link Morebits.quickForm} - generate quick HTML forms on the fly | * - {@link Morebits.quickForm} - generate quick HTML forms on the fly | ||
Line 34: | Line 35: | ||
*/ | */ | ||
(function() { | |||
(function (window, document, $) { // Wrap entire file with anonymous function | |||
/** @lends Morebits */ | /** @lends Morebits */ | ||
var Morebits = {}; | |||
window.Morebits = Morebits; // allow global access | window.Morebits = Morebits; // allow global access | ||
/** | /** | ||
Line 49: | Line 51: | ||
* Examples: | * Examples: | ||
* Use jquery-i18n: | * Use jquery-i18n: | ||
* Morebits.i18n.setParser({ get: $.i18n }); | * Morebits.i18n.setParser({ get: $.i18n }); | ||
* Use banana-i18n or orange-i18n: | * Use banana-i18n or orange-i18n: | ||
* var banana = new Banana('en'); | * var banana = new Banana('en'); | ||
* Morebits.i18n.setParser({ get: banana.i18n }); | * Morebits.i18n.setParser({ get: banana.i18n }); | ||
* @param {Object} parser | * @param {Object} parser | ||
*/ | */ | ||
Line 64: | Line 65: | ||
/** | /** | ||
* @private | * @private | ||
* @ | * @returns {string} | ||
*/ | */ | ||
getMessage: function () { | getMessage: function () { | ||
var args = Array.prototype.slice.call(arguments); // array of size `n` | |||
// 1st arg: message name | // 1st arg: message name | ||
// 2nd to (n-1)th arg: message parameters | // 2nd to (n-1)th arg: message parameters | ||
// nth arg: legacy English fallback | // nth arg: legacy English fallback | ||
var msgName = args[0]; | |||
var fallback = args[args.length - 1]; | |||
if (!Morebits.i18n.parser) { | if (!Morebits.i18n.parser) { | ||
return fallback; | return fallback; | ||
Line 78: | Line 79: | ||
// i18n libraries are generally invoked with variable number of arguments | // i18n libraries are generally invoked with variable number of arguments | ||
// as msg(msgName, ...parameters) | // as msg(msgName, ...parameters) | ||
var 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 no i18n message exists, i18n libraries generally give back the message name | ||
if (i18nMessage === msgName) { | if (i18nMessage === msgName) { | ||
Line 88: | Line 89: | ||
// shortcut | // shortcut | ||
var msg = Morebits.i18n.getMessage; | |||
/** | /** | ||
Line 99: | Line 101: | ||
*/ | */ | ||
redirectTagAliases: ['#REDIRECT'], | redirectTagAliases: ['#REDIRECT'], | ||
/** | |||
* Additional regex used to identify usernames as likely unflagged bots. | |||
* | |||
* @constant | |||
* @default | |||
* @type {RegExp} | |||
*/ | |||
botUsernameRegex: /bot\b/i, | |||
/** | /** | ||
Line 105: | Line 116: | ||
* in the format [year, month, date, hour, minute, second] | * in the format [year, month, date, hour, minute, second] | ||
* which can be passed to Date.UTC() | * which can be passed to Date.UTC() | ||
* @param {string} str | * @param {string} str | ||
* @ | * @returns {number[] | null} | ||
*/ | */ | ||
signatureTimestampFormat: function (str) { | signatureTimestampFormat: function (str) { | ||
// HH:mm, DD Month YYYY (UTC) | // 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) { | if (!match) { | ||
return null; | return null; | ||
} | } | ||
var month = Morebits.date.localeData.months.indexOf(match[4]); | |||
if (month === -1) { | if (month === -1) { | ||
return null; | return null; | ||
Line 124: | Line 134: | ||
} | } | ||
}; | }; | ||
/** | /** | ||
Line 129: | Line 140: | ||
* | * | ||
* @param {string} group - e.g. `sysop`, `extendedconfirmed`, etc. | * @param {string} group - e.g. `sysop`, `extendedconfirmed`, etc. | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
Morebits.userIsInGroup = function (group) { | Morebits.userIsInGroup = function (group) { | ||
return mw.config.get('wgUserGroups'). | return mw.config.get('wgUserGroups').indexOf(group) !== -1; | ||
}; | }; | ||
/* | /** Hardcodes whether the user is a sysop, used a lot. | ||
* | * | ||
* @type {boolean} | * @type {boolean} | ||
Line 151: | Line 161: | ||
* | * | ||
* @param {string} address - The IPv6 address, with or without CIDR. | * @param {string} address - The IPv6 address, with or without CIDR. | ||
* @ | * @returns {string} | ||
*/ | */ | ||
Morebits.sanitizeIPv6 = function (address) { | Morebits.sanitizeIPv6 = function (address) { | ||
Line 163: | Line 173: | ||
* detect Module:RfD, with the same failure points. | * detect Module:RfD, with the same failure points. | ||
* | * | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
Morebits.isPageRedirect = function() { | Morebits.isPageRedirect = function() { | ||
Line 176: | Line 186: | ||
*/ | */ | ||
Morebits.pageNameNorm = mw.config.get('wgPageName').replace(/_/g, ' '); | Morebits.pageNameNorm = mw.config.get('wgPageName').replace(/_/g, ' '); | ||
/** | /** | ||
Line 183: | Line 194: | ||
* | * | ||
* @param {string} pageName - Page name without namespace. | * @param {string} pageName - Page name without namespace. | ||
* @ | * @returns {string} - For a page name `Foo bar`, returns the string `[Ff]oo[_ ]bar`. | ||
*/ | */ | ||
Morebits.pageNameRegex = function(pageName) { | Morebits.pageNameRegex = function(pageName) { | ||
Line 189: | Line 200: | ||
return ''; | return ''; | ||
} | } | ||
var firstChar = pageName[0], | |||
remainder = Morebits.string.escapeRegExp(pageName.slice(1)); | remainder = Morebits.string.escapeRegExp(pageName.slice(1)); | ||
if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) { | if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) { | ||
Line 201: | Line 212: | ||
* Wikilink syntax (`[[...]]`) is transformed into HTML anchor. | * Wikilink syntax (`[[...]]`) is transformed into HTML anchor. | ||
* Used in Morebits.quickForm and Morebits.status | * Used in Morebits.quickForm and Morebits.status | ||
* @internal | * @internal | ||
* @param {string|Node|(string|Node)[]} input | * @param {string|Node|(string|Node)[]} input | ||
* @ | * @returns {DocumentFragment} | ||
*/ | */ | ||
Morebits.createHtml = function(input) { | Morebits.createHtml = function(input) { | ||
var fragment = document.createDocumentFragment(); | |||
if (!input) { | if (!input) { | ||
return fragment; | return fragment; | ||
Line 214: | Line 224: | ||
input = [ input ]; | input = [ input ]; | ||
} | } | ||
for ( | for (var i = 0; i < input.length; ++i) { | ||
if (input[i] instanceof Node) { | if (input[i] instanceof Node) { | ||
fragment.appendChild(input[i]); | fragment.appendChild(input[i]); | ||
} else { | } else { | ||
$.parseHTML(Morebits.createHtml.renderWikilinks(input[i])).forEach((node) | $.parseHTML(Morebits.createHtml.renderWikilinks(input[i])).forEach(function(node) { | ||
fragment.appendChild(node); | fragment.appendChild(node); | ||
}); | }); | ||
Line 228: | Line 238: | ||
/** | /** | ||
* Converts wikilinks to HTML anchor tags. | * Converts wikilinks to HTML anchor tags. | ||
* @param text | * @param text | ||
* @ | * @returns {*} | ||
*/ | */ | ||
Morebits.createHtml.renderWikilinks = function (text) { | Morebits.createHtml.renderWikilinks = function (text) { | ||
var ub = new Morebits.unbinder(text); | |||
// Don't convert wikilinks within code tags as they're used for displaying wiki-code | // Don't convert wikilinks within code tags as they're used for displaying wiki-code | ||
ub.unbind('<code>', '</code>'); | ub.unbind('<code>', '</code>'); | ||
ub.content = ub.content.replace( | ub.content = ub.content.replace( | ||
/\[\[:?(?:([^|\]]+?)\|)?([^\]|]+?)\]\]/g, | /\[\[:?(?:([^|\]]+?)\|)?([^\]|]+?)\]\]/g, | ||
(_, target, text) | function(_, target, text) { | ||
if (!target) { | if (!target) { | ||
target = text; | target = text; | ||
Line 261: | Line 270: | ||
* // returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])' | * // returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])' | ||
* Morebits.namespaceRegex([6]) | * Morebits.namespaceRegex([6]) | ||
* @ | * @returns {string} - Regex-suitable string of all namespace aliases. | ||
*/ | */ | ||
Morebits.namespaceRegex = function(namespaces) { | Morebits.namespaceRegex = function(namespaces) { | ||
Line 267: | Line 276: | ||
namespaces = [namespaces]; | namespaces = [namespaces]; | ||
} | } | ||
var aliases = [], regex; | |||
$.each(mw.config.get('wgNamespaceIds'), function(name, number) { | |||
$.each(mw.config.get('wgNamespaceIds'), (name, number) | if (namespaces.indexOf(number) !== -1) { | ||
if (namespaces. | |||
// Namespaces are completely agnostic as to case, | // Namespaces are completely agnostic as to case, | ||
// and a regex string is more useful/compatible than a RegExp object, | // and a regex string is more useful/compatible than a RegExp object, | ||
// so we accept any casing for any letter. | // so we accept any casing for any letter. | ||
aliases.push(name.split('').map((char) | aliases.push(name.split('').map(function(char) { | ||
return Morebits.pageNameRegex(char); | |||
}).join('')); | |||
} | } | ||
}); | }); | ||
Line 290: | Line 300: | ||
return regex; | return regex; | ||
}; | }; | ||
/* **************** Morebits.quickForm **************** */ | /* **************** Morebits.quickForm **************** */ | ||
Line 309: | Line 320: | ||
* | * | ||
* @memberof Morebits.quickForm | * @memberof Morebits.quickForm | ||
* @ | * @returns {HTMLElement} | ||
*/ | */ | ||
Morebits.quickForm.prototype.render = function QuickFormRender() { | Morebits.quickForm.prototype.render = function QuickFormRender() { | ||
var ret = this.root.render(); | |||
ret.names = {}; | ret.names = {}; | ||
return ret; | return ret; | ||
Line 323: | Line 334: | ||
* @param {(object|Morebits.quickForm.element)} data - A quickform element, or the object with which | * @param {(object|Morebits.quickForm.element)} data - A quickform element, or the object with which | ||
* a quickform element is constructed. | * a quickform element is constructed. | ||
* @ | * @returns {Morebits.quickForm.element} - Same as what is passed to the function. | ||
*/ | */ | ||
Morebits.quickForm.prototype.append = function QuickFormAppend(data) { | Morebits.quickForm.prototype.append = function QuickFormAppend(data) { | ||
Line 353: | Line 364: | ||
* - Attributes: Everything the text `input` has, as well as: min, max, step, list | * - 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. | * - `dyninput`: A set of text boxes with "Remove" buttons and an "Add" button. | ||
* - Attributes: name, label, min, max | * - Attributes: name, label, min, max, sublabel, value, size, maxlength, event | ||
* - `hidden`: An invisible form field. | * - `hidden`: An invisible form field. | ||
* - Attributes: name, value | * - Attributes: name, value | ||
Line 371: | Line 382: | ||
* - `div`, `select`, `field`, `checkbox`/`radio`, `input`, `textarea`, `header`, and `dyninput` can accept an array of items, | * - `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. | * and the label item(s) can be `Element`s. | ||
* - `option`, `optgroup`, ` | * - `option`, `optgroup`, `_dyninput_element`, `submit`, and `button` accept only a single string. | ||
* | * | ||
* @memberof Morebits.quickForm | * @memberof Morebits.quickForm | ||
* @class | * @class | ||
* @param { | * @param {object} data - Object representing the quickform element. Should | ||
* specify one of the available types from the index above, as well as any | * specify one of the available types from the index above, as well as any | ||
* relevant and available attributes. | * relevant and available attributes. | ||
Line 403: | Line 414: | ||
* @param {Morebits.quickForm.element} data - A quickForm element or the object required to | * @param {Morebits.quickForm.element} data - A quickForm element or the object required to | ||
* create the quickForm element. | * create the quickForm element. | ||
* @ | * @returns {Morebits.quickForm.element} The same element passed in. | ||
*/ | */ | ||
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) { | Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) { | ||
var child; | |||
if (data instanceof Morebits.quickForm.element) { | if (data instanceof Morebits.quickForm.element) { | ||
child = data; | child = data; | ||
Line 421: | Line 432: | ||
* | * | ||
* @memberof Morebits.quickForm.element | * @memberof Morebits.quickForm.element | ||
* @ | * @returns {HTMLElement} | ||
*/ | */ | ||
Morebits.quickForm.element.prototype.render = function QuickFormElementRender(internal_subgroup_id) { | Morebits.quickForm.element.prototype.render = function QuickFormElementRender(internal_subgroup_id) { | ||
var currentNode = this.compute(this.data, internal_subgroup_id); | |||
for ( | for (var i = 0; i < this.childs.length; ++i) { | ||
// do not pass internal_subgroup_id to recursive calls | // do not pass internal_subgroup_id to recursive calls | ||
currentNode[1].appendChild(this.childs[i].render()); | currentNode[1].appendChild(this.childs[i].render()); | ||
Line 432: | Line 443: | ||
return currentNode[0]; | return currentNode[0]; | ||
}; | }; | ||
/** @memberof Morebits.quickForm.element */ | /** @memberof Morebits.quickForm.element */ | ||
Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute(data, in_id) { | Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute(data, in_id) { | ||
var node; | |||
var childContainer = null; | |||
var label; | |||
var id = (in_id ? in_id + '_' : '') + 'node_' + Morebits.quickForm.element.id++; | |||
if (data.adminonly && !Morebits.userIsSysop) { | if (data.adminonly && !Morebits.userIsSysop) { | ||
// hell hack alpha | // hell hack alpha | ||
Line 444: | Line 456: | ||
} | } | ||
var i, current, subnode; | |||
switch (data.type) { | switch (data.type) { | ||
case 'form': | case 'form': | ||
Line 458: | Line 470: | ||
// fragments can't have any attributes, so just return it straight away | // fragments can't have any attributes, so just return it straight away | ||
return [ node, node ]; | return [ node, node ]; | ||
case 'select': | case 'select': | ||
node = document.createElement('div'); | node = document.createElement('div'); | ||
Line 545: | Line 556: | ||
if (data.list) { | if (data.list) { | ||
for (i = 0; i < data.list.length; ++i) { | for (i = 0; i < data.list.length; ++i) { | ||
var cur_id = id + '_' + i; | |||
current = data.list[i]; | current = data.list[i]; | ||
var cur_div; | var cur_div; | ||
if (current.type === 'header') { | if (current.type === 'header') { | ||
// inline hack | |||
cur_div = node.appendChild(document.createElement('h6')); | cur_div = node.appendChild(document.createElement('h6')); | ||
cur_div.appendChild(document.createTextNode(current.label)); | cur_div.appendChild(document.createTextNode(current.label)); | ||
Line 592: | Line 603: | ||
var event; | var event; | ||
if (current.subgroup) { | if (current.subgroup) { | ||
var tmpgroup = current.subgroup; | |||
if (!Array.isArray(tmpgroup)) { | if (!Array.isArray(tmpgroup)) { | ||
Line 602: | Line 613: | ||
id: id + '_' + i + '_subgroup' | id: id + '_' + i + '_subgroup' | ||
}); | }); | ||
$.each(tmpgroup, (idx, el) | $.each(tmpgroup, function(idx, el) { | ||
var newEl = $.extend({}, el); | |||
if (!newEl.type) { | if (!newEl.type) { | ||
newEl.type = data.type; | newEl.type = data.type; | ||
Line 611: | Line 622: | ||
}); | }); | ||
var subgroup = subgroupRaw.render(cur_id); | |||
subgroup.className = 'quickformSubgroup'; | subgroup.className = 'quickformSubgroup'; | ||
subnode.subgroup = subgroup; | subnode.subgroup = subgroup; | ||
Line 620: | Line 631: | ||
e.target.parentNode.appendChild(e.target.subgroup); | e.target.parentNode.appendChild(e.target.subgroup); | ||
if (e.target.type === 'radio') { | if (e.target.type === 'radio') { | ||
var name = e.target.name; | |||
if (e.target.form.names[name] !== undefined) { | if (e.target.form.names[name] !== undefined) { | ||
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup); | e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup); | ||
Line 637: | Line 648: | ||
event = function(e) { | event = function(e) { | ||
if (e.target.checked) { | if (e.target.checked) { | ||
var name = e.target.name; | |||
if (e.target.form.names[name] !== undefined) { | if (e.target.form.names[name] !== undefined) { | ||
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup); | e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup); | ||
Line 678: | Line 689: | ||
} else { | } else { | ||
subnode.setAttribute('type', 'number'); | subnode.setAttribute('type', 'number'); | ||
['min', 'max', 'step', 'list'].forEach((att) | ['min', 'max', 'step', 'list'].forEach(function(att) { | ||
if (data[att]) { | if (data[att]) { | ||
subnode.setAttribute(att, data[att]); | subnode.setAttribute(att, data[att]); | ||
Line 685: | Line 696: | ||
} | } | ||
['value', 'size', 'placeholder', 'maxlength'].forEach((att) | ['value', 'size', 'placeholder', 'maxlength'].forEach(function(att) { | ||
if (data[att]) { | if (data[att]) { | ||
subnode.setAttribute(att, data[att]); | subnode.setAttribute(att, data[att]); | ||
} | } | ||
}); | }); | ||
['disabled', 'required', 'readonly'].forEach((att) | ['disabled', 'required', 'readonly'].forEach(function(att) { | ||
if (data[att]) { | if (data[att]) { | ||
subnode.setAttribute(att, att); | subnode.setAttribute(att, att); | ||
Line 716: | Line 727: | ||
disabled: min >= max, | disabled: min >= max, | ||
event: function(e) { | event: function(e) { | ||
var new_node = new Morebits.quickForm.element(e.target.sublist); | |||
e.target.area.appendChild(new_node.render()); | e.target.area.appendChild(new_node.render()); | ||
Line 730: | Line 741: | ||
var sublist = { | var sublist = { | ||
type: ' | type: '_dyninput_element', | ||
label: data.sublabel || data.label, | |||
name: data.name, | |||
value: data.value, | |||
size: data.size, | |||
remove: false, | remove: false, | ||
maxlength: data.maxlength, | maxlength: data.maxlength, | ||
event: data.event | event: data.event | ||
}; | }; | ||
for (i = 0; i < min; ++i) { | for (i = 0; i < min; ++i) { | ||
var elem = new Morebits.quickForm.element(sublist); | |||
listNode.appendChild(elem.render()); | listNode.appendChild(elem.render()); | ||
} | } | ||
Line 756: | Line 764: | ||
moreButton.counter = 0; | moreButton.counter = 0; | ||
break; | break; | ||
case ' | case '_dyninput_element': // Private, similar to normal input | ||
node = document.createElement('div'); | node = document.createElement('div'); | ||
if (data.label) { | if (data.label) { | ||
label = node.appendChild(document.createElement('label')); | label = node.appendChild(document.createElement('label')); | ||
label.appendChild(document.createTextNode(data.label)); | label.appendChild(document.createTextNode(data.label)); | ||
label.setAttribute('for', id | label.setAttribute('for', id); | ||
label.style.marginRight = '3px'; | label.style.marginRight = '3px'; | ||
} | } | ||
subnode = node.appendChild(document.createElement('input')); | subnode = node.appendChild(document.createElement('input')); | ||
if (data.value) { | if (data.value) { | ||
subnode.setAttribute('value', data.value); | subnode.setAttribute('value', data.value); | ||
Line 802: | Line 780: | ||
subnode.setAttribute('name', data.name); | subnode.setAttribute('name', data.name); | ||
subnode.setAttribute('type', 'text'); | subnode.setAttribute('type', 'text'); | ||
if (data.size) { | if (data.size) { | ||
subnode.setAttribute('size', data.size); | subnode.setAttribute('size', data.size); | ||
Line 808: | Line 785: | ||
if (data.maxlength) { | if (data.maxlength) { | ||
subnode.setAttribute('maxlength', data.maxlength); | subnode.setAttribute('maxlength', data.maxlength); | ||
} | } | ||
if (data.event) { | if (data.event) { | ||
subnode.addEventListener('keyup', data.event, false); | subnode.addEventListener('keyup', data.event, false); | ||
} | } | ||
node. | if (data.remove) { | ||
break; | var remove = this.compute({ | ||
case 'hidden': | type: 'button', | ||
node = document.createElement('input'); | label: 'remove', | ||
node.setAttribute('type', 'hidden'); | 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': | |||
node = document.createElement('input'); | |||
node.setAttribute('type', 'hidden'); | |||
node.values = data.value; | node.values = data.value; | ||
node.setAttribute('value', data.value); | node.setAttribute('value', data.value); | ||
Line 837: | Line 828: | ||
} | } | ||
if (data.label) { | if (data.label) { | ||
var result = document.createElement('span'); | |||
result.className = 'quickformDescription'; | result.className = 'quickformDescription'; | ||
result.appendChild(Morebits.createHtml(data.label)); | result.appendChild(Morebits.createHtml(data.label)); | ||
Line 875: | Line 866: | ||
if (data.label) { | if (data.label) { | ||
label = node.appendChild(document.createElement('h5')); | label = node.appendChild(document.createElement('h5')); | ||
var labelElement = document.createElement('label'); | |||
labelElement.appendChild(Morebits.createHtml(data.label)); | labelElement.appendChild(Morebits.createHtml(data.label)); | ||
labelElement.setAttribute('for', data.id || id); | labelElement.setAttribute('for', data.id || id); | ||
Line 936: | Line 927: | ||
* | * | ||
* @memberof Morebits.quickForm.element | * @memberof Morebits.quickForm.element | ||
* @requires | * @requires jquery.ui | ||
* @param {HTMLElement} node - The HTML element beside which a tooltip is to be generated. | * @param {HTMLElement} node - The HTML element beside which a tooltip is to be generated. | ||
* @param { | * @param {object} data - Tooltip-related configuration data. | ||
*/ | */ | ||
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) { | Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) { | ||
var tooltipButton = node.appendChild(document.createElement('span')); | |||
tooltipButton.className = 'morebits-tooltipButton'; | tooltipButton.className = 'morebits-tooltipButton'; | ||
tooltipButton.title = data.tooltip; // Provides the content for jQuery UI | tooltipButton.title = data.tooltip; // Provides the content for jQuery UI | ||
Line 951: | Line 942: | ||
}); | }); | ||
}; | }; | ||
// Some utility methods for manipulating quickForms after their creation: | // Some utility methods for manipulating quickForms after their creation: | ||
Line 961: | Line 953: | ||
* @memberof Morebits.quickForm | * @memberof Morebits.quickForm | ||
* @param {HTMLFormElement} form | * @param {HTMLFormElement} form | ||
* @ | * @returns {object} With field names as keys, input data as values. | ||
*/ | */ | ||
Morebits.quickForm.getInputData = function(form) { | Morebits.quickForm.getInputData = function(form) { | ||
var result = {}; | |||
for ( | for (var i = 0; i < form.elements.length; i++) { | ||
var field = form.elements[i]; | |||
if (field.disabled || !field.name || !field.type || | if (field.disabled || !field.name || !field.type || | ||
field.type === 'submit' || field.type === 'button') { | field.type === 'submit' || field.type === 'button') { | ||
Line 975: | Line 967: | ||
// For elements in subgroups, quickform prepends element names with | // For elements in subgroups, quickform prepends element names with | ||
// name of the parent group followed by a period, get rid of that. | // name of the parent group followed by a period, get rid of that. | ||
var fieldNameNorm = field.name.slice(field.name.indexOf('.') + 1); | |||
switch (field.type) { | switch (field.type) { | ||
Line 998: | Line 990: | ||
case 'text': // falls through | case 'text': // falls through | ||
case 'textarea': | case 'textarea': | ||
result[fieldNameNorm] = field.value.trim(); | |||
break; | break; | ||
default: // could be select-one, date, number, email, etc | default: // could be select-one, date, number, email, etc | ||
Line 1,014: | Line 1,001: | ||
return result; | return result; | ||
}; | }; | ||
/** | /** | ||
Line 1,021: | Line 1,009: | ||
* @param {HTMLFormElement} form | * @param {HTMLFormElement} form | ||
* @param {string} fieldName - The name or id of the fields. | * @param {string} fieldName - The name or id of the fields. | ||
* @ | * @returns {HTMLElement[]} - Array of matching form elements. | ||
*/ | */ | ||
Morebits.quickForm.getElements = function QuickFormGetElements(form, fieldName) { | Morebits.quickForm.getElements = function QuickFormGetElements(form, fieldName) { | ||
var $form = $(form); | |||
fieldName = $.escapeSelector(fieldName); // sanitize input | fieldName = $.escapeSelector(fieldName); // sanitize input | ||
var $elements = $form.find('[name="' + fieldName + '"]'); | |||
if ($elements.length > 0) { | if ($elements.length > 0) { | ||
return $elements.toArray(); | return $elements.toArray(); | ||
Line 1,041: | Line 1,029: | ||
* @param {HTMLInputElement[]} elementArray - Array of checkbox or radio elements. | * @param {HTMLInputElement[]} elementArray - Array of checkbox or radio elements. | ||
* @param {string} value - Value to search for. | * @param {string} value - Value to search for. | ||
* @ | * @returns {HTMLInputElement} | ||
*/ | */ | ||
Morebits.quickForm.getCheckboxOrRadio = function QuickFormGetCheckboxOrRadio(elementArray, value) { | Morebits.quickForm.getCheckboxOrRadio = function QuickFormGetCheckboxOrRadio(elementArray, value) { | ||
var found = $.grep(elementArray, function(el) { | |||
return el.value === value; | |||
}); | |||
if (found.length > 0) { | if (found.length > 0) { | ||
return found[0]; | return found[0]; | ||
Line 1,057: | Line 1,047: | ||
* @memberof Morebits.quickForm | * @memberof Morebits.quickForm | ||
* @param {HTMLElement} element | * @param {HTMLElement} element | ||
* @ | * @returns {HTMLElement} | ||
*/ | */ | ||
Morebits.quickForm.getElementContainer = function QuickFormGetElementContainer(element) { | Morebits.quickForm.getElementContainer = function QuickFormGetElementContainer(element) { | ||
// for divs, headings and fieldsets, the container is the element itself | // for divs, headings and fieldsets, the container is the element itself | ||
if (element instanceof HTMLFieldSetElement || element instanceof HTMLDivElement || | if (element instanceof HTMLFieldSetElement || element instanceof HTMLDivElement || | ||
element instanceof HTMLHeadingElement) { | |||
return element; | return element; | ||
} | } | ||
Line 1,076: | Line 1,066: | ||
* @memberof Morebits.quickForm | * @memberof Morebits.quickForm | ||
* @param {(HTMLElement|Morebits.quickForm.element)} element | * @param {(HTMLElement|Morebits.quickForm.element)} element | ||
* @ | * @returns {HTMLElement} | ||
*/ | */ | ||
Morebits.quickForm.getElementLabelObject = function QuickFormGetElementLabelObject(element) { | Morebits.quickForm.getElementLabelObject = function QuickFormGetElementLabelObject(element) { | ||
// for buttons, divs and headers, the label is on the element itself | // for buttons, divs and headers, the label is on the element itself | ||
if (element.type === 'button' || element.type === 'submit' || | if (element.type === 'button' || element.type === 'submit' || | ||
element instanceof HTMLDivElement || element instanceof HTMLHeadingElement) { | |||
return element; | return element; | ||
// for fieldsets, the label is the child <legend> element | |||
} else if (element instanceof HTMLFieldSetElement) { | } else if (element instanceof HTMLFieldSetElement) { | ||
return element.getElementsByTagName('legend')[0]; | return element.getElementsByTagName('legend')[0]; | ||
// for textareas, the label is the sibling <h5> element | |||
} else if (element instanceof HTMLTextAreaElement) { | } else if (element instanceof HTMLTextAreaElement) { | ||
return element.parentNode.getElementsByTagName('h5')[0]; | return element.parentNode.getElementsByTagName('h5')[0]; | ||
Line 1,099: | Line 1,089: | ||
* @memberof Morebits.quickForm | * @memberof Morebits.quickForm | ||
* @param {(HTMLElement|Morebits.quickForm.element)} element | * @param {(HTMLElement|Morebits.quickForm.element)} element | ||
* @ | * @returns {string} | ||
*/ | */ | ||
Morebits.quickForm.getElementLabel = function QuickFormGetElementLabel(element) { | Morebits.quickForm.getElementLabel = function QuickFormGetElementLabel(element) { | ||
var labelElement = Morebits.quickForm.getElementLabelObject(element); | |||
if (!labelElement) { | if (!labelElement) { | ||
Line 1,116: | Line 1,106: | ||
* @param {(HTMLElement|Morebits.quickForm.element)} element | * @param {(HTMLElement|Morebits.quickForm.element)} element | ||
* @param {string} labelText | * @param {string} labelText | ||
* @ | * @returns {boolean} True if succeeded, false if the label element is unavailable. | ||
*/ | */ | ||
Morebits.quickForm.setElementLabel = function QuickFormSetElementLabel(element, labelText) { | Morebits.quickForm.setElementLabel = function QuickFormSetElementLabel(element, labelText) { | ||
var labelElement = Morebits.quickForm.getElementLabelObject(element); | |||
if (!labelElement) { | if (!labelElement) { | ||
Line 1,134: | Line 1,124: | ||
* @param {(HTMLElement|Morebits.quickForm.element)} element | * @param {(HTMLElement|Morebits.quickForm.element)} element | ||
* @param {string} temporaryLabelText | * @param {string} temporaryLabelText | ||
* @ | * @returns {boolean} `true` if succeeded, `false` if the label element is unavailable. | ||
*/ | */ | ||
Morebits.quickForm.overrideElementLabel = function QuickFormOverrideElementLabel(element, temporaryLabelText) { | Morebits.quickForm.overrideElementLabel = function QuickFormOverrideElementLabel(element, temporaryLabelText) { | ||
Line 1,148: | Line 1,138: | ||
* @memberof Morebits.quickForm | * @memberof Morebits.quickForm | ||
* @param {(HTMLElement|Morebits.quickForm.element)} element | * @param {(HTMLElement|Morebits.quickForm.element)} element | ||
* @ | * @returns {boolean} True if succeeded, false if the label element is unavailable. | ||
*/ | */ | ||
Morebits.quickForm.resetElementLabel = function QuickFormResetElementLabel(element) { | Morebits.quickForm.resetElementLabel = function QuickFormResetElementLabel(element) { | ||
Line 1,178: | Line 1,168: | ||
$(Morebits.quickForm.getElementContainer(element)).find('.morebits-tooltipButton').toggle(visibility); | $(Morebits.quickForm.getElementContainer(element)).find('.morebits-tooltipButton').toggle(visibility); | ||
}; | }; | ||
/** | /** | ||
Line 1,185: | Line 1,177: | ||
* Get checked items in the form. | * Get checked items in the form. | ||
* | * | ||
* @ | * @function external:HTMLFormElement.getChecked | ||
* @param {string} name - Find checked property of elements (i.e. a checkbox | * @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 | * or a radiobutton) with the given name, or select options that have selected | ||
Line 1,191: | Line 1,183: | ||
* @param {string} [type] - Optionally specify either radio or checkbox (for | * @param {string} [type] - Optionally specify either radio or checkbox (for | ||
* the event that both checkboxes and radiobuttons have the same name). | * the event that both checkboxes and radiobuttons have the same name). | ||
* @ | * @returns {string[]} - Contains the values of elements with the given name | ||
* checked property set to true. | * checked property set to true. | ||
*/ | */ | ||
HTMLFormElement.prototype.getChecked = function(name, type) { | HTMLFormElement.prototype.getChecked = function(name, type) { | ||
var elements = this.elements[name]; | |||
if (!elements) { | if (!elements) { | ||
return []; | return []; | ||
} | } | ||
var return_array = []; | |||
var i; | |||
if (elements instanceof HTMLSelectElement) { | if (elements instanceof HTMLSelectElement) { | ||
var options = elements.options; | |||
for (i = 0; i < options.length; ++i) { | for (i = 0; i < options.length; ++i) { | ||
if (options[i].selected) { | if (options[i].selected) { | ||
Line 1,239: | Line 1,231: | ||
* Does the same as {@link HTMLFormElement.getChecked|getChecked}, but with unchecked elements. | * Does the same as {@link HTMLFormElement.getChecked|getChecked}, but with unchecked elements. | ||
* | * | ||
* @ | * @function external:HTMLFormElement.getUnchecked | ||
* @param {string} name - Find checked property of elements (i.e. a checkbox | * @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 | * or a radiobutton) with the given name, or select options that have selected | ||
Line 1,245: | Line 1,237: | ||
* @param {string} [type] - Optionally specify either radio or checkbox (for | * @param {string} [type] - Optionally specify either radio or checkbox (for | ||
* the event that both checkboxes and radiobuttons have the same name). | * the event that both checkboxes and radiobuttons have the same name). | ||
* @ | * @returns {string[]} - Contains the values of elements with the given name | ||
* checked property set to true. | * checked property set to true. | ||
*/ | */ | ||
HTMLFormElement.prototype.getUnchecked = function(name, type) { | HTMLFormElement.prototype.getUnchecked = function(name, type) { | ||
var elements = this.elements[name]; | |||
if (!elements) { | if (!elements) { | ||
return []; | return []; | ||
} | } | ||
var return_array = []; | |||
var i; | |||
if (elements instanceof HTMLSelectElement) { | if (elements instanceof HTMLSelectElement) { | ||
var options = elements.options; | |||
for (i = 0; i < options.length; ++i) { | for (i = 0; i < options.length; ++i) { | ||
if (!options[i].selected) { | if (!options[i].selected) { | ||
Line 1,304: | Line 1,296: | ||
* | * | ||
* @param {string} address - The IPv6 address, with or without CIDR. | * @param {string} address - The IPv6 address, with or without CIDR. | ||
* @ | * @returns {string} | ||
*/ | */ | ||
sanitizeIPv6: function (address) { | sanitizeIPv6: function (address) { | ||
Line 1,317: | Line 1,309: | ||
address = address.toUpperCase(); | address = address.toUpperCase(); | ||
// Expand zero abbreviations | // Expand zero abbreviations | ||
var abbrevPos = address.indexOf('::'); | |||
if (abbrevPos > -1) { | if (abbrevPos > -1) { | ||
// We know this is valid IPv6. Find the last index of the | // We know this is valid IPv6. Find the last index of the | ||
// address before any CIDR number (e.g. "a:b:c::/24"). | // 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... | // If the '::' is at the beginning... | ||
var repeat, extra, pad; | |||
if (abbrevPos === 0) { | if (abbrevPos === 0) { | ||
repeat = '0:'; | repeat = '0:'; | ||
Line 1,340: | Line 1,332: | ||
pad = 8; // 6+2 (due to '::') | pad = 8; // 6+2 (due to '::') | ||
} | } | ||
var replacement = repeat; | |||
pad -= address.split(':').length - 1; | pad -= address.split(':').length - 1; | ||
for ( | for (var i = 1; i < pad; i++) { | ||
replacement += repeat; | replacement += repeat; | ||
} | } | ||
Line 1,357: | Line 1,349: | ||
* | * | ||
* @param {string} ip | * @param {string} ip | ||
* @ | * @returns {boolean} - True if given a valid IP address range, false otherwise. | ||
*/ | */ | ||
isRange: function (ip) { | isRange: function (ip) { | ||
Line 1,368: | Line 1,360: | ||
* for IPv4 and /32 for IPv6. | * for IPv4 and /32 for IPv6. | ||
* | * | ||
* @ | * @returns {boolean} - True for valid ranges within the CIDR limits, | ||
* otherwise false (ranges outside the limit, single IPs, non-IPs). | * otherwise false (ranges outside the limit, single IPs, non-IPs). | ||
*/ | */ | ||
validCIDR: function (ip) { | validCIDR: function (ip) { | ||
if (Morebits.ip.isRange(ip)) { | if (Morebits.ip.isRange(ip)) { | ||
var subnet = parseInt(ip.match(/\/(\d{1,3})$/)[1], 10); | |||
if (subnet) { // Should be redundant | if (subnet) { // Should be redundant | ||
if (mw.util.isIPv6Address(ip, true)) { | if (mw.util.isIPv6Address(ip, true)) { | ||
Line 1,393: | Line 1,385: | ||
* | * | ||
* @param {string} ipv6 - The IPv6 address, with or without a subnet. | * @param {string} ipv6 - The IPv6 address, with or without a subnet. | ||
* @ | * @returns {boolean|string} - False if not IPv6 or bigger than a 64, | ||
* otherwise the (sanitized) /64 address. | * otherwise the (sanitized) /64 address. | ||
*/ | */ | ||
Line 1,400: | Line 1,392: | ||
return false; | return false; | ||
} | } | ||
var subnetMatch = ipv6.match(/\/(\d{1,3})$/); | |||
if (subnetMatch && parseInt(subnetMatch[1], 10) < 64) { | if (subnetMatch && parseInt(subnetMatch[1], 10) < 64) { | ||
return false; | return false; | ||
} | } | ||
ipv6 = Morebits.ip.sanitizeIPv6(ipv6); | ipv6 = Morebits.ip.sanitizeIPv6(ipv6); | ||
var ip_re = /^((?:[0-9A-F]{1,4}:){4})(?:[0-9A-F]{1,4}:){3}[0-9A-F]{1,4}(?:\/\d{1,3})?$/; | |||
return ipv6.replace(ip_re, '$1' + '0:0:0:0/64'); | return ipv6.replace(ip_re, '$1' + '0:0:0:0/64'); | ||
} | } | ||
}; | }; | ||
/** | /** | ||
Line 1,420: | Line 1,412: | ||
/** | /** | ||
* @param {string} str | * @param {string} str | ||
* @ | * @returns {string} | ||
*/ | */ | ||
toUpperCaseFirstChar: function(str) { | toUpperCaseFirstChar: function(str) { | ||
str = str.toString(); | str = str.toString(); | ||
return str. | return str.substr(0, 1).toUpperCase() + str.substr(1); | ||
}, | }, | ||
/** | /** | ||
* @param {string} str | * @param {string} str | ||
* @ | * @returns {string} | ||
*/ | */ | ||
toLowerCaseFirstChar: function(str) { | toLowerCaseFirstChar: function(str) { | ||
str = str.toString(); | str = str.toString(); | ||
return str. | return str.substr(0, 1).toLowerCase() + str.substr(1); | ||
}, | }, | ||
Line 1,444: | Line 1,436: | ||
* @param {string} end | * @param {string} end | ||
* @param {(string[]|string)} [skiplist] | * @param {(string[]|string)} [skiplist] | ||
* @ | * @returns {string[]} | ||
* @throws If the `start` and `end` strings aren't of the same length. | * @throws If the `start` and `end` strings aren't of the same length. | ||
* @throws If `skiplist` isn't an array or string | * @throws If `skiplist` isn't an array or string | ||
Line 1,452: | Line 1,444: | ||
throw new Error('start marker and end marker must be of the same length'); | throw new Error('start marker and end marker must be of the same length'); | ||
} | } | ||
var level = 0; | |||
var initial = null; | |||
var result = []; | |||
if (!Array.isArray(skiplist)) { | if (!Array.isArray(skiplist)) { | ||
if (skiplist === undefined) { | if (skiplist === undefined) { | ||
Line 1,464: | Line 1,456: | ||
} | } | ||
} | } | ||
for ( | for (var i = 0; i < str.length; ++i) { | ||
for ( | for (var j = 0; j < skiplist.length; ++j) { | ||
if (str.substr(i, skiplist[j].length) === skiplist[j]) { | if (str.substr(i, skiplist[j].length) === skiplist[j]) { | ||
i += skiplist[j].length - 1; | i += skiplist[j].length - 1; | ||
Line 1,498: | Line 1,490: | ||
* @param {string} str | * @param {string} str | ||
* @param {boolean} [addSig] | * @param {boolean} [addSig] | ||
* @ | * @returns {string} | ||
*/ | */ | ||
formatReasonText: function(str, addSig) { | formatReasonText: function(str, addSig) { | ||
var reason = (str || '').toString().trim(); | |||
var unbinder = new Morebits.unbinder(reason); | |||
unbinder.unbind('<no' + 'wiki>', '</no' + 'wiki>'); | unbinder.unbind('<no' + 'wiki>', '</no' + 'wiki>'); | ||
unbinder.content = unbinder.content.replace(/\|/g, '{{subst:!}}'); | unbinder.content = unbinder.content.replace(/\|/g, '{{subst:!}}'); | ||
reason = unbinder.rebind(); | reason = unbinder.rebind(); | ||
if (addSig) { | if (addSig) { | ||
var sig = '~~~~', sigIndex = reason.lastIndexOf(sig); | |||
if (sigIndex === -1 || sigIndex !== reason.length - sig.length) { | if (sigIndex === -1 || sigIndex !== reason.length - sig.length) { | ||
reason += ' ' + sig; | reason += ' ' + sig; | ||
Line 1,522: | Line 1,513: | ||
* | * | ||
* @param {string} str | * @param {string} str | ||
* @ | * @returns {string} | ||
*/ | */ | ||
formatReasonForLog: function(str) { | formatReasonForLog: function(str) { | ||
Line 1,542: | Line 1,533: | ||
* @param {(string|RegExp)} pattern | * @param {(string|RegExp)} pattern | ||
* @param {string} replacement | * @param {string} replacement | ||
* @ | * @returns {string} | ||
*/ | */ | ||
safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) { | safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) { | ||
Line 1,555: | Line 1,546: | ||
* | * | ||
* @param {string} expiry | * @param {string} expiry | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
isInfinity: function morebitsStringIsInfinity(expiry) { | isInfinity: function morebitsStringIsInfinity(expiry) { | ||
return ['indefinite', 'infinity', 'infinite', 'never']. | return ['indefinite', 'infinity', 'infinite', 'never'].indexOf(expiry) !== -1; | ||
}, | }, | ||
Line 1,566: | Line 1,557: | ||
* | * | ||
* @param {string} text - String to be escaped. | * @param {string} text - String to be escaped. | ||
* @ | * @returns {string} - The escaped text. | ||
*/ | */ | ||
escapeRegExp: function(text) { | escapeRegExp: function(text) { | ||
Line 1,572: | Line 1,563: | ||
} | } | ||
}; | }; | ||
/** | /** | ||
Line 1,584: | Line 1,576: | ||
* | * | ||
* @param {Array} arr | * @param {Array} arr | ||
* @ | * @returns {Array} A copy of the array with duplicates removed. | ||
* @throws When provided a non-array. | * @throws When provided a non-array. | ||
*/ | */ | ||
uniq: function(arr) { | uniq: function(arr) { | ||
if (!Array.isArray(arr)) { | if (!Array.isArray(arr)) { | ||
throw | throw 'A non-array object passed to Morebits.array.uniq'; | ||
} | } | ||
return arr.filter((item, idx) | return arr.filter(function(item, idx) { | ||
return arr.indexOf(item) === idx; | |||
}); | |||
}, | }, | ||
Line 1,598: | Line 1,592: | ||
* | * | ||
* @param {Array} arr | * @param {Array} arr | ||
* @ | * @returns {Array} A copy of the array with the first instance of each value | ||
* removed; subsequent instances of those values (duplicates) remain. | * removed; subsequent instances of those values (duplicates) remain. | ||
* @throws When provided a non-array. | * @throws When provided a non-array. | ||
Line 1,604: | Line 1,598: | ||
dups: function(arr) { | dups: function(arr) { | ||
if (!Array.isArray(arr)) { | if (!Array.isArray(arr)) { | ||
throw | throw 'A non-array object passed to Morebits.array.dups'; | ||
} | } | ||
return arr.filter((item, idx) | return arr.filter(function(item, idx) { | ||
return arr.indexOf(item) !== idx; | |||
}); | |||
}, | }, | ||
/** | /** | ||
Line 1,614: | Line 1,611: | ||
* @param {Array} arr | * @param {Array} arr | ||
* @param {number} size - Size of each chunk (except the last, which could be different). | * @param {number} size - Size of each chunk (except the last, which could be different). | ||
* @ | * @returns {Array[]} An array containing the smaller, chunked arrays. | ||
* @throws When provided a non-array. | * @throws When provided a non-array. | ||
*/ | */ | ||
chunk: function(arr, size) { | chunk: function(arr, size) { | ||
if (!Array.isArray(arr)) { | if (!Array.isArray(arr)) { | ||
throw | throw 'A non-array object passed to Morebits.array.chunk'; | ||
} | } | ||
if (typeof size !== 'number' || size <= 0) { // pretty impossible to do anything :) | if (typeof size !== 'number' || size <= 0) { // pretty impossible to do anything :) | ||
return [ arr ]; // we return an array consisting of this array. | return [ arr ]; // we return an array consisting of this array. | ||
} | } | ||
var numChunks = Math.ceil(arr.length / size); | |||
var result = new Array(numChunks); | |||
for ( | for (var i = 0; i < numChunks; i++) { | ||
result[i] = arr.slice(i * size, (i + 1) * size); | result[i] = arr.slice(i * size, (i + 1) * size); | ||
} | } | ||
Line 1,641: | Line 1,638: | ||
* @namespace Morebits.select2 | * @namespace Morebits.select2 | ||
* @memberof Morebits | * @memberof Morebits | ||
* @requires | * @requires jquery.select2 | ||
*/ | */ | ||
Morebits.select2 = { | Morebits.select2 = { | ||
Line 1,650: | Line 1,647: | ||
*/ | */ | ||
optgroupFull: function(params, data) { | optgroupFull: function(params, data) { | ||
var originalMatcher = $.fn.select2.defaults.defaults.matcher; | |||
var result = originalMatcher(params, data); | |||
if (result && params.term && | if (result && params.term && | ||
data.text.toUpperCase(). | data.text.toUpperCase().indexOf(params.term.toUpperCase()) !== -1) { | ||
result.children = data.children; | result.children = data.children; | ||
} | } | ||
Line 1,662: | Line 1,659: | ||
/** Custom matcher that matches from the beginning of words only. */ | /** Custom matcher that matches from the beginning of words only. */ | ||
wordBeginning: function(params, data) { | wordBeginning: function(params, data) { | ||
var originalMatcher = $.fn.select2.defaults.defaults.matcher; | |||
var result = originalMatcher(params, data); | |||
if (!params.term || (result && | if (!params.term || (result && | ||
new RegExp('\\b' + mw.util.escapeRegExp(params.term), 'i').test(result.text))) { | new RegExp('\\b' + mw.util.escapeRegExp(params.term), 'i').test(result.text))) { | ||
Line 1,674: | Line 1,671: | ||
/** Underline matched part of options. */ | /** Underline matched part of options. */ | ||
highlightSearchMatches: function(data) { | highlightSearchMatches: function(data) { | ||
var searchTerm = Morebits.select2SearchQuery; | |||
if (!searchTerm || data.loading) { | if (!searchTerm || data.loading) { | ||
return data.text; | return data.text; | ||
} | } | ||
var idx = data.text.toUpperCase().indexOf(searchTerm.toUpperCase()); | |||
if (idx < 0) { | if (idx < 0) { | ||
return data.text; | return data.text; | ||
Line 1,705: | Line 1,702: | ||
return; | return; | ||
} | } | ||
var target = $(ev.target).closest('.select2-container'); | |||
if (! | if (!target.length) { | ||
return; | return; | ||
} | } | ||
target = target.prev(); | |||
target.select2('open'); | |||
var search = target.data('select2').dropdown.$search || | |||
target.data('select2').selection.$search; | |||
search.focus(); | |||
search | |||
} | } | ||
}; | }; | ||
/** | /** | ||
Line 1,757: | Line 1,754: | ||
throw new Error('Both prefix and postfix must be provided'); | throw new Error('Both prefix and postfix must be provided'); | ||
} | } | ||
var re = new RegExp(prefix + '([\\s\\S]*?)' + postfix, 'g'); | |||
this.content = this.content.replace(re, Morebits.unbinder.getCallback(this)); | this.content = this.content.replace(re, Morebits.unbinder.getCallback(this)); | ||
}, | }, | ||
Line 1,764: | Line 1,761: | ||
* Restore the hidden portion of the `content` string. | * Restore the hidden portion of the `content` string. | ||
* | * | ||
* @ | * @returns {string} The processed output. | ||
*/ | */ | ||
rebind: function UnbinderRebind() { | rebind: function UnbinderRebind() { | ||
var content = this.content; | |||
content.self = this; | content.self = this; | ||
for ( | for (var current in this.history) { | ||
if (Object.prototype.hasOwnProperty.call(this.history, current)) { | if (Object.prototype.hasOwnProperty.call(this.history, current)) { | ||
content = content.replace(current, this.history[current]); | content = content.replace(current, this.history[current]); | ||
Line 1,785: | Line 1,782: | ||
Morebits.unbinder.getCallback = function UnbinderGetCallback(self) { | Morebits.unbinder.getCallback = function UnbinderGetCallback(self) { | ||
return function UnbinderCallback(match) { | return function UnbinderCallback(match) { | ||
var current = self.prefix + self.counter + self.postfix; | |||
self.history[current] = match; | self.history[current] = match; | ||
++self.counter; | ++self.counter; | ||
Line 1,791: | Line 1,788: | ||
}; | }; | ||
}; | }; | ||
/* **************** Morebits.date **************** */ | /* **************** Morebits.date **************** */ | ||
Line 1,802: | Line 1,801: | ||
*/ | */ | ||
Morebits.date = function() { | Morebits.date = function() { | ||
var args = Array.prototype.slice.call(arguments); | |||
// Check MediaWiki formats | // Check MediaWiki formats | ||
Line 1,809: | Line 1,808: | ||
// 14-digit string will be interpreted differently. | // 14-digit string will be interpreted differently. | ||
if (args.length === 1) { | if (args.length === 1) { | ||
var param = args[0]; | |||
if (/^\d{14}$/.test(param)) { | if (/^\d{14}$/.test(param)) { | ||
// YYYYMMDDHHmmss | // YYYYMMDDHHmmss | ||
var digitMatch = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(param); | |||
if (digitMatch) { | if (digitMatch) { | ||
// ..... year ... month .. date ... hour .... minute ..... second | // ..... year ... month .. date ... hour .... minute ..... second | ||
this. | this._d = new Date(Date.UTC.apply(null, [digitMatch[1], digitMatch[2] - 1, digitMatch[3], digitMatch[4], digitMatch[5], digitMatch[6]])); | ||
} | } | ||
} else if (typeof param === 'string') { | } else if (typeof param === 'string') { | ||
// Wikitext signature timestamp | // Wikitext signature timestamp | ||
var dateParts = Morebits.l10n.signatureTimestampFormat(param); | |||
if (dateParts) { | if (dateParts) { | ||
this. | this._d = new Date(Date.UTC.apply(null, dateParts)); | ||
} | } | ||
} | } | ||
} | } | ||
if (!this. | if (!this._d) { | ||
// Try standard date | // Try standard date | ||
this. | this._d = new (Function.prototype.bind.apply(Date, [Date].concat(args))); | ||
} | } | ||
Line 1,901: | Line 1,900: | ||
Morebits.date.prototype = { | Morebits.date.prototype = { | ||
/** @ | /** @returns {boolean} */ | ||
isValid: function() { | isValid: function() { | ||
return !isNaN(this.getTime()); | return !isNaN(this.getTime()); | ||
Line 1,908: | Line 1,907: | ||
/** | /** | ||
* @param {(Date|Morebits.date)} date | * @param {(Date|Morebits.date)} date | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
isBefore: function(date) { | isBefore: function(date) { | ||
Line 1,915: | Line 1,914: | ||
/** | /** | ||
* @param {(Date|Morebits.date)} date | * @param {(Date|Morebits.date)} date | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
isAfter: function(date) { | isAfter: function(date) { | ||
Line 1,921: | Line 1,920: | ||
}, | }, | ||
/** @ | /** @returns {string} */ | ||
getUTCMonthName: function() { | getUTCMonthName: function() { | ||
return Morebits.date.localeData.months[this.getUTCMonth()]; | return Morebits.date.localeData.months[this.getUTCMonth()]; | ||
}, | }, | ||
/** @ | /** @returns {string} */ | ||
getUTCMonthNameAbbrev: function() { | getUTCMonthNameAbbrev: function() { | ||
return Morebits.date.localeData.monthsShort[this.getUTCMonth()]; | return Morebits.date.localeData.monthsShort[this.getUTCMonth()]; | ||
}, | }, | ||
/** @ | /** @returns {string} */ | ||
getMonthName: function() { | getMonthName: function() { | ||
return Morebits.date.localeData.months[this.getMonth()]; | return Morebits.date.localeData.months[this.getMonth()]; | ||
}, | }, | ||
/** @ | /** @returns {string} */ | ||
getMonthNameAbbrev: function() { | getMonthNameAbbrev: function() { | ||
return Morebits.date.localeData.monthsShort[this.getMonth()]; | return Morebits.date.localeData.monthsShort[this.getMonth()]; | ||
}, | }, | ||
/** @ | /** @returns {string} */ | ||
getUTCDayName: function() { | getUTCDayName: function() { | ||
return Morebits.date.localeData.days[this.getUTCDay()]; | return Morebits.date.localeData.days[this.getUTCDay()]; | ||
}, | }, | ||
/** @ | /** @returns {string} */ | ||
getUTCDayNameAbbrev: function() { | getUTCDayNameAbbrev: function() { | ||
return Morebits.date.localeData.daysShort[this.getUTCDay()]; | return Morebits.date.localeData.daysShort[this.getUTCDay()]; | ||
}, | }, | ||
/** @ | /** @returns {string} */ | ||
getDayName: function() { | getDayName: function() { | ||
return Morebits.date.localeData.days[this.getDay()]; | return Morebits.date.localeData.days[this.getDay()]; | ||
}, | }, | ||
/** @ | /** @returns {string} */ | ||
getDayNameAbbrev: function() { | getDayNameAbbrev: function() { | ||
return Morebits.date.localeData.daysShort[this.getDay()]; | return Morebits.date.localeData.daysShort[this.getDay()]; | ||
Line 1,961: | Line 1,960: | ||
* @param {string} unit | * @param {string} unit | ||
* @throws If invalid or unsupported unit is given. | * @throws If invalid or unsupported unit is given. | ||
* @ | * @returns {Morebits.date} | ||
*/ | */ | ||
add: function(number, unit) { | add: function(number, unit) { | ||
var num = parseInt(number, 10); // normalize | |||
if (isNaN(num)) { | if (isNaN(num)) { | ||
throw new Error('Invalid number "' + number + '" provided.'); | throw new Error('Invalid number "' + number + '" provided.'); | ||
} | } | ||
unit = unit.toLowerCase(); // normalize | unit = unit.toLowerCase(); // normalize | ||
var unitMap = Morebits.date.unitMap; | |||
var unitNorm = unitMap[unit] || unitMap[unit + 's']; // so that both singular and plural forms work | |||
if (unitNorm) { | if (unitNorm) { | ||
// No built-in week functions, so rather than build out ISO's getWeek/setWeek, just multiply | // 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. | // Probably can't be used for Julian->Gregorian changeovers, etc. | ||
if (unitNorm === 'Week') { | if (unitNorm === 'Week') { | ||
unitNorm = 'Date' | unitNorm = 'Date', num *= 7; | ||
} | } | ||
this['set' + unitNorm](this['get' + unitNorm]() + num); | this['set' + unitNorm](this['get' + unitNorm]() + num); | ||
Line 1,991: | Line 1,989: | ||
* @param {string} unit | * @param {string} unit | ||
* @throws If invalid or unsupported unit is given. | * @throws If invalid or unsupported unit is given. | ||
* @ | * @returns {Morebits.date} | ||
*/ | */ | ||
subtract: function(number, unit) { | subtract: function(number, unit) { | ||
Line 2,031: | Line 2,029: | ||
* @param {(string|number)} [zone=system] - `system` (for browser-default time zone), | * @param {(string|number)} [zone=system] - `system` (for browser-default time zone), | ||
* `utc`, or specify a time zone as number of minutes relative to UTC. | * `utc`, or specify a time zone as number of minutes relative to UTC. | ||
* @ | * @returns {string} | ||
*/ | */ | ||
format: function(formatstr, zone) { | format: function(formatstr, zone) { | ||
Line 2,037: | Line 2,035: | ||
return 'Invalid date'; // Put the truth out, preferable to "NaNNaNNan NaN:NaN" or whatever | return 'Invalid date'; // Put the truth out, preferable to "NaNNaNNan NaN:NaN" or whatever | ||
} | } | ||
var udate = this; | |||
// create a new date object that will contain the date to display as system time | // create a new date object that will contain the date to display as system time | ||
if (zone === 'utc') { | if (zone === 'utc') { | ||
Line 2,051: | Line 2,049: | ||
} | } | ||
var pad = function(num, len) { | |||
len = len || 2; // Up to length of 00 + 1 | len = len || 2; // Up to length of 00 + 1 | ||
return ('00' + num).toString().slice(0 - len); | return ('00' + num).toString().slice(0 - len); | ||
}; | }; | ||
var h24 = udate.getHours(), m = udate.getMinutes(), s = udate.getSeconds(), ms = udate.getMilliseconds(); | |||
var D = udate.getDate(), M = udate.getMonth() + 1, Y = udate.getFullYear(); | |||
var h12 = h24 % 12 || 12, amOrPm = h24 >= 12 ? msg('period-pm', 'PM') : msg('period-am', 'AM'); | |||
var replacementMap = { | |||
HH: pad(h24), H: h24, hh: pad(h12), h: h12, A: amOrPm, | HH: pad(h24), H: h24, hh: pad(h12), h: h12, A: amOrPm, | ||
mm: pad(m), m: m, | mm: pad(m), m: m, | ||
Line 2,069: | Line 2,067: | ||
}; | }; | ||
var unbinder = new Morebits.unbinder(formatstr); // escape stuff between [...] | |||
unbinder.unbind('\\[', '\\]'); | unbinder.unbind('\\[', '\\]'); | ||
unbinder.content = unbinder.content.replace( | unbinder.content = unbinder.content.replace( | ||
/* Regex notes: | /* Regex notes: | ||
* d(d{2,3})? matches exactly 1, 3 or 4 occurrences of 'd' ('dd' is treated as a double match of 'd') | |||
* Y{1,2}(Y{2})? matches exactly 1, 2 or 4 occurrences of 'Y' | |||
*/ | |||
/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, | /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, | ||
(match) | function(match) { | ||
return replacementMap[match]; | |||
} | |||
); | ); | ||
return unbinder.rebind().replace(/\[(.*?)\]/g, '$1'); | return unbinder.rebind().replace(/\[(.*?)\]/g, '$1'); | ||
Line 2,088: | Line 2,088: | ||
* @param {(string|number)} [zone=system] - 'system' (for browser-default time zone), | * @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. | * 'utc' (for UTC), or specify a time zone as number of minutes past UTC. | ||
* @ | * @returns {string} | ||
*/ | */ | ||
calendar: function(zone) { | calendar: function(zone) { | ||
// Zero out the hours, minutes, seconds and milliseconds - keeping only the date; | // Zero out the hours, minutes, seconds and milliseconds - keeping only the date; | ||
// find the difference. Note that setHours() returns the same thing as getTime(). | // find the difference. Note that setHours() returns the same thing as getTime(). | ||
var dateDiff = (new Date().setHours(0, 0, 0, 0) - | |||
new Date(this).setHours(0, 0, 0, 0)) / 8.64e7; | new Date(this).setHours(0, 0, 0, 0)) / 8.64e7; | ||
switch (true) { | switch (true) { | ||
Line 2,115: | Line 2,115: | ||
* as `==December 2019==` or `=== Jan 2018 ===`. | * as `==December 2019==` or `=== Jan 2018 ===`. | ||
* | * | ||
* @ | * @returns {RegExp} | ||
*/ | */ | ||
monthHeaderRegex: function() { | monthHeaderRegex: function() { | ||
Line 2,127: | Line 2,127: | ||
* @param {number} [level=2] - Header level. Pass 0 for just the text | * @param {number} [level=2] - Header level. Pass 0 for just the text | ||
* with no wikitext markers (==). | * with no wikitext markers (==). | ||
* @ | * @returns {string} | ||
*/ | */ | ||
monthHeader: function(level) { | monthHeader: function(level) { | ||
Line 2,134: | Line 2,134: | ||
level = isNaN(level) ? 2 : level; | level = isNaN(level) ? 2 : level; | ||
var header = Array(level + 1).join('='); // String.prototype.repeat not supported in IE 11 | |||
var text = this.getUTCMonthName() + ' ' + this.getUTCFullYear(); | |||
if (header.length) { // wikitext-formatted header | if (header.length) { // wikitext-formatted header | ||
Line 2,147: | Line 2,147: | ||
// Allow native Date.prototype methods to be used on Morebits.date objects | // Allow native Date.prototype methods to be used on Morebits.date objects | ||
Object.getOwnPropertyNames(Date.prototype).forEach((func) = | Object.getOwnPropertyNames(Date.prototype).forEach(function(func) { | ||
// Exclude methods that collide with PageTriage's Date.js external, which clobbers native Date: [[phab:T268513]] | |||
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 **************** */ | /* **************** Morebits.wiki **************** */ | ||
/** | /** | ||
* | * Useful classes for wiki editing and API access, in particular | ||
* {@link Morebits.wiki.api} and {@link Morebits.wiki.page}. | * {@link Morebits.wiki.api}, and {@link Morebits.wiki.page}, | ||
* and {@link Morebits.wiki.user}. | |||
* | * | ||
* @namespace Morebits.wiki | * @namespace Morebits.wiki | ||
Line 2,166: | Line 2,171: | ||
* @deprecated in favor of Morebits.isPageRedirect as of November 2020 | * @deprecated in favor of Morebits.isPageRedirect as of November 2020 | ||
* @memberof Morebits.wiki | * @memberof Morebits.wiki | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() { | Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() { | ||
Line 2,172: | Line 2,177: | ||
return Morebits.isPageRedirect(); | return Morebits.isPageRedirect(); | ||
}; | }; | ||
/* **************** Morebits.wiki.actionCompleted **************** */ | /* **************** Morebits.wiki.actionCompleted **************** */ | ||
Line 2,233: | Line 2,239: | ||
} | } | ||
} | } | ||
window.setTimeout(() | window.setTimeout(function() { | ||
window.location = Morebits.wiki.actionCompleted.redirect; | window.location = Morebits.wiki.actionCompleted.redirect; | ||
}, Morebits.wiki.actionCompleted.timeOut); | }, Morebits.wiki.actionCompleted.timeOut); | ||
Line 2,257: | Line 2,263: | ||
} | } | ||
}; | }; | ||
/* **************** Morebits.wiki.api **************** */ | /* **************** Morebits.wiki.api **************** */ | ||
Line 2,275: | Line 2,282: | ||
* @class | * @class | ||
* @param {string} currentAction - The current action (required). | * @param {string} currentAction - The current action (required). | ||
* @param { | * @param {object} query - The query (required). | ||
* @param {Function} [onSuccess] - The function to call when request is successful. | * @param {Function} [onSuccess] - The function to call when request is successful. | ||
* @param {Morebits.status} [statusElement] - A Morebits.status object to use for status messages. | * @param {Morebits.status} [statusElement] - A Morebits.status object to use for status messages. | ||
Line 2,285: | Line 2,292: | ||
this.query.assert = 'user'; | this.query.assert = 'user'; | ||
// Enforce newer error formats, preferring html | // Enforce newer error formats, preferring html | ||
if (!query.errorformat || | if (!query.errorformat || ['wikitext', 'plaintext'].indexOf(query.errorformat) === -1) { | ||
this.query.errorformat = 'html'; | this.query.errorformat = 'html'; | ||
} | } | ||
Line 2,306: | Line 2,313: | ||
} else if (query.format === 'json' && !query.formatversion) { | } else if (query.format === 'json' && !query.formatversion) { | ||
this.query.formatversion = '2'; | this.query.formatversion = '2'; | ||
} else if ( | } else if (['xml', 'json'].indexOf(query.format) === -1) { | ||
this.statelem.error('Invalid API format: only xml and json are supported.'); | this.statelem.error('Invalid API format: only xml and json are supported.'); | ||
} | } | ||
// Ignore tags for queries and most common unsupported actions, produces warnings | // Ignore tags for queries and most common unsupported actions, produces warnings | ||
if (query.action && ['query', 'review', 'stabilize', 'pagetriageaction', 'watch']. | if (query.action && ['query', 'review', 'stabilize', 'pagetriageaction', 'watch'].indexOf(query.action) !== -1) { | ||
delete query.tags; | delete query.tags; | ||
} else if (!query.tags && morebitsWikiChangeTag) { | } else if (!query.tags && morebitsWikiChangeTag) { | ||
Line 2,322: | Line 2,329: | ||
onSuccess: null, | onSuccess: null, | ||
onError: null, | onError: null, | ||
parent: window, // use global context if there is no parent object | parent: window, // use global context if there is no parent object | ||
query: null, | query: null, | ||
response: null, | response: null, | ||
responseXML: null, // use `response` instead; retained for backwards compatibility | responseXML: null, // use `response` instead; retained for backwards compatibility | ||
statelem: null, // this non-standard name kept for backwards compatibility | statelem: null, // this non-standard name kept for backwards compatibility | ||
statusText: null, // result received from the API, normally "success" or "error" | 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 | errorCode: null, // short text error code, if any, as documented in the MediaWiki API | ||
Line 2,350: | Line 2,357: | ||
* Carry out the request. | * Carry out the request. | ||
* | * | ||
* @param { | * @param {object} callerAjaxParameters - Do not specify a parameter unless you really | ||
* really want to give jQuery some extra parameters. | * really want to give jQuery some extra parameters. | ||
* @ | * @returns {promise} - A jQuery promise object that is resolved or rejected with the api object. | ||
*/ | */ | ||
post: function(callerAjaxParameters) { | post: function(callerAjaxParameters) { | ||
Line 2,358: | Line 2,365: | ||
++Morebits.wiki.numberOfActionsLeft; | ++Morebits.wiki.numberOfActionsLeft; | ||
var queryString = $.map(this.query, function(val, i) { | |||
if (Array.isArray(val)) { | if (Array.isArray(val)) { | ||
return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|'); | return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|'); | ||
Line 2,367: | Line 2,374: | ||
// token should always be the last item in the query string (bug TW-B-0013) | // token should always be the last item in the query string (bug TW-B-0013) | ||
var ajaxparams = $.extend({}, { | |||
context: this, | context: this, | ||
type: this.query.action === 'query' ? 'GET' : 'POST', | type: this.query.action === 'query' ? 'GET' : 'POST', | ||
Line 2,433: | Line 2,440: | ||
// Get a new CSRF token and retry. If the original action needs a different | // 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 | // type of action than CSRF, we do one pointless retry before bailing out | ||
return Morebits.wiki.api.getToken().then((token) | return Morebits.wiki.api.getToken().then(function(token) { | ||
this.query.token = token; | this.query.token = token; | ||
return this.post(callerAjaxParameters); | return this.post(callerAjaxParameters); | ||
}); | }.bind(this)); | ||
} | } | ||
Line 2,473: | Line 2,480: | ||
} | } | ||
}; | }; | ||
Line 2,512: | Line 2,499: | ||
morebitsWikiApiUserAgent = (ua ? ua + ' ' : '') + 'morebits.js ([[w:WT:TW]])'; | morebitsWikiApiUserAgent = (ua ? ua + ' ' : '') + 'morebits.js ([[w:WT:TW]])'; | ||
}; | }; | ||
/** | /** | ||
Line 2,522: | Line 2,511: | ||
*/ | */ | ||
var morebitsWikiChangeTag = ''; | var morebitsWikiChangeTag = ''; | ||
/** | /** | ||
Line 2,527: | Line 2,517: | ||
* | * | ||
* @memberof Morebits.wiki.api | * @memberof Morebits.wiki.api | ||
* @ | * @returns {string} MediaWiki CSRF token. | ||
*/ | */ | ||
Morebits.wiki.api.getToken = function() { | Morebits.wiki.api.getToken = function() { | ||
var tokenApi = new Morebits.wiki.api(msg('getting-token', 'Getting token'), { | |||
action: 'query', | action: 'query', | ||
meta: 'tokens', | meta: 'tokens', | ||
Line 2,536: | Line 2,526: | ||
format: 'json' | format: 'json' | ||
}); | }); | ||
return tokenApi.post().then((apiobj) | return tokenApi.post().then(function(apiobj) { | ||
return apiobj.response.query.tokens.csrftoken; | |||
}); | |||
}; | }; | ||
/* **************** Morebits.wiki.page **************** */ | /* **************** Morebits.wiki.page **************** */ | ||
Line 2,578: | Line 2,571: | ||
* 2. The sequence for append/prepend/newSection could be slightly shortened, | * 2. The sequence for append/prepend/newSection could be slightly shortened, | ||
* but it would require significant duplication of code for little benefit. | * but it would require significant duplication of code for little benefit. | ||
* | |||
* | * | ||
* @memberof Morebits.wiki | * @memberof Morebits.wiki | ||
Line 2,600: | Line 2,594: | ||
* @private | * @private | ||
*/ | */ | ||
var ctx = { | |||
// backing fields for public properties | // backing fields for public properties | ||
pageName: pageName, | pageName: pageName, | ||
Line 2,606: | Line 2,600: | ||
editSummary: null, | editSummary: null, | ||
changeTags: null, | changeTags: null, | ||
testActions: null, // array if any valid actions | testActions: null, // array if any valid actions | ||
callbackParameters: null, | callbackParameters: null, | ||
statusElement: status instanceof Morebits.status ? status : new Morebits.status(status), | statusElement: status instanceof Morebits.status ? status : new Morebits.status(status), | ||
Line 2,612: | Line 2,606: | ||
// - edit | // - edit | ||
pageText: null, | pageText: null, | ||
editMode: 'all', // save() replaces entire contents of the page by default | 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 | 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 | prependText: null, // can't reuse pageText for this because pageText is needed to follow a redirect | ||
newSectionText: null, | newSectionText: null, | ||
newSectionTitle: null, | newSectionTitle: null, | ||
Line 2,627: | Line 2,621: | ||
watchlistOption: 'nochange', | watchlistOption: 'nochange', | ||
watchlistExpiry: null, | watchlistExpiry: null, | ||
creator: null, | creator: null, | ||
creationTimestamp: null, | |||
// - revert | // - revert | ||
Line 2,644: | Line 2,639: | ||
protectCreate: null, | protectCreate: null, | ||
protectCascade: null, | protectCascade: null, | ||
// - creation lookup | // - creation lookup | ||
Line 2,661: | Line 2,650: | ||
csrfToken: null, | csrfToken: null, | ||
loadTime: null, | loadTime: null, | ||
lastTouchedTime: null, | |||
pageID: null, | pageID: null, | ||
contentModel: null, | contentModel: null, | ||
latestRevID: null, | |||
revertUser: null, | revertUser: null, | ||
watched: false, | watched: false, | ||
Line 2,694: | Line 2,683: | ||
loadApi: null, | loadApi: null, | ||
saveApi: null, | saveApi: null, | ||
saveResponse: null, | |||
lookupCreationApi: null, | lookupCreationApi: null, | ||
moveApi: null, | moveApi: null, | ||
Line 2,712: | Line 2,702: | ||
}; | }; | ||
var emptyFunction = function() { }; | |||
/** | /** | ||
Line 2,745: | Line 2,735: | ||
if (ctx.editMode === 'all') { | if (ctx.editMode === 'all') { | ||
// get the page content at the same time, if needed | |||
ctx.loadQuery.rvprop = 'content'; | |||
} else if (ctx.editMode === 'revert') { | } else if (ctx.editMode === 'revert') { | ||
ctx.loadQuery.rvprop = ' | // We're mainly just interested in the user, but this is a potential area for expansion, | ||
// such as the content of the old revision or multiple revisions to process. | |||
ctx.loadQuery.rvprop = 'ids|user'; | |||
ctx.loadQuery.rvlimit = 1; | ctx.loadQuery.rvlimit = 1; | ||
ctx.loadQuery.rvstartid = ctx.revertOldID; | ctx.loadQuery.rvstartid = ctx.revertOldID; | ||
Line 2,753: | Line 2,746: | ||
if (ctx.followRedirect) { | if (ctx.followRedirect) { | ||
ctx.loadQuery.redirects = ''; // follow all redirects | ctx.loadQuery.redirects = ''; // follow all redirects | ||
} | } | ||
if (typeof ctx.pageSection === 'number') { | if (typeof ctx.pageSection === 'number') { | ||
Line 2,785: | Line 2,778: | ||
// are we getting our editing token from mw.user.tokens? | // are we getting our editing token from mw.user.tokens? | ||
var canUseMwUserToken = fnCanUseMwUserToken('edit'); | |||
if (!ctx.pageLoaded && !canUseMwUserToken) { | if (!ctx.pageLoaded && !canUseMwUserToken) { | ||
Line 2,793: | Line 2,786: | ||
} | } | ||
if (!ctx.editSummary) { | if (!ctx.editSummary) { | ||
if (ctx.editMode === 'new' && ctx.newSectionTitle) { | if (ctx.editMode === 'new' && ctx.newSectionTitle) { | ||
// new section mode allows (nay, encourages) using the | |||
// title as the edit summary, but the query needs | |||
// editSummary to be undefined or '', not null | |||
ctx.editSummary = ''; | ctx.editSummary = ''; | ||
} else if (ctx.editMode === 'revert') { | |||
// Default reversion edit summary | |||
ctx.editSummary = msg('revert-summary', | |||
ctx.revertOldID, ctx.revertUser || msg('hidden-user'), | |||
'Restored revision ' + ctx.revertOldID + ' by ' + (ctx.revertUser || 'an unknown user') | |||
); | |||
} else { | } else { | ||
ctx.statusElement.error('Internal error: edit summary not set before save!'); | ctx.statusElement.error('Internal error: edit summary not set before save!'); | ||
Line 2,808: | Line 2,807: | ||
if (ctx.fullyProtected && !ctx.suppressProtectWarning && | if (ctx.fullyProtected && !ctx.suppressProtectWarning && | ||
!confirm( | !confirm( | ||
ctx.fullyProtected === 'infinity' | ctx.fullyProtected === 'infinity' | ||
msg('protected-indef-edit-warning', ctx.pageName, | ? msg('protected-indef-edit-warning', ctx.pageName, | ||
'You are about to make an edit to the fully protected page "' + ctx.pageName + '" (protected indefinitely). \n\nClick OK to proceed with the edit, or Cancel to skip this edit.' | |||
) | ) | ||
msg('protected-edit-warning', ctx.pageName, ctx.fullyProtected, | : 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.' | '" (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,825: | Line 2,824: | ||
ctx.retries = 0; | ctx.retries = 0; | ||
var query = { | |||
action: 'edit', | action: 'edit', | ||
title: ctx.pageName, | title: ctx.pageName, | ||
Line 2,849: | Line 2,848: | ||
query.minor = true; | query.minor = true; | ||
} else { | } else { | ||
query.notminor = true; // force Twinkle config to override user preference setting for "all edits are minor" | query.notminor = true; // force Twinkle config to override user preference setting for "all edits are minor" | ||
} | } | ||
Line 2,864: | Line 2,863: | ||
return; | return; | ||
} | } | ||
query.appendtext = ctx.appendText; // use mode to append to current page contents | query.appendtext = ctx.appendText; // use mode to append to current page contents | ||
break; | break; | ||
case 'prepend': | case 'prepend': | ||
Line 2,872: | Line 2,871: | ||
return; | return; | ||
} | } | ||
query.prependtext = ctx.prependText; // use mode to prepend to current page contents | query.prependtext = ctx.prependText; // use mode to prepend to current page contents | ||
break; | break; | ||
case 'new': | case 'new': | ||
Line 2,881: | Line 2,880: | ||
} | } | ||
query.section = 'new'; | query.section = 'new'; | ||
query.text = ctx.newSectionText; // add a new section to current page | 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 | query.sectiontitle = ctx.newSectionTitle || ctx.editSummary; // done by the API, but non-'' values would get treated as text | ||
break; | break; | ||
case 'revert': | case 'revert': | ||
query.undo = ctx. | if (!ctx.revertOldID) { | ||
query.undoafter = ctx.revertOldID; | ctx.statusElement.error('Internal error: revision ID to revert to was not set before save!'); | ||
if (ctx. | ctx.onSaveFailure(this); | ||
query.basetimestamp = ctx. | return; | ||
} | |||
query.undo = ctx.latestRevID; // Undo this revision | |||
query.undoafter = ctx.revertOldID; // Revert all revisions from undo to this, restoring this revision | |||
// check that page hasn't been edited since it was loaded | |||
if (ctx.lastTouchedTime) { | |||
query.basetimestamp = ctx.lastTouchedTime; | |||
} | } | ||
query.baserevid = ctx.latestRevID; | |||
query.starttimestamp = ctx.loadTime; // check that page hasn't been deleted since it was loaded (don't recreate bad stuff) | query.starttimestamp = ctx.loadTime; // check that page hasn't been deleted since it was loaded (don't recreate bad stuff) | ||
break; | break; | ||
default: // 'all' | default: // 'all' | ||
query.text = ctx.pageText; // replace entire contents of the page | query.text = ctx.pageText; // replace entire contents of the page | ||
if (ctx. | // check that page hasn't been edited since it was loaded | ||
query.basetimestamp = ctx. | if (ctx.lastTouchedTime) { | ||
query.basetimestamp = ctx.lastTouchedTime; | |||
} | |||
if (ctx.latestRevID) { | |||
query.baserevid = ctx.latestRevID; | |||
} | } | ||
query.starttimestamp = ctx.loadTime; // check that page hasn't been deleted since it was loaded (don't recreate bad stuff) | query.starttimestamp = ctx.loadTime; // check that page hasn't been deleted since it was loaded (don't recreate bad stuff) | ||
Line 2,901: | Line 2,911: | ||
} | } | ||
if (['recreate', 'createonly', 'nocreate']. | if (['recreate', 'createonly', 'nocreate'].indexOf(ctx.createOption) !== -1) { | ||
query[ctx.createOption] = ''; | query[ctx.createOption] = ''; | ||
} | } | ||
Line 2,977: | Line 2,987: | ||
}; | }; | ||
/** @ | /** @returns {string} The name of the loaded page, including the namespace */ | ||
this.getPageName = function() { | this.getPageName = function() { | ||
return ctx.pageName; | return ctx.pageName; | ||
}; | }; | ||
/** @ | /** @returns {string} The text of the page after a successful load() */ | ||
this.getPageText = function() { | this.getPageText = function() { | ||
return ctx.pageText; | return ctx.pageText; | ||
Line 3,019: | Line 3,029: | ||
ctx.newSectionTitle = newSectionTitle; | ctx.newSectionTitle = newSectionTitle; | ||
}; | }; | ||
/** | |||
* Get the post-save response object from the API. | |||
* | |||
* @returns {object} | |||
*/ | |||
this.getSaveResponse = function() { | |||
return ctx.saveResponse; | |||
}; | |||
// Edit-related setter methods: | // Edit-related setter methods: | ||
/** | /** | ||
* Set the edit summary that will be used when `save()` is called. | * Set the edit summary that will be used when `save()` is called. | ||
* Unnecessary if editMode is | * Unnecessary if editMode is `new` ({@link Morebits.wiki.page#newSection}) | ||
* and `newSectionTitle` is provided, or if editMode is `revert` | |||
* ({@link Morebits.wiki.page#revert}). | |||
* | * | ||
* @param {string} summary | * @param {string} summary | ||
Line 3,042: | Line 3,064: | ||
ctx.changeTags = tags; | ctx.changeTags = tags; | ||
}; | }; | ||
/** | /** | ||
Line 3,051: | Line 3,074: | ||
* - `null`: create the page if it does not exist, unless it was deleted | * - `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). | * in the moment between loading the page and saving the edit (default). | ||
* | |||
*/ | */ | ||
this.setCreateOption = function(createOption) { | this.setCreateOption = function(createOption) { | ||
Line 3,296: | Line 3,320: | ||
}; | }; | ||
/** @returns {string} The most current revision ID of the page */ | |||
/** @ | this.getCurrentID = function() { | ||
this. | return ctx.latestRevID; | ||
ctx. | |||
}; | }; | ||
/** @returns {string} ISO 8601 timestamp at which the page was last edited or modified. */ | |||
/** @ | this.getLastEditTime = function() { | ||
this. | return ctx.lastTouchedTime; | ||
ctx. | |||
}; | }; | ||
// Revert-related getters/setters: | // Revert-related getters/setters: | ||
/** | |||
* Set the revision to which the page should be restored. For | |||
* the `revert` mode. | |||
* | |||
* @param {string|number} oldID | |||
*/ | |||
this.setOldID = function(oldID) { | this.setOldID = function(oldID) { | ||
ctx.editMode = 'revert'; | |||
ctx.revertOldID = oldID; | ctx.revertOldID = oldID; | ||
}; | }; | ||
/** @ | /** @returns {string} ID of the fetched revision. Only available for the `revert` edit mode. */ | ||
this. | this.getRevisionID = function() { | ||
return ctx. | return ctx.revertOldID; | ||
}; | }; | ||
/** @returns {string} Editor of the fetched revision. Only available for the `revert` edit mode. */ | |||
/** @ | |||
this.getRevisionUser = function() { | this.getRevisionUser = function() { | ||
return ctx.revertUser; | return ctx.revertUser; | ||
}; | }; | ||
Line 3,340: | Line 3,363: | ||
* detected upon calling `save()`. | * detected upon calling `save()`. | ||
* | * | ||
* @param { | * @param {object} callbackParameters | ||
*/ | */ | ||
this.setCallbackParameters = function(callbackParameters) { | this.setCallbackParameters = function(callbackParameters) { | ||
Line 3,347: | Line 3,370: | ||
/** | /** | ||
* @ | * @returns {object} - The object previously set by `setCallbackParameters()`. | ||
*/ | */ | ||
this.getCallbackParameters = function() { | this.getCallbackParameters = function() { | ||
Line 3,361: | Line 3,384: | ||
/** | /** | ||
* @ | * @returns {Morebits.status} Status element created by the constructor. | ||
*/ | */ | ||
this.getStatusElement = function() { | this.getStatusElement = function() { | ||
Line 3,377: | Line 3,400: | ||
/** | /** | ||
* @ | * @returns {boolean} True if the page existed on the wiki when it was last loaded. | ||
*/ | */ | ||
this.exists = function() { | this.exists = function() { | ||
Line 3,384: | Line 3,407: | ||
/** | /** | ||
* @ | * @returns {string} Page ID of the page loaded. 0 if the page doesn't | ||
* exist. | * exist. | ||
*/ | */ | ||
Line 3,392: | Line 3,415: | ||
/** | /** | ||
* @ | * @returns {string} - Content model of the page. Possible values | ||
* include (but may not be limited to): `wikitext`, `javascript`, | * include (but may not be limited to): `wikitext`, `javascript`, | ||
* `css`, `json`, `Scribunto`, `sanitized-css`, `MassMessageListContent`. | * `css`, `json`, `Scribunto`, `sanitized-css`, `MassMessageListContent`. | ||
Line 3,402: | Line 3,425: | ||
/** | /** | ||
* @ | * @returns {boolean|string} - Watched status of the page. Boolean | ||
* unless it's being watched temporarily, in which case returns the | * unless it's being watched temporarily, in which case returns the | ||
* expiry string. | * expiry string. | ||
Line 3,411: | Line 3,434: | ||
/** | /** | ||
* @ | * @returns {string} ISO 8601 timestamp at which the page was last loaded. | ||
*/ | */ | ||
this.getLoadTime = function() { | this.getLoadTime = function() { | ||
Line 3,418: | Line 3,441: | ||
/** | /** | ||
* @ | * @returns {string} The user who created the page following `lookupCreation()`. | ||
*/ | */ | ||
this.getCreator = function() { | this.getCreator = function() { | ||
Line 3,425: | Line 3,448: | ||
/** | /** | ||
* @ | * @returns {string} The ISOString timestamp of page creation following `lookupCreation()`. | ||
*/ | */ | ||
this.getCreationTimestamp = function() { | this.getCreationTimestamp = function() { | ||
return ctx. | return ctx.creationTimestamp; | ||
}; | }; | ||
/** @ | /** @returns {boolean} whether or not you can edit the page */ | ||
this.canEdit = function() { | this.canEdit = function() { | ||
return !!ctx.testActions && ctx.testActions. | return !!ctx.testActions && ctx.testActions.indexOf('edit') !== -1; | ||
}; | }; | ||
Line 3,457: | Line 3,480: | ||
} | } | ||
var query = { | |||
action: 'query', | action: 'query', | ||
prop: 'revisions', | prop: 'revisions', | ||
Line 3,478: | Line 3,501: | ||
if (ctx.followRedirect) { | if (ctx.followRedirect) { | ||
query.redirects = ''; // follow all redirects | query.redirects = ''; // follow all redirects | ||
} | } | ||
Line 3,487: | Line 3,510: | ||
/** | /** | ||
* Reverts a page to ` | * Reverts a page to the revision set by `setOldID`. Does not require | ||
* loading the page beforehand, but always requires `setOldID`. Can | |||
* provide a default edit summary. | |||
* | * | ||
* @param {Function} [onSuccess] - Callback function to run on success. | * @param {Function} [onSuccess] - Callback function to run on success. | ||
Line 3,493: | Line 3,518: | ||
*/ | */ | ||
this.revert = function(onSuccess, onFailure) { | this.revert = function(onSuccess, onFailure) { | ||
ctx. | ctx.editMode = 'revert'; | ||
if ( | if (ctx.pageLoaded) { | ||
this.save(onSuccess, onFailure); | |||
ctx.onSaveFailure | } else { | ||
ctx.onSaveSuccess = onSuccess; | |||
ctx.onSaveFailure = onFailure || emptyFunction; | |||
this.load(fnAutoSave, ctx.onSaveFailure); | |||
} | } | ||
}; | }; | ||
Line 3,529: | Line 3,552: | ||
fnProcessMove.call(this, this); | fnProcessMove.call(this, this); | ||
} else { | } else { | ||
var query = fnNeedTokenInfoQuery('move'); | |||
ctx.moveApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure); | ctx.moveApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure); | ||
Line 3,553: | Line 3,576: | ||
// If a link is present, don't need to check if it's patrolled | // If a link is present, don't need to check if it's patrolled | ||
if ($('.patrollink').length) { | if ($('.patrollink').length) { | ||
var patrolhref = $('.patrollink a').attr('href'); | |||
ctx.rcid = mw.util.getParamValue('rcid', patrolhref); | ctx.rcid = mw.util.getParamValue('rcid', patrolhref); | ||
fnProcessPatrol(this, this); | fnProcessPatrol(this, this); | ||
} else { | } else { | ||
var patrolQuery = { | |||
action: 'query', | action: 'query', | ||
prop: 'info', | prop: 'info', | ||
Line 3,595: | Line 3,618: | ||
this.triage = function() { | this.triage = function() { | ||
// Fall back to patrol if not a valid triage namespace | // Fall back to patrol if not a valid triage namespace | ||
if ( | if (mw.config.get('pageTriageNamespaces').indexOf(new mw.Title(ctx.pageName).getNamespaceId()) === -1) { | ||
this.patrol(); | this.patrol(); | ||
} else { | } else { | ||
Line 3,607: | Line 3,630: | ||
fnProcessTriageList(this, this); | fnProcessTriageList(this, this); | ||
} else { | } else { | ||
var query = fnNeedTokenInfoQuery('triage'); | |||
ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList); | ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList); | ||
Line 3,634: | Line 3,657: | ||
fnProcessDelete.call(this, this); | fnProcessDelete.call(this, this); | ||
} else { | } else { | ||
var query = fnNeedTokenInfoQuery('delete'); | |||
ctx.deleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure); | ctx.deleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure); | ||
Line 3,659: | Line 3,682: | ||
fnProcessUndelete.call(this, this); | fnProcessUndelete.call(this, this); | ||
} else { | } else { | ||
var query = fnNeedTokenInfoQuery('undelete'); | |||
ctx.undeleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure); | ctx.undeleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure); | ||
Line 3,690: | Line 3,713: | ||
// (absolute, not differential), we always need to request | // (absolute, not differential), we always need to request | ||
// protection levels from the server | // protection levels from the server | ||
var query = fnNeedTokenInfoQuery('protect'); | |||
ctx.protectApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure); | ctx.protectApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure); | ||
Line 3,725: | Line 3,748: | ||
fnProcessStabilize.call(this, this); | fnProcessStabilize.call(this, this); | ||
} else { | } else { | ||
var query = fnNeedTokenInfoQuery('stabilize'); | |||
ctx.stabilizeApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure); | ctx.stabilizeApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure); | ||
Line 3,734: | Line 3,757: | ||
/* | /* | ||
* Private member functions | |||
* These are not exposed outside | |||
*/ | |||
/** | /** | ||
Line 3,749: | Line 3,772: | ||
* @param {string} [action=edit] - The action being undertaken, e.g. | * @param {string} [action=edit] - The action being undertaken, e.g. | ||
* "edit" or "delete". In practice, only "edit" or "notedit" matters. | * "edit" or "delete". In practice, only "edit" or "notedit" matters. | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
var fnCanUseMwUserToken = function(action = 'edit' | var fnCanUseMwUserToken = function(action) { | ||
action = typeof action !== 'undefined' ? action : 'edit'; // IE doesn't support default parameters | |||
// If a watchlist expiry is set, we must always load the page | // If a watchlist expiry is set, we must always load the page | ||
// to avoid overwriting indefinite protection. Of course, not | // to avoid overwriting indefinite protection. Of course, not | ||
Line 3,778: | Line 3,803: | ||
// wgRestrictionEdit is null on non-existent pages, | // wgRestrictionEdit is null on non-existent pages, | ||
// so this neatly handles nonexistent pages | // so this neatly handles nonexistent pages | ||
var editRestriction = mw.config.get('wgRestrictionEdit'); | |||
if (!editRestriction || editRestriction. | if (!editRestriction || editRestriction.indexOf('sysop') !== -1) { | ||
return false; | return false; | ||
} | } | ||
Line 3,800: | Line 3,825: | ||
* @param {string} action - The action being undertaken, e.g. "edit" or | * @param {string} action - The action being undertaken, e.g. "edit" or | ||
* "delete". | * "delete". | ||
* @ | * @returns {object} Appropriate query. | ||
*/ | */ | ||
var fnNeedTokenInfoQuery = function(action) { | var fnNeedTokenInfoQuery = function(action) { | ||
var query = { | |||
action: 'query', | action: 'query', | ||
meta: 'tokens', | meta: 'tokens', | ||
Line 3,829: | Line 3,854: | ||
// callback from loadApi.post() | // callback from loadApi.post() | ||
var fnLoadSuccess = function() { | var fnLoadSuccess = function() { | ||
var response = ctx.loadApi.getResponse().query; | |||
if (!fnCheckPageName(response, ctx.onLoadFailure)) { | if (!fnCheckPageName(response, ctx.onLoadFailure)) { | ||
Line 3,835: | Line 3,860: | ||
} | } | ||
var page = response.pages[0], rev; | |||
ctx.pageExists = !page.missing; | ctx.pageExists = !page.missing; | ||
if (ctx.pageExists) { | if (ctx.pageExists) { | ||
ctx.pageID = page.pageid; | |||
ctx.lastTouchedTime = page.touched; // Used as basetimestamp when saving | |||
// Only actually required for revert editMode, but used for | |||
// edit conflict detection and accessible to all via getCurrentID | |||
ctx.latestRevID = page.lastrevid; | |||
rev = page.revisions[0]; | rev = page.revisions[0]; | ||
ctx. | if (ctx.editMode === 'revert') { | ||
// Is this ever even possible? | |||
ctx. | if (rev.revid !== ctx.revertOldID) { | ||
ctx.statusElement.error(msg('revert-mismatch', 'The retrieved revision does not match the requested revision.')); | |||
ctx.onLoadFailure(this); | |||
return; | |||
} | |||
if (!ctx.latestRevID) { | |||
ctx.statusElement.error(msg('revert-curid-fail', 'Failed to retrieve current revision ID.')); | |||
ctx.onLoadFailure(this); | |||
return; | |||
} | |||
if (!rev.userhidden) { // ensure username wasn't RevDel'd or oversighted | |||
ctx.revertUser = rev.user; | |||
if (!ctx.revertUser) { | |||
ctx.statusElement.error(msg('revert-user-fail', 'Failed to retrieve user who made the revision.')); | |||
ctx.onLoadFailure(this); | |||
return; | |||
} | |||
} | |||
} else { | |||
ctx.pageText = rev.content; | |||
} | |||
} else { | } else { | ||
ctx.pageText = ''; // allow for concatenation, etc. | ctx.pageText = ''; // allow for concatenation, etc. | ||
ctx.pageID = 0; // nonexistent in response, matches wgArticleId | ctx.pageID = 0; // nonexistent in response, matches wgArticleId | ||
} | } | ||
Line 3,866: | Line 3,916: | ||
// Includes cascading protection | // Includes cascading protection | ||
if (Morebits.userIsSysop) { | if (Morebits.userIsSysop) { | ||
var editProt = page.protection.filter(function(pr) { | |||
return pr.type === 'edit' && pr.level === 'sysop'; | |||
}).pop(); | |||
if (editProt) { | if (editProt) { | ||
ctx.fullyProtected = editProt.expiry; | ctx.fullyProtected = editProt.expiry; | ||
Line 3,874: | Line 3,926: | ||
} | } | ||
var testactions = page.actions; | |||
ctx.testActions = []; // was null | ctx.testActions = []; // was null | ||
Object.keys(testactions).forEach((action) | Object.keys(testactions).forEach(function(action) { | ||
if (testactions[action]) { | if (testactions[action]) { | ||
ctx.testActions.push(action); | ctx.testActions.push(action); | ||
} | } | ||
}); | }); | ||
ctx.pageLoaded = true; | ctx.pageLoaded = true; | ||
// alert("Generate edit conflict now"); // for testing edit conflict recovery logic | // alert("Generate edit conflict now"); // for testing edit conflict recovery logic | ||
ctx.onLoadSuccess(this); // invoke callback | ctx.onLoadSuccess(this); // invoke callback | ||
}; | }; | ||
Line 3,917: | Line 3,945: | ||
} | } | ||
var page = response.pages && response.pages[0]; | |||
if (page) { | if (page) { | ||
// check for invalid titles | // check for invalid titles | ||
Line 3,927: | Line 3,955: | ||
// retrieve actual title of the page after normalization and redirects | // retrieve actual title of the page after normalization and redirects | ||
var resolvedName = page.title; | |||
if (response.redirects) { | if (response.redirects) { | ||
// check for cross-namespace redirect: | // check for cross-namespace redirect: | ||
var origNs = new mw.Title(ctx.pageName).namespace; | |||
var newNs = new mw.Title(resolvedName).namespace; | |||
if (origNs !== newNs && !ctx.followCrossNsRedirect) { | 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')); | ctx.statusElement.error(msg('cross-redirect-abort', ctx.pageName, resolvedName, ctx.pageName + ' is a cross-namespace redirect to ' + resolvedName + ', aborted')); | ||
Line 3,966: | Line 3,994: | ||
* ensured of knowing the watch status by the use of this. | * ensured of knowing the watch status by the use of this. | ||
* | * | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
var fnApplyWatchlistExpiry = function() { | var fnApplyWatchlistExpiry = function() { | ||
Line 3,973: | Line 4,001: | ||
return true; | return true; | ||
} else if (typeof ctx.watched === 'string') { | } else if (typeof ctx.watched === 'string') { | ||
var newExpiry; | |||
// Attempt to determine if the new expiry is a | // Attempt to determine if the new expiry is a | ||
// relative (e.g. `1 month`) or absolute datetime | // relative (e.g. `1 month`) or absolute datetime | ||
var rel = ctx.watchlistExpiry.split(' '); | |||
try { | try { | ||
newExpiry = new Morebits.date().add(rel[0], rel[1]); | newExpiry = new Morebits.date().add(rel[0], rel[1]); | ||
Line 4,001: | Line 4,029: | ||
// callback from saveApi.post() | // callback from saveApi.post() | ||
var fnSaveSuccess = function() { | var fnSaveSuccess = function() { | ||
ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes | ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes | ||
ctx.saveResponse = ctx.saveApi.getResponse(); | |||
var edit = ctx.saveResponse.edit; | |||
// see if the API thinks we were successful | // see if the API thinks we were successful | ||
if ( | if (edit.nochange) { | ||
// nochange treated as a "successful" result | |||
ctx.statusElement.error('Could not save the page because the provided content was identical to the current revision.'); | |||
} else if (edit.result === 'Success') { | |||
// real success | // real success | ||
// default on success action - display link for edited page | // default on success action - display link for edited page | ||
var link = document.createElement('a'); | |||
link.setAttribute('href', mw.util.getUrl(ctx.pageName)); | link.setAttribute('href', mw.util.getUrl(ctx.pageName)); | ||
link.appendChild(document.createTextNode(ctx.pageName)); | link.appendChild(document.createTextNode(ctx.pageName)); | ||
ctx.statusElement.info(['completed (', link, ')']); | ctx.statusElement.info(['completed (', link, ')']); | ||
if (ctx.onSaveSuccess) { | if (ctx.onSaveSuccess) { | ||
ctx.onSaveSuccess(this); // invoke callback | ctx.onSaveSuccess(this); // invoke callback | ||
} | } | ||
return; | return; | ||
} | } else if (edit.captcha) { | ||
// errors here are only generated by extensions which hook APIEditBeforeSave within MediaWiki, | |||
// which as of 1.34.0-wmf.23 (Sept 2019) should only encompass captcha messages | |||
ctx.statusElement.error('Could not save the page because the wiki server wanted you to fill out a CAPTCHA.'); | ctx.statusElement.error('Could not save the page because the wiki server wanted you to fill out a CAPTCHA.'); | ||
} else { | } else { | ||
Line 4,035: | Line 4,064: | ||
// callback from saveApi.post() | // callback from saveApi.post() | ||
var fnSaveError = function() { | var fnSaveError = function() { | ||
ctx.saveResponse = ctx.saveApi.getResponse(); | |||
var errorCode = ctx.saveApi.getErrorCode(); | |||
// check for edit conflict | // check for edit conflict | ||
Line 4,041: | Line 4,071: | ||
// edit conflicts can occur when the page needs to be purged from the server cache | // edit conflicts can occur when the page needs to be purged from the server cache | ||
var purgeQuery = { | |||
action: 'purge', | action: 'purge', | ||
titles: ctx.pageName // redirects are already resolved | titles: ctx.pageName // redirects are already resolved | ||
}; | }; | ||
var 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 | --Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds | ||
ctx.statusElement.info(msg('editconflict-retrying', 'Edit conflict detected, reapplying edit')); | ctx.statusElement.info(msg('editconflict-retrying', 'Edit conflict detected, reapplying edit')); | ||
Line 4,055: | Line 4,085: | ||
ctx.loadApi.post(); // reload the page and reapply the edit | ctx.loadApi.post(); // reload the page and reapply the edit | ||
} | } | ||
} | }, ctx.statusElement); | ||
purgeApi.post(); | purgeApi.post(); | ||
// check for network or server error | |||
} else if ((errorCode === null || errorCode === undefined) && ctx.retries++ < ctx.maxRetries) { | } else if ((errorCode === null || errorCode === undefined) && ctx.retries++ < ctx.maxRetries) { | ||
// the error might be transient, so try again | // the error might be transient, so try again | ||
ctx.statusElement.info(msg('save-failed-retrying', 2, 'Save failed, retrying in 2 seconds ...')); | ctx.statusElement.info(msg('save-failed-retrying', 2, 'Save failed, retrying in 2 seconds ...')); | ||
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds | --Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds | ||
// wait for sometime for client to regain connectivity | // wait for sometime for client to regain connectivity | ||
sleep(2000).then(() | sleep(2000).then(function() { | ||
ctx.saveApi.post(); // give it another go! | ctx.saveApi.post(); // give it another go! | ||
}); | }); | ||
// hard error, give up | |||
} else { | } else { | ||
switch (errorCode) { | switch (errorCode) { | ||
Line 4,084: | Line 4,111: | ||
case 'abusefilter-disallowed': | case 'abusefilter-disallowed': | ||
ctx.statusElement.error('The edit was disallowed by the edit filter: "' + | ctx.statusElement.error('The edit was disallowed by the edit filter: "' + ctx.saveApi.getResponse().error.abusefilter.description + '".'); | ||
break; | break; | ||
case 'abusefilter-warning': | case 'abusefilter-warning': | ||
ctx.statusElement.error([ 'A warning was returned by the edit filter: "', | ctx.statusElement.error([ 'A warning was returned by the edit filter: "', ctx.saveApi.getResponse().error.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 - | // 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 | // I can't see how to do this without creating a UI dependency on Morebits.wiki.page though -- TTO | ||
Line 4,095: | Line 4,122: | ||
case 'spamblacklist': | case 'spamblacklist': | ||
// If multiple items are blacklisted, we only return the first | // If multiple items are blacklisted, we only return the first | ||
var spam = | var spam = ctx.saveApi.getResponse().error.spamblacklist.matches[0]; | ||
ctx.statusElement.error('Could not save the page because the URL ' + spam + ' is on the spam blacklist'); | ctx.statusElement.error('Could not save the page because the URL ' + spam + ' is on the spam blacklist'); | ||
break; | break; | ||
Line 4,103: | Line 4,130: | ||
} | } | ||
ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes | ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes | ||
if (ctx.onSaveFailure) { | if (ctx.onSaveFailure) { | ||
ctx.onSaveFailure(this); // invoke callback | ctx.onSaveFailure(this); // invoke callback | ||
} | } | ||
} | } | ||
}; | }; | ||
var isTextRedirect = function(text) { | |||
if (!text) { // no text - content empty or inaccessible (revdelled or suppressed) | if (!text) { // no text - content empty or inaccessible (revdelled or suppressed) | ||
return false; | return false; | ||
} | } | ||
return Morebits.l10n.redirectTagAliases.some((tag) | return Morebits.l10n.redirectTagAliases.some(function(tag) { | ||
return new RegExp('^\\s*' + tag + '\\W', 'i').test(text); | |||
}); | |||
}; | }; | ||
var fnLookupCreationSuccess = function() { | var fnLookupCreationSuccess = function() { | ||
var response = ctx.lookupCreationApi.getResponse().query; | |||
if (!fnCheckPageName(response, ctx.onLookupCreationFailure)) { | if (!fnCheckPageName(response, ctx.onLookupCreationFailure)) { | ||
Line 4,124: | Line 4,153: | ||
} | } | ||
var rev = response.pages[0].revisions && response.pages[0].revisions[0]; | |||
if (!rev) { | if (!rev) { | ||
ctx.statusElement.error('Could not find any revisions of ' + ctx.pageName); | ctx.statusElement.error('Could not find any revisions of ' + ctx.pageName); | ||
Line 4,139: | Line 4,168: | ||
return; | return; | ||
} | } | ||
ctx. | ctx.creationTimestamp = rev.timestamp; | ||
if (!ctx. | if (!ctx.creationTimestamp) { | ||
ctx.statusElement.error('Could not find timestamp of page creation'); | ctx.statusElement.error('Could not find timestamp of page creation'); | ||
ctx.onLookupCreationFailure(this); | ctx.onLookupCreationFailure(this); | ||
Line 4,161: | Line 4,190: | ||
var fnLookupNonRedirectCreator = function() { | var fnLookupNonRedirectCreator = function() { | ||
var response = ctx.lookupCreationApi.getResponse().query; | |||
var revs = response.pages[0].revisions; | |||
for ( | for (var i = 0; i < revs.length; i++) { | ||
if (!isTextRedirect(revs[i].content)) { | if (!isTextRedirect(revs[i].content)) { | ||
ctx.creator = revs[i].user; | ctx.creator = revs[i].user; | ||
ctx. | ctx.creationTimestamp = revs[i].timestamp; | ||
break; | break; | ||
} | } | ||
Line 4,176: | Line 4,205: | ||
// fallback to give first revision author if no non-redirect version in the first 50 | // fallback to give first revision author if no non-redirect version in the first 50 | ||
ctx.creator = revs[0].user; | ctx.creator = revs[0].user; | ||
ctx. | ctx.creationTimestamp = revs[0].timestamp; | ||
if (!ctx.creator) { | if (!ctx.creator) { | ||
ctx.statusElement.error('Could not find name of page creator'); | ctx.statusElement.error('Could not find name of page creator'); | ||
Line 4,184: | Line 4,213: | ||
} | } | ||
if (!ctx. | if (!ctx.creationTimestamp) { | ||
ctx.statusElement.error('Could not find timestamp of page creation'); | ctx.statusElement.error('Could not find timestamp of page creation'); | ||
ctx.onLookupCreationFailure(this); | ctx.onLookupCreationFailure(this); | ||
Line 4,201: | Line 4,230: | ||
* @param {string} action - The action being checked. | * @param {string} action - The action being checked. | ||
* @param {string} onFailure - Failure callback. | * @param {string} onFailure - Failure callback. | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
var fnPreflightChecks = function(action, onFailure) { | var fnPreflightChecks = function(action, onFailure) { | ||
Line 4,226: | Line 4,255: | ||
* @param {string} onFailure - Failure callback. | * @param {string} onFailure - Failure callback. | ||
* @param {string} response - The response document from the API call. | * @param {string} response - The response document from the API call. | ||
* @ | * @returns {boolean} | ||
*/ | */ | ||
var fnProcessChecks = function(action, onFailure, response) { | |||
var missing = response.pages[0].missing; | |||
// No undelete as an existing page could have deleted revisions | // No undelete as an existing page could have deleted revisions | ||
var actionMissing = missing && ['delete', 'stabilize', 'move'].indexOf(action) !== -1; | |||
var protectMissing = action === 'protect' && missing && (ctx.protectEdit || ctx.protectMove); | |||
var saltMissing = action === 'protect' && !missing && ctx.protectCreate; | |||
if (actionMissing || protectMissing || saltMissing) { | if (actionMissing || protectMissing || saltMissing) { | ||
Line 4,244: | Line 4,273: | ||
// Delete, undelete, move | // Delete, undelete, move | ||
// extract protection info | // extract protection info | ||
var editprot; | |||
if (action === 'undelete') { | if (action === 'undelete') { | ||
editprot = response.pages[0].protection.filter((pr) | editprot = response.pages[0].protection.filter(function(pr) { | ||
return pr.type === 'create' && pr.level === 'sysop'; | |||
}).pop(); | |||
} else if (action === 'delete' || action === 'move') { | } else if (action === 'delete' || action === 'move') { | ||
editprot = response.pages[0].protection.filter((pr) | editprot = response.pages[0].protection.filter(function(pr) { | ||
return pr.type === 'edit' && pr.level === 'sysop'; | |||
}).pop(); | |||
} | } | ||
if (editprot && !ctx.suppressProtectWarning && | if (editprot && !ctx.suppressProtectWarning && | ||
!confirm('You are about to ' + action + ' the fully protected page "' + ctx.pageName + | !confirm('You are about to ' + action + ' the fully protected page "' + ctx.pageName + | ||
(editprot.expiry === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + new Morebits.date(editprot.expiry).calendar('utc') + ' (UTC))') + | |||
'. \n\nClick OK to proceed with ' + action + ', or Cancel to skip.')) { | |||
ctx.statusElement.error('Aborted ' + action + ' on fully protected page.'); | ctx.statusElement.error('Aborted ' + action + ' on fully protected page.'); | ||
onFailure(this); | onFailure(this); | ||
Line 4,268: | Line 4,301: | ||
var fnProcessMove = function() { | var fnProcessMove = function() { | ||
var pageTitle, token; | |||
if (fnCanUseMwUserToken('move')) { | if (fnCanUseMwUserToken('move')) { | ||
Line 4,274: | Line 4,307: | ||
pageTitle = ctx.pageName; | pageTitle = ctx.pageName; | ||
} else { | } else { | ||
var response = ctx.moveApi.getResponse().query; | |||
if (!fnProcessChecks('move', ctx.onMoveFailure, response)) { | if (!fnProcessChecks('move', ctx.onMoveFailure, response)) { | ||
Line 4,281: | Line 4,314: | ||
token = response.tokens.csrftoken; | token = response.tokens.csrftoken; | ||
var page = response.pages[0]; | |||
pageTitle = page.title; | pageTitle = page.title; | ||
ctx.watched = page.watchlistexpiry || page.watched; | ctx.watched = page.watchlistexpiry || page.watched; | ||
} | } | ||
var query = { | |||
action: 'move', | action: 'move', | ||
from: pageTitle, | from: pageTitle, | ||
Line 4,318: | Line 4,351: | ||
var fnProcessPatrol = function() { | var fnProcessPatrol = function() { | ||
var query = { | |||
action: 'patrol', | action: 'patrol', | ||
format: 'json' | format: 'json' | ||
Line 4,328: | Line 4,361: | ||
query.token = mw.user.tokens.get('patrolToken'); | query.token = mw.user.tokens.get('patrolToken'); | ||
} else { | } else { | ||
var response = ctx.patrolApi.getResponse().query; | |||
// Don't patrol if not unpatrolled | // Don't patrol if not unpatrolled | ||
Line 4,335: | Line 4,368: | ||
} | } | ||
var lastrevid = response.pages[0].lastrevid; | |||
if (!lastrevid) { | if (!lastrevid) { | ||
return; | return; | ||
Line 4,341: | Line 4,374: | ||
query.revid = lastrevid; | query.revid = lastrevid; | ||
var token = response.tokens.csrftoken; | |||
if (!token) { | if (!token) { | ||
return; | return; | ||
Line 4,351: | Line 4,384: | ||
} | } | ||
var patrolStat = new Morebits.status('Marking page as patrolled'); | |||
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat); | ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat); | ||
Line 4,363: | Line 4,396: | ||
ctx.csrfToken = mw.user.tokens.get('csrfToken'); | ctx.csrfToken = mw.user.tokens.get('csrfToken'); | ||
} else { | } else { | ||
var response = ctx.triageApi.getResponse().query; | |||
ctx.pageID = response.pages[0].pageid; | ctx.pageID = response.pages[0].pageid; | ||
Line 4,376: | Line 4,409: | ||
} | } | ||
var query = { | |||
action: 'pagetriagelist', | action: 'pagetriagelist', | ||
page_id: ctx.pageID, | page_id: ctx.pageID, | ||
Line 4,389: | Line 4,422: | ||
// callback from triageProcessListApi.post() | // callback from triageProcessListApi.post() | ||
var fnProcessTriage = function() { | var fnProcessTriage = function() { | ||
var responseList = ctx.triageProcessListApi.getResponse().pagetriagelist; | |||
// Exit if not in the queue | // Exit if not in the queue | ||
if (!responseList || responseList.result !== 'success') { | if (!responseList || responseList.result !== 'success') { | ||
return; | return; | ||
} | } | ||
var page = responseList.pages && responseList.pages[0]; | |||
// Do nothing if page already triaged/patrolled | // Do nothing if page already triaged/patrolled | ||
if (!page || !parseInt(page.patrol_status, 10)) { | if (!page || !parseInt(page.patrol_status, 10)) { | ||
var query = { | |||
action: 'pagetriageaction', | action: 'pagetriageaction', | ||
pageid: ctx.pageID, | pageid: ctx.pageID, | ||
Line 4,407: | Line 4,440: | ||
format: 'json' | format: 'json' | ||
}; | }; | ||
var triageStat = new Morebits.status('Marking page as curated'); | |||
ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, null, triageStat); | ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, null, triageStat); | ||
ctx.triageProcessApi.setParent(this); | ctx.triageProcessApi.setParent(this); | ||
Line 4,415: | Line 4,448: | ||
var fnProcessDelete = function() { | var fnProcessDelete = function() { | ||
var pageTitle, token; | |||
if (fnCanUseMwUserToken('delete')) { | if (fnCanUseMwUserToken('delete')) { | ||
Line 4,421: | Line 4,454: | ||
pageTitle = ctx.pageName; | pageTitle = ctx.pageName; | ||
} else { | } else { | ||
var response = ctx.deleteApi.getResponse().query; | |||
if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) { | if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) { | ||
Line 4,428: | Line 4,461: | ||
token = response.tokens.csrftoken; | token = response.tokens.csrftoken; | ||
var page = response.pages[0]; | |||
pageTitle = page.title; | pageTitle = page.title; | ||
ctx.watched = page.watchlistexpiry || page.watched; | ctx.watched = page.watchlistexpiry || page.watched; | ||
} | } | ||
var query = { | |||
action: 'delete', | action: 'delete', | ||
title: pageTitle, | title: pageTitle, | ||
Line 4,443: | Line 4,476: | ||
if (ctx.changeTags) { | if (ctx.changeTags) { | ||
query.tags = ctx.changeTags; | query.tags = ctx.changeTags; | ||
} | } | ||
Line 4,460: | Line 4,490: | ||
var fnProcessDeleteError = function() { | var fnProcessDeleteError = function() { | ||
var errorCode = ctx.deleteProcessApi.getErrorCode(); | |||
// check for "Database query error" | // check for "Database query error" | ||
if (errorCode === 'internal_api_error_DBQueryError' && ctx.retries++ < ctx.maxRetries) { | if (errorCode === 'internal_api_error_DBQueryError' && ctx.retries++ < ctx.maxRetries) { | ||
ctx.statusElement.info('Database query error, retrying'); | ctx.statusElement.info('Database query error, retrying'); | ||
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds | --Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds | ||
ctx.deleteProcessApi.post(); // give it another go! | ctx.deleteProcessApi.post(); // give it another go! | ||
Line 4,471: | Line 4,501: | ||
ctx.statusElement.error('Cannot delete the page, because it no longer exists'); | ctx.statusElement.error('Cannot delete the page, because it no longer exists'); | ||
if (ctx.onDeleteFailure) { | if (ctx.onDeleteFailure) { | ||
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback | ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback | ||
} | } | ||
// hard error, give up | |||
} else { | } else { | ||
ctx.statusElement.error('Failed to delete the page: ' + ctx.deleteProcessApi.getErrorText()); | ctx.statusElement.error('Failed to delete the page: ' + ctx.deleteProcessApi.getErrorText()); | ||
if (ctx.onDeleteFailure) { | if (ctx.onDeleteFailure) { | ||
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback | ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback | ||
} | } | ||
} | } | ||
Line 4,483: | Line 4,513: | ||
var fnProcessUndelete = function() { | var fnProcessUndelete = function() { | ||
var pageTitle, token; | |||
if (fnCanUseMwUserToken('undelete')) { | if (fnCanUseMwUserToken('undelete')) { | ||
Line 4,489: | Line 4,519: | ||
pageTitle = ctx.pageName; | pageTitle = ctx.pageName; | ||
} else { | } else { | ||
var response = ctx.undeleteApi.getResponse().query; | |||
if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) { | if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) { | ||
Line 4,496: | Line 4,526: | ||
token = response.tokens.csrftoken; | token = response.tokens.csrftoken; | ||
var page = response.pages[0]; | |||
pageTitle = page.title; | pageTitle = page.title; | ||
ctx.watched = page.watchlistexpiry || page.watched; | ctx.watched = page.watchlistexpiry || page.watched; | ||
} | } | ||
var query = { | |||
action: 'undelete', | action: 'undelete', | ||
title: pageTitle, | title: pageTitle, | ||
Line 4,511: | Line 4,541: | ||
if (ctx.changeTags) { | if (ctx.changeTags) { | ||
query.tags = ctx.changeTags; | query.tags = ctx.changeTags; | ||
} | } | ||
Line 4,528: | Line 4,555: | ||
var fnProcessUndeleteError = function() { | var fnProcessUndeleteError = function() { | ||
var errorCode = ctx.undeleteProcessApi.getErrorCode(); | |||
// check for "Database query error" | // check for "Database query error" | ||
Line 4,534: | Line 4,561: | ||
if (ctx.retries++ < ctx.maxRetries) { | if (ctx.retries++ < ctx.maxRetries) { | ||
ctx.statusElement.info('Database query error, retrying'); | ctx.statusElement.info('Database query error, retrying'); | ||
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds | --Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds | ||
ctx.undeleteProcessApi.post(); // give it another go! | ctx.undeleteProcessApi.post(); // give it another go! | ||
} else { | } else { | ||
ctx.statusElement.error('Repeated database query error, please try again'); | ctx.statusElement.error('Repeated database query error, please try again'); | ||
if (ctx.onUndeleteFailure) { | if (ctx.onUndeleteFailure) { | ||
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback | ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback | ||
} | } | ||
} | } | ||
Line 4,545: | Line 4,572: | ||
ctx.statusElement.error('Cannot undelete the page, either because there are no revisions to undelete or because it has already been undeleted'); | 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) { | if (ctx.onUndeleteFailure) { | ||
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback | ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback | ||
} | } | ||
// hard error, give up | |||
} else { | } else { | ||
ctx.statusElement.error('Failed to undelete the page: ' + ctx.undeleteProcessApi.getErrorText()); | ctx.statusElement.error('Failed to undelete the page: ' + ctx.undeleteProcessApi.getErrorText()); | ||
if (ctx.onUndeleteFailure) { | if (ctx.onUndeleteFailure) { | ||
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback | ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback | ||
} | } | ||
} | } | ||
Line 4,557: | Line 4,584: | ||
var fnProcessProtect = function() { | var fnProcessProtect = function() { | ||
var response = ctx.protectApi.getResponse().query; | |||
if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) { | if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) { | ||
Line 4,563: | Line 4,590: | ||
} | } | ||
var token = response.tokens.csrftoken; | |||
var page = response.pages[0]; | |||
var pageTitle = page.title; | |||
ctx.watched = page.watchlistexpiry || page.watched; | ctx.watched = page.watchlistexpiry || page.watched; | ||
// Fetch existing protection levels | // Fetch existing protection levels | ||
var prs = response.pages[0].protection; | |||
var editprot, moveprot, createprot; | |||
prs.forEach((pr) | prs.forEach(function(pr) { | ||
// Filter out protection from cascading | // Filter out protection from cascading | ||
if (pr.type === 'edit' && !pr.source) { | if (pr.type === 'edit' && !pr.source) { | ||
Line 4,581: | Line 4,608: | ||
} | } | ||
}); | }); | ||
// Fall back to current levels if not explicitly set | // Fall back to current levels if not explicitly set | ||
Line 4,595: | Line 4,623: | ||
// Default to pre-existing cascading protection if unchanged (similar to above) | // Default to pre-existing cascading protection if unchanged (similar to above) | ||
if (ctx.protectCascade === null) { | if (ctx.protectCascade === null) { | ||
ctx.protectCascade = !!prs.filter((pr) | ctx.protectCascade = !!prs.filter(function(pr) { | ||
return pr.cascade; | |||
}).length; | |||
} | } | ||
// Warn if cascading protection being applied with an invalid protection level, | // Warn if cascading protection being applied with an invalid protection level, | ||
Line 4,605: | Line 4,635: | ||
(!ctx.protectMove || ctx.protectMove.level !== 'sysop')) && | (!ctx.protectMove || ctx.protectMove.level !== 'sysop')) && | ||
!confirm('You have cascading protection enabled on "' + ctx.pageName + | !confirm('You have cascading protection enabled on "' + ctx.pageName + | ||
'" but have not selected uniform sysop-level protection.\n\n' + | |||
'Click OK to adjust and proceed with sysop-level cascading protection, or Cancel to skip this action.')) { | |||
ctx.statusElement.error('Cascading protection was aborted.'); | ctx.statusElement.error('Cascading protection was aborted.'); | ||
ctx.onProtectFailure(this); | ctx.onProtectFailure(this); | ||
Line 4,617: | Line 4,647: | ||
// Build protection levels and expirys (expiries?) for query | // Build protection levels and expirys (expiries?) for query | ||
var protections = [], expirys = []; | |||
if (ctx.protectEdit) { | if (ctx.protectEdit) { | ||
protections.push('edit=' + ctx.protectEdit.level); | protections.push('edit=' + ctx.protectEdit.level); | ||
Line 4,633: | Line 4,663: | ||
} | } | ||
var query = { | |||
action: 'protect', | action: 'protect', | ||
title: pageTitle, | title: pageTitle, | ||
Line 4,661: | Line 4,691: | ||
var fnProcessStabilize = function() { | var fnProcessStabilize = function() { | ||
var pageTitle, token; | |||
if (fnCanUseMwUserToken('stabilize')) { | if (fnCanUseMwUserToken('stabilize')) { | ||
Line 4,667: | Line 4,697: | ||
pageTitle = ctx.pageName; | pageTitle = ctx.pageName; | ||
} else { | } else { | ||
var response = ctx.stabilizeApi.getResponse().query; | |||
// 'stabilize' as a verb not necessarily well understood | // 'stabilize' as a verb not necessarily well understood | ||
Line 4,675: | Line 4,705: | ||
token = response.tokens.csrftoken; | token = response.tokens.csrftoken; | ||
var page = response.pages[0]; | |||
pageTitle = page.title; | pageTitle = page.title; | ||
// Doesn't support watchlist expiry [[phab:T263336]] | // Doesn't support watchlist expiry [[phab:T263336]] | ||
Line 4,681: | Line 4,711: | ||
} | } | ||
var query = { | |||
action: 'stabilize', | action: 'stabilize', | ||
title: pageTitle, | title: pageTitle, | ||
Line 4,694: | Line 4,724: | ||
/* Doesn't support watchlist expiry [[phab:T263336]] | /* 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); | ctx.stabilizeProcessApi = new Morebits.wiki.api('configuring stabilization settings...', query, ctx.onStabilizeSuccess, ctx.statusElement, ctx.onStabilizeFailure); | ||
Line 4,705: | Line 4,735: | ||
var sleep = function(milliseconds) { | var sleep = function(milliseconds) { | ||
var deferred = $.Deferred(); | |||
setTimeout(deferred.resolve, milliseconds); | setTimeout(deferred.resolve, milliseconds); | ||
return deferred; | return deferred; | ||
Line 4,719: | Line 4,749: | ||
*/ | */ | ||
/* **************** Morebits.wiki. | |||
/* **************** Morebits.wiki.user **************** */ | |||
/** | /** | ||
* Use the API to | * Use the MediaWiki API to {@link Morebits.wiki.user#load|load info about} | ||
* | * a user, and optionally {@link Morebits.wiki.user#block|block}, | ||
* | * {@link Morebits.wiki.user#unblock|unblock}, or | ||
* {@link Morebits. | * {@link Morebits.wiki.user#notify|notify} them, or, | ||
* | * {@link Morebits.wiki.user#groups|change their user groups}. | ||
* | * Generic setters include {@link Morebits.wiki.user#setReason|setReason}, | ||
* | * {@link Morebits.wiki.user#setWatchuser|setWatchuser}, | ||
* and {@link Morebits.wiki.user#setChangeTags|setChangeTags}. | |||
* | * | ||
* @memberof Morebits.wiki | * @memberof Morebits.wiki | ||
* @class | * @class | ||
* @param { | * @param {string} userName - The user in question. Can be a username, IP address, or range. | ||
* | * @param {string|Morebits.status} [currentAction='Querying user' + userName] - A string | ||
* describing the action about to be undertaken, or a `Morebits.status` object. | |||
* @throws {Error} If invalid username provided. | |||
*/ | */ | ||
Morebits.wiki. | Morebits.wiki.user = function(userName, currentAction) { | ||
// Basic normalization, e.g. if namespace prefix is included | |||
// Used elsewhere to get prefixed user & user talk page titles | |||
var userTitle; | |||
if (typeof userName !== 'string' || !(userTitle = mw.Title.newFromText(userName, 2))) { | |||
throw new Error('Invalid username provided'); | |||
* to render the specified wikitext. | } | ||
* | // Normalize IPv6 | ||
* @param {string} wikitext - Wikitext to render; most things should work, including `subst:` and `~~~~`. | userName = Morebits.ip.sanitizeIPv6(userTitle.getMainText()); | ||
* @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. | if (!currentAction) { | ||
* @ | currentAction = msg('querying-user', userName, 'Querying user "' + userName + '"'); | ||
*/ | } | ||
this.beginRender = function(wikitext, pageTitle, sectionTitle) { | |||
$(previewbox).show(); | /** | ||
* Private context variable not visible to the outside, thus all the | |||
* data here must be accessed via getter and setter functions. | |||
previewbox.appendChild(statusspan); | * | ||
Morebits.status.init(statusspan); | * @private | ||
*/ | |||
var ctx = { | |||
action: 'parse', | userName: userName, | ||
prop: ['text', 'modules'], | userID: null, | ||
pst: true, // PST = pre-save transform; this makes substitution work properly | editCount: null, | ||
preview: true, | registration: null, | ||
text: wikitext, | exists: false, | ||
title: pageTitle || mw.config.get('wgPageName'), | hidden: false, | ||
disablelimitreport: true, | loadTime: null, | ||
disableeditsection: true, | isIP: mw.util.isIPAddress(userName, true), | ||
format: 'json' | isIPRange: Morebits.ip.isRange(userName), | ||
}; | |||
if (sectionTitle) { | reason: null, // Will default to current reason if reblocking | ||
query.section = 'new'; | changeTags: null, | ||
query.sectiontitle = sectionTitle; | watchuser: false, | ||
} | watchlistExpiry: null, | ||
expiry: null, // Will default to current expiry if reblocking | |||
return renderApi.post(); | callbackParameters: null, | ||
}; | statusElement: currentAction instanceof Morebits.status ? currentAction : new Morebits.status(currentAction), | ||
var fnRenderSuccess = function(apiobj) { | // block parameters | ||
hasBlockLog: null, | |||
lastBlockLogEntry: null, | |||
if (!html) { | blockInfo: null, // If blocked, an object full of block parameters | ||
apiobj.statelem.error('failed to retrieve preview, or template was blanked'); | blockedRange: null, | ||
return; | isBlocked: null, | ||
} | isRangeBlocked: null, | ||
previewbox.innerHTML = html; | reblock: false, | ||
mw.loader.load(response.parse.modulestyles); | useOriginalBlockParams: true, | ||
mw.loader.load(response.parse.modules); | |||
// null before loading, array after | |||
// this makes links open in new tab | groups: null, | ||
$(previewbox).find('a').attr('target', '_blank'); | autoGroups: null, | ||
}; | userRights: null, | ||
// Response is array of objects with group: name and expiry: time, | |||
/** Hides the preview box and clears it. */ | // but we force it into an object with groupname: expiration | ||
this.closePreview = function() { | grantedGroups: null, | ||
$(previewbox).empty().hide(); | |||
}; | /* Block */ | ||
}; | // If the user is directly blocked, these defaults will be | ||
// overridden with values from the active block unless | |||
/* **************** Morebits.wikitext **************** */ | // useOriginalBlockParams is set | ||
allowusertalk: true, | |||
/** | anononly: false, | ||
* Wikitext manipulation. | autoblock: true, | ||
* | nocreate: true, | ||
* @namespace Morebits.wikitext | noemail: false, | ||
* @memberof Morebits | hidename: false, | ||
partial: false, | |||
namespacerestrictions: null, | |||
pagerestrictions: null, | |||
/* Change usergroups */ | |||
addGroups: null, | |||
removeGroups: null, | |||
/* Notify */ | |||
// talkLinks, talkTemplates, and notifySkipTemplates end up as arrays | |||
talkTitle: userTitle.getTalkPage().toText(), | |||
talkText: null, | |||
talkExists: null, | |||
talkTimestamp: null, | |||
talkLastEditor: null, | |||
talkTemplates: null, | |||
talkLinks: null, | |||
message: null, | |||
sectionTitle: null, | |||
notifyBots: false, | |||
notifyIndef: false, | |||
notifySelf: false, | |||
notifySkipTemplates: null, | |||
notifySkipLink: null, | |||
pageobjectFunctions: null, | |||
// Internals | |||
// In theory mw.user.tokens is available as a fallback, | |||
// but since we're always loading there's really no need | |||
csrfToken: null, | |||
userrightsToken: null, | |||
userApi: null, | |||
userLoaded: false, | |||
blockApi: null, | |||
unblockApi: null, | |||
groupsApi: null, | |||
actionResponse: null, | |||
// Callbacks | |||
onLoadSuccess: null, | |||
onLoadFailure: null, | |||
onBlockSuccess: null, | |||
onBlockFailure: null, | |||
onUnblockSuccess: null, | |||
onUnblockFailure: null, | |||
onGroupsSuccess: null, | |||
onGroupsFailure: null, | |||
onNotifySuccess: null, | |||
onNotifyFailure: null | |||
}; | |||
var emptyFunction = function() { }; | |||
/** | |||
* Loads info about the user. Required before (nearly) all of the | |||
* object methods, but will be done automatically if forgotten. Note | |||
* that unlike {@link Morebits.wiki.page#load}, the `onSuccess` callback | |||
* is not required. | |||
* | |||
* @param {Function} [onSuccess] - Callback function which is called when the load has succeeded. | |||
* @param {Function} [onFailure] - Callback function which is called when the load fails. | |||
*/ | |||
this.load = function(onSuccess, onFailure) { | |||
ctx.onLoadSuccess = onSuccess; | |||
ctx.onLoadFailure = onFailure || emptyFunction; | |||
ctx.loadQuery = { | |||
action: 'query', | |||
// Potential expansions: | |||
// list=usercontribs to get timestamp of user's last | |||
// edit, can skip if haven't edited in X days | |||
// list=allusers for global attached stats | |||
// list=globalblocks | |||
// meta=globaluserinfo for locked status | |||
list: 'blocks|users|logevents', | |||
// groups technically redundant to implicit+groupmemberships, but meh | |||
usprop: 'registration|editcount|rights|groups|implicitgroups|groupmemberships', | |||
ususers: ctx.userName, | |||
// bkusers or bkip set below as appropriate | |||
bkprop: 'id|user|by|timestamp|expiry|reason|flags|restrictions|range', | |||
// Just to know if there is a block log. Logs users, IPs, and CIDR blocks, | |||
// but note: no entries present for an IP caught within a range block. | |||
// Moreover, semi-busted on ranges, see [[phab:T270737]] and [[phab:T146628]]. | |||
// Basically, logevents doesn't treat functionally-equivalent ranges | |||
// as equivalent, meaning functionally-equivalent IP ranges may be | |||
// misinterpreted. Without logevents redirecting (like Special:Block does) | |||
// we would need a function to parse ranges, which is a pain. | |||
// IPUtils has code, but it'd be a lot of cruft for one purpose. | |||
letype: 'block', | |||
letitle: userTitle.toText(), | |||
lelimit: 1, | |||
// Get the talk page content, categories, etc. | |||
titles: ctx.talkTitle, | |||
// Redirect checking is present in morebits.wiki.page, | |||
// but as this is mainly a utility in case talkpage | |||
// content is desired, concerns like cross-namespace | |||
// redirects aren't checked; we follow all redirects. | |||
redirects: '', | |||
prop: 'info|revisions|templates|extlinks', | |||
// Could include intestactions but that's probably overkill | |||
rvprop: 'content|timestamp|user', | |||
curtimestamp: '', | |||
meta: 'tokens', | |||
type: 'csrf|userrights', // We don't yet know which we'll need | |||
format: 'json' | |||
}; | |||
// bkusers doesn't catch single IPs blocked as part of a range block | |||
if (ctx.isIP) { | |||
ctx.loadQuery.bkip = ctx.userName; | |||
} else { | |||
ctx.loadQuery.bkusers = ctx.userName; | |||
} | |||
// If skip templates already set, use those; if not, just get a bunch | |||
if (ctx.notifySkipTemplates && ctx.notifySkipTemplates.length) { | |||
ctx.loadQuery.tltemplates = ctx.notifySkipTemplates; | |||
} else { | |||
ctx.loadQuery.tllimit = 42; // 640K ought to be enough for anybody | |||
} | |||
// Likewise for external skip links. elprotocol missing so should get everyone | |||
if (ctx.notifySkipLink) { | |||
ctx.loadQuery.elquery = ctx.notifySkipLink; | |||
} else { | |||
ctx.loadQuery.ellimit = 42; | |||
} | |||
ctx.userApi = new Morebits.wiki.api(msg('fetching-userinfo', 'Retrieving user information...'), ctx.loadQuery, fnLoadSuccess, ctx.statusElement, ctx.onLoadFailure); | |||
ctx.userApi.setParent(this); | |||
ctx.userApi.post(); | |||
}; | |||
// callback from userApi.post() | |||
var fnLoadSuccess = function() { | |||
var response = ctx.userApi.getResponse(); | |||
ctx.loadTime = response.curtimestamp; | |||
// None of these have time-based "edit conflict"-like | |||
// resolution. If we really wanted to replicate something | |||
// here (we don't), we could attempt something with logevents, | |||
// but that's complicated by the fact that logevents only | |||
// allows one type at a time, not to mention the extra, | |||
// nearly-always unnecessary query it'd entail. In the end, | |||
// block is probably fine enough with `reblock`, unblock will | |||
// just fail, and userrights will fail quietly, so it'd just | |||
// be excessive. We *do* store the last block log entry, so | |||
// clients can do as they please. This tells when the user | |||
// was loaded, which is useful for time-based functions. | |||
if (!ctx.loadTime) { | |||
ctx.statusElement.error(msg('failed-timestamp', 'Failed to retrieve current timestamp.')); | |||
ctx.onLoadFailure(this); | |||
return; | |||
} | |||
// This is what we *really* care about... | |||
response = response.query; | |||
// Even if this is unnecessary (notification), an issue here | |||
// likely indicates *something* went wrong. The same | |||
// as Morebits.wiki.page, though it's more necessary there. | |||
if (!response.tokens.csrftoken || !response.tokens.userrightstoken) { | |||
ctx.statusElement.error(msg('failed-token', 'Failed to retrieve token.')); | |||
ctx.onLoadFailure(this); | |||
return; | |||
} | |||
ctx.csrfToken = response.tokens.csrftoken; | |||
ctx.userrightsToken = response.tokens.userrightstoken; | |||
var user = response.users && response.users[0]; | |||
// Not sure scenario could lead to this, but might as well be safe | |||
if (!user) { | |||
ctx.statusElement.error(msg('failed-userinfo', ctx.userName, 'Failed to retrieve user info for ' + ctx.userName)); | |||
ctx.onLoadFailure(this); | |||
// force error to stay on the screen | |||
++Morebits.wiki.numberOfActionsLeft; | |||
return; | |||
} | |||
// IPs and registered accounts | |||
ctx.exists = !user.missing; | |||
if (ctx.exists) { | |||
ctx.userName = user.name; // Normalization, possibly? | |||
// Registered account, equivalent to !!user.userid | |||
// IPs and unregistered accounts default to null for ID and registration; | |||
// edit count is similarly meaningless | |||
if (!user.invalid) { | |||
ctx.userID = user.userid; | |||
ctx.registration = user.registration; | |||
ctx.editCount = user.editcount; | |||
// Username oversighted or globally hidden, | |||
// mostly so advanced users know to be careful | |||
ctx.hidden = !!user.hidden; | |||
// Array | |||
ctx.groups = user.groups; | |||
ctx.autoGroups = user.implicitgroups; | |||
ctx.userRights = user.rights; | |||
// Force into object with group: expiry pairs | |||
// It's negligible, but reduce seems about 10-15% slower | |||
if (user.groupmemberships) { | |||
ctx.grantedGroups = {}; | |||
user.groupmemberships.forEach(function(gm) { | |||
ctx.grantedGroups[gm.group] = gm.expiry; | |||
}); | |||
} | |||
} | |||
// Save the most recent block log entry. It's | |||
// probably most interesting for checking the last | |||
// action performed or rechecking a block status using | |||
// the logid. IPs caught in a range block won't show | |||
// entries here, but will be noted as blocked below, | |||
// so it's possible to be currently blocked but not | |||
// have a block log. | |||
if (response.logevents.length) { | |||
ctx.hasBlockLog = true; | |||
ctx.lastBlockLogEntry = $.extend({}, response.logevents[0]); | |||
} | |||
if (response.blocks.length) { | |||
// Note that this is really a marker for whether the user is covered by a known | |||
// block, not whether the user in question is itself directly blocked. That is, a single | |||
// IP blocked only as part of a rangeblock will show up here, but we won't treat treat | |||
// them as if they are directly blocked (such as with `reblock`). As such, the context | |||
// variables are only overwritten if the user is directly blocked, and the relevant getters | |||
// all use ctx.blockInfo to derive their information. | |||
ctx.isBlocked = true; | |||
// In the case of multiple blocks, such as an IP blocked *and* rangeblocked, | |||
// find the exact block; otherwise, fall back to the most recent. | |||
// Likewise, save the widest rangeblock. | |||
// Could also pre-sort this by expiry, as that may be more useful. | |||
var block, subnet = 0; | |||
response.blocks.reverse().forEach(function(bl, idx) { | |||
if (bl.user === ctx.userName || (idx === response.blocks.length - 1 && !block)) { | |||
block = bl; | |||
} | |||
// Always false (0.0.0.0 === 0.0.0.0) for users | |||
// Ensure we get the largest range | |||
if (bl.rangestart !== bl.rangeend && (!subnet || bl.user.split('/')[1] < subnet)) { | |||
subnet = bl.user.split('/')[1]; | |||
ctx.isRangeBlocked = true; | |||
ctx.blockedRange = bl.user; | |||
} | |||
}); | |||
// blockInfo object used by getters | |||
ctx.blockInfo = $.extend({}, block); | |||
// If this is the actual user in question, override the default | |||
// context values in order to default a reblock to the existing parameters. | |||
if (ctx.blockInfo.user === ctx.userName && ctx.useOriginalBlockParams) { | |||
// Note that expiry and reason aren't here, | |||
// as they can apply to non-block methods; | |||
// they are handled in fnProcessBlock. | |||
['allowusertalk', 'anononly', 'autoblock', 'nocreate', 'noemail', 'partial'].forEach(function(param) { | |||
ctx[param] = !!block[param]; | |||
}); | |||
// hidename, not hidden, since when applying a block, it's hidename. | |||
// See also user.hidden aka ctx.hidden. | |||
ctx.hidename = !!block.hidden; | |||
if (ctx.partial) { | |||
if (block.restrictions.namespaces) { | |||
ctx.namespacerestrictions = block.restrictions.namespaces; | |||
} | |||
// Force into array of titles, ditch ns (included in title) and page ID | |||
if (block.restrictions.pages) { | |||
ctx.pagerestrictions = block.restrictions.pages.map(function(rp) { | |||
return rp.title; | |||
}); | |||
} | |||
} | |||
} | |||
} | |||
} else { | |||
// User doesn't exist locally | |||
// Suppressed (and gsuppressed) names show | |||
// up here as well to those without the permission. | |||
// In the future, could consider adding cancreate to | |||
// usprop if we wanted to allow for account creation | |||
// Which apparently is fucking hard https://www.mediawiki.org/wiki/API:Account_creation#Creating_an_account | |||
ctx.userName = ''; | |||
} | |||
// Talk page stuff | |||
// Ignore unresolved, invalid page titles (e.g. circular redirects) | |||
var page = response.pages && response.pages[0]; | |||
if (page && !page.invalid) { | |||
ctx.talkExists = !page.missing; | |||
if (ctx.talkExists) { | |||
// Update to redirect target or normalized name; | |||
// no status message so as to avoid duplication when notifying | |||
ctx.talkTitle = page.title; | |||
var rev = page.revisions[0]; | |||
ctx.talkText = rev.content; | |||
ctx.talkTimestamp = rev.timestamp; | |||
ctx.talkLastEditor = rev.user; | |||
// Force into array of titles, ditch ns (included in title) | |||
if (page.templates) { | |||
ctx.talkTemplates = page.templates.map(function(template) { | |||
return template.title; | |||
}); | |||
} | |||
// Squash array of objects with single item | |||
if (page.extlinks) { | |||
ctx.talkLinks = Morebits.array.uniq(page.extlinks.map(function(link) { | |||
// Remove leading protocol, be http/https insensitive | |||
return link.url.replace(/^https?:\/\//, ''); | |||
})); | |||
} | |||
} else { | |||
ctx.talkText = ''; // allow for concatenation, etc. | |||
} | |||
} | |||
ctx.userLoaded = true; | |||
if (ctx.onLoadSuccess) { // invoke success callback if one was supplied | |||
ctx.onLoadSuccess.call(this, this); | |||
} | |||
}; | |||
/** | |||
* Block a user. If already blocked, will default to any prior block | |||
* settings unless {@link Morebits.wiki.user#useOriginalBlock} is set | |||
* to `false`. Makes use of: | |||
* - {@link Morebits.wiki.user#setExpiry|setExpiry} | |||
* - {@link Morebits.wiki.user#setAllowusertalk|setAllowusertalk} | |||
* - {@link Morebits.wiki.user#setAnononly|setAnononly} | |||
* - {@link Morebits.wiki.user#setAutoblock|setAutoblock} | |||
* - {@link Morebits.wiki.user#setNocreate|setNocreate} | |||
* - {@link Morebits.wiki.user#setNoemail|setNoemail} | |||
* - {@link Morebits.wiki.user#setReblock|setReblock} | |||
* - {@link Morebits.wiki.user#setHidename|setHidename} | |||
* - {@link Morebits.wiki.user#setPartial|setPartial} | |||
* - {@link Morebits.wiki.user#setPartialPages|setPartialPages} | |||
* - {@link Morebits.wiki.user#setPartialNamespaces|setPartialNamespaces} | |||
* - {@link Morebits.wiki.user#useOriginalBlock|useOriginalBlock} | |||
* | |||
* The actual processing is handled in `fnProcessBlock`. | |||
* | |||
* @param {Function} [onSuccess] - Callback function to run on success. | |||
* @param {Function} [onFailure] - Callback function to run on failure. | |||
*/ | |||
this.block = function(onSuccess, onFailure) { | |||
ctx.onBlockSuccess = onSuccess; | |||
ctx.onBlockFailure = onFailure || emptyFunction; | |||
// Ensure user is loaded | |||
if (fnDontNeedLoad('block')) { | |||
fnProcessBlock.call(this); | |||
} else { | |||
this.load(fnProcessBlock, ctx.onBlockFailure); | |||
} | |||
}; | |||
// Process the block | |||
var fnProcessBlock = function() { | |||
var directBlock = ctx.isBlocked && ctx.blockInfo.user === ctx.userName; | |||
// Default to existing block's expiry/reason if missing; done here rather than in | |||
// fnLoadSuccess so as not to provide erroneous defaults to other methods | |||
if (directBlock) { | |||
if (!ctx.reason) { | |||
ctx.reason = ctx.blockInfo.reason; | |||
} | |||
if (!ctx.expiry) { | |||
ctx.expiry = ctx.blockInfo.expiry; | |||
} | |||
} | |||
if (!fnProcessChecks('block', ctx.onBlockFailure)) { | |||
return; // abort | |||
} | |||
// If blocked and reblock is missing, assume we didn't know | |||
// the user was already blocked, so ask to toggle | |||
if (directBlock && !ctx.reblock) { | |||
var message = Morebits.string.isInfinity(this.getBlockExpiry()) | |||
? msg('already-blocked-indef', ctx.userName, this.getBlockingSysop(), ctx.userName + ' is already blocked (indefinitely; by ' + this.getBlockingSysop() + '), would you like to override the block?') | |||
: msg('already-blocked', ctx.userName, this.getBlockExpiry(), this.getBlockingSysop(), ctx.userName + ' is already blocked (until ' + new Morebits.date(this.getBlockExpiry()).calendar() + '; by ' + this.getBlockingSysop() + '), would you like to override the block?'); | |||
if (!confirm(message)) { | |||
ctx.statusElement.error(msg('reblock-aborted', 'Reblock aborted.')); | |||
ctx.onBlockFailure(this); | |||
return; | |||
} | |||
ctx.reblock = true; | |||
} | |||
// setExpiry allows arrays because userrights accepts it, but block doesn't | |||
if (Array.isArray(ctx.expiry)) { | |||
if (ctx.expiry.length !== 1) { | |||
ctx.statusElement.error(msg('invalid-block-expiry', 'You must provide a valid block expiration.')); | |||
ctx.onBlockFailure(this); | |||
return; | |||
} | |||
// Single-element array fine by Morebits.wiki.api, but we can't do isInfinity checks | |||
ctx.expiry = ctx.expiry[0]; | |||
} | |||
// Check before indefing IPs or blocking sysops | |||
if (ctx.isIP && Morebits.string.isInfinity(ctx.expiry) && | |||
!confirm(msg('ip-indef-confirm', ctx.userName, ctx.userName + ' is an IP address, do you really want to block it indefinitely?' + | |||
'\n\nClick OK to proceed with the block, or Cancel to abort.'))) { | |||
ctx.statusElement.error(msg('ip-indef-aborted', 'Indefinite block of IP address was aborted.')); | |||
ctx.onBlockFailure(this); | |||
return; | |||
} else if (this.isSysop() && | |||
!confirm(msg('admin-block-confirm', ctx.userName, ctx.userName + ' is an administrator, are you sure you want to block them? \n\nClick OK to proceed with the block, or Cancel to abort.'))) { | |||
ctx.statusElement.error(msg('admin-block-aborted', 'Block of administrator was aborted.')); | |||
ctx.onBlockFailure(this); | |||
return; | |||
} | |||
var query = fnBaseAction('block'); | |||
// If not altered and already blocked, these will match the | |||
// current block's status thanks to fnLoadSuccess (reason and | |||
// expiry already handled above). | |||
['allowusertalk', 'anononly', 'autoblock', 'nocreate', 'noemail', 'reblock'].forEach(function(param) { | |||
// Any value interpreted as true | |||
if (ctx[param]) { | |||
query[param] = ctx[param]; | |||
} | |||
}); | |||
if (ctx.partial) { | |||
query.partial = ctx.partial; | |||
if (ctx.namespacerestrictions) { | |||
// This awfulness is to ensure other namespaces (e.g. 13) don't get caught up in here | |||
if (!ctx.allowusertalk && ( | |||
(Array.isArray(ctx.namespacerestrictions) && ctx.namespacerestrictions.indexOf(3) === -1 && ctx.namespacerestrictions.indexOf('3') === -1) || | |||
(typeof ctx.namespacerestrictions === 'string' && ctx.namespacerestrictions.split('|').indexOf('3') === -1) || | |||
(typeof ctx.namespacerestrictions === 'number' && ctx.namespacerestrictions !== 3))) { | |||
ctx.statusElement.error(msg('partial-usertalk', 'Partial blocks cannot prevent talk page access unless also restricting User talk namespace.')); | |||
ctx.onBlockFailure(this); | |||
return; | |||
} | |||
query.namespacerestrictions = ctx.namespacerestrictions; | |||
} | |||
if (ctx.pagerestrictions) { | |||
query.pagerestrictions = ctx.pagerestrictions; | |||
} | |||
} | |||
// Only for oversighters | |||
if (ctx.hidename) { | |||
if (!Morebits.userIsInGroup('oversight')) { | |||
ctx.statusElement.error('Username suppression only available to oversighters.'); | |||
ctx.onBlockFailure(this); | |||
return; | |||
} | |||
if (ctx.partial || !Morebits.string.isInfinity(ctx.expiry)) { | |||
ctx.statusElement.error('Username suppression not available for partial or non-infinite blocks.'); | |||
ctx.onBlockFailure(this); | |||
return; | |||
} | |||
query.hidename = ctx.hidename; | |||
} else if (this.getHidename()) { | |||
// Warn if unsuppressing is taking place, by definition only oversighters will see this | |||
if (!confirm(ctx.userName + ' has been suppressed, do you really want to unhide it?' + | |||
'\n\nClick OK to proceed with the block, or Cancel to skip this block.')) { | |||
ctx.statusElement.error('Unsuppression of username was aborted.'); | |||
ctx.onBlockFailure(this); | |||
return; | |||
} | |||
} | |||
ctx.blockApi = new Morebits.wiki.api(msg('blocking', 'blocking user...'), query, fnBlockSuccess, ctx.statusElement, fnBlockError); | |||
ctx.blockApi.setParent(this); | |||
ctx.blockApi.post(); | |||
}; | |||
/** | |||
* Unblock a user. The actual processing is handled in `fnProcessUnblock`. | |||
* | |||
* @param {Function} [onSuccess] - Callback function to run on success. | |||
* @param {Function} [onFailure] - Callback function to run on failure. | |||
*/ | |||
this.unblock = function(onSuccess, onFailure) { | |||
ctx.onUnblockSuccess = onSuccess; | |||
ctx.onUnblockFailure = onFailure || emptyFunction; | |||
// Ensure user is loaded | |||
if (fnDontNeedLoad('unblock')) { | |||
fnProcessUnblock.call(this); | |||
} else { | |||
this.load(fnProcessUnblock, ctx.onUnblockFailure); | |||
} | |||
}; | |||
// Process the unblock | |||
var fnProcessUnblock = function() { | |||
if (!fnProcessChecks('unblock', ctx.onUnblockFailure)) { | |||
return; // abort | |||
} | |||
if (!ctx.isBlocked) { | |||
ctx.statusElement.error(msg('not-blocked', 'User is not blocked.')); | |||
ctx.onUnblockFailure(this); | |||
return; | |||
} else if (ctx.blockInfo.user !== ctx.userName) { | |||
ctx.statusElement.error(msg('indirect-block', ctx.blockInfo.user, 'User is not directly blocked, but rather ' + ctx.blockInfo.user + ' is.')); | |||
ctx.onUnblockFailure(this); | |||
return; | |||
} | |||
var query = fnBaseAction('unblock'); | |||
ctx.unblockApi = new Morebits.wiki.api(msg('unblocking', 'unblocking user...'), query, fnUnblockSuccess, ctx.statusElement, fnUnblockError); | |||
ctx.unblockApi.setParent(this); | |||
ctx.unblockApi.post(); | |||
}; | |||
// Forgiving, hardly any errors with which to contend [[phab:T35732]] | |||
/** | |||
* Change a user's usergroups. Makes use of: | |||
* - {@link Morebits.wiki.user#setExpiry|setExpiry} | |||
* - {@link Morebits.wiki.user#setAddGroups|setAddGroups} | |||
* - {@link Morebits.wiki.user#setRemoveGroups|setRemoveGroups} | |||
* | |||
* The actual processing is handled in `fnProcessGroups`. | |||
* | |||
* @param {Function} [onSuccess] - Callback function to run on success. | |||
* @param {Function} [onFailure] - Callback function to run on failure. | |||
*/ | |||
this.groups = function(onSuccess, onFailure) { | |||
ctx.onGroupsSuccess = onSuccess; | |||
ctx.onGroupsFailure = onFailure || emptyFunction; | |||
// Ensure user is loaded | |||
if (fnDontNeedLoad('groups')) { | |||
fnProcessGroups.call(this); | |||
} else { | |||
this.load(fnProcessGroups, ctx.onGroupsFailure); | |||
} | |||
}; | |||
// Process changing of user groups | |||
var fnProcessGroups = function() { | |||
if (!fnProcessChecks('change groups', ctx.onGroupsFailure)) { | |||
return; // abort | |||
} | |||
// Could be before the (required) user load, but better to fail fnProcessChecks first | |||
if (ctx.isIP) { | |||
ctx.statusElement.error('You can only change user groups for registered users.'); | |||
ctx.onGroupsFailure(this); | |||
return; | |||
} | |||
var query = fnBaseAction('userrights'); | |||
// userrights API is otherwise fairly forgiving | |||
if (ctx.addGroups) { | |||
if (Array.isArray(ctx.expiry) && ctx.expiry.length !== 1 && ctx.expiry.length !== ctx.addGroups.length) { | |||
ctx.statusElement.error("Number of expirations doesn't match the number of groups being added."); | |||
ctx.onGroupsFailure(this); | |||
return; | |||
} | |||
query.add = ctx.addGroups; | |||
} | |||
if (ctx.removeGroups) { | |||
query.remove = ctx.removeGroups; | |||
} | |||
ctx.groupsApi = new Morebits.wiki.api('changing user groups...', query, fnGroupsSuccess, ctx.statusElement, fnGroupsError); | |||
ctx.groupsApi.setParent(this); | |||
ctx.groupsApi.post(); | |||
}; | |||
/** | |||
* Notify a user via {@link Morebits.wiki.page}. Main advantages are | |||
* ability to skip notifying bots or indefinitely sitewide-blocked | |||
* users, or users with specific template or optout links. Some | |||
* options are customizable, but implies `setCreateOption('recreate')` | |||
* and `setFollowRedirect(true, false)`; other options are available | |||
* via `setPageobjectFunctions`. Makes use of: | |||
* - {@link Morebits.wiki.user#setMessage|setMessage} | |||
* - {@link Morebits.wiki.user#setSectionTitle|setSectionTitle} | |||
* - {@link Morebits.wiki.user#setNotifyBots|setNotifyBots} | |||
* - {@link Morebits.wiki.user#setNotifyIndef|setNotifyIndef} | |||
* - {@link Morebits.wiki.user#setNotifySelf|setNotifySelf} | |||
* - {@link Morebits.wiki.user#setNotifySkips|setNotifySkips} | |||
* - {@link Morebits.wiki.user#setPageobjectFunctions|setPageobjectFunctions} | |||
* | |||
* The actual processing is handled in `fnProcessNotify`. | |||
* | |||
* @param {Function} [onSuccess] - Callback function to run on success. | |||
* @param {Function} [onFailure] - Callback function to run on failure. | |||
*/ | |||
this.notify = function(onSuccess, onFailure) { | |||
ctx.onNotifySuccess = onSuccess; | |||
ctx.onNotifyFailure = onFailure || emptyFunction; | |||
if (ctx.isIPRange) { | |||
ctx.statusElement.error(msg('notify-fail-iprange', 'Cannot notify IP ranges')); | |||
ctx.onNotifyFailure(this); | |||
return; | |||
} | |||
// Check underscores | |||
if (ctx.notifySelf && ctx.userName === mw.config.get('wgUserName')) { | |||
ctx.statusElement.error(msg('notify-self-skip', ctx.userName, 'You (' + ctx.userName + ') created this page; skipping user notification')); | |||
ctx.onNotifyFailure(this); | |||
return; | |||
} | |||
// Ensure user is loaded | |||
if (fnDontNeedLoad('notify')) { | |||
fnProcessNotify.call(this); | |||
} else { | |||
this.load(fnProcessNotify, ctx.onNotifyFailure); | |||
} | |||
}; | |||
// Send the notification | |||
var fnProcessNotify = function() { | |||
// Empty reason, message, and token handled by Morebits.wiki.page | |||
if (!ctx.exists) { | |||
ctx.statusElement.error(msg('notify-fail-noexist', 'Cannot notify the user because the user does not exist')); | |||
ctx.onNotifyFailure(this); | |||
return; | |||
} | |||
if (ctx.notifySkipTemplates && ctx.notifySkipTemplates.length && ctx.talkTemplates && ctx.talkTemplates.length) { | |||
// More efficient to do a for loop, but this is prettier? | |||
var tlDups = Morebits.array.dups(ctx.talkTemplates.concat(ctx.notifySkipTemplates)); | |||
if (tlDups.length) { | |||
ctx.statusElement.error(msg('notify-fail-template', tlDups[0], 'User talk page transcludes {{' + tlDups[0] + '}}, aborting notification')); | |||
ctx.onNotifyFailure(this); | |||
return; | |||
} | |||
} else if (ctx.notifySkipLink && ctx.talkLinks && ctx.talkLinks.length) { | |||
// Should be without leading protocol; relying on mw.Uri could help | |||
var elDups = Morebits.array.dups(ctx.talkLinks.concat(ctx.notifySkipLink)); | |||
if (elDups.length) { | |||
ctx.statusElement.error(msg('notify-fail-optout', 'User has opted out of this notification, aborting')); | |||
ctx.onNotifyFailure(this); | |||
return; | |||
} | |||
} | |||
if (!ctx.notifyBots && this.isBot()) { | |||
ctx.statusElement.error(msg('notify-fail-bot', 'User is a bot, aborting notification')); | |||
ctx.onNotifyFailure(this); | |||
return; | |||
} | |||
// Clients may find this most useful iff notalk or the block isn't brand new | |||
// ctx.isBlocked intentionally used to account for any indef block, not just direct ones | |||
if (!ctx.notifyIndef && ctx.isBlocked && !this.getPartial() && Morebits.string.isInfinity(this.getBlockExpiry())) { | |||
ctx.statusElement.error(msg('notify-fail-blocked', 'User is indefinitely blocked, aborting notification')); | |||
ctx.onNotifyFailure(this); | |||
return; | |||
} | |||
// Intentionally *not* ctx.talkTitle, as that may have followed a cross-namespace redirect | |||
var exactTalkPage = mw.Title.newFromText(ctx.userName, 3).toText(); | |||
var usertalk = new Morebits.wiki.page(exactTalkPage, msg('notifying-user', ctx.userName, 'Notifying ' + ctx.userName)); | |||
// Usurp status element into new object | |||
usertalk.setStatusElement(ctx.statusElement); | |||
// Unlike with block, etc., this need not be binary. | |||
// Morebits.wiki.page#setWatchlist can handle the expiry in | |||
// one go, but we've kept things simpler/less repetitive here. | |||
usertalk.setWatchlist(ctx.watchuser); | |||
if (ctx.watchlistExpiry) { | |||
usertalk.setWatchlist(ctx.watchlistExpiry); | |||
} | |||
if (ctx.changeTags) { | |||
usertalk.setChangeTags(ctx.changeTags); | |||
} | |||
usertalk.setCreateOption('recreate'); | |||
// Loading via Morebits.wiki.user is set to follow all | |||
// redirects, which allows us to confirm whether or not the | |||
// talk page redirects. If it doesn't, then it turns out we | |||
// don't need to use setFollowRedirect which means | |||
// Morebits.wiki.page might not need to (re)load the page. | |||
if (!ctx.userLoaded || ctx.talkTitle !== exactTalkPage) { | |||
usertalk.setFollowRedirect(true, false); // Don't follow cross-namespace-redirects | |||
} | |||
if (ctx.callbackParameters) { | |||
usertalk.setCallbackParameters(ctx.callbackParameters); | |||
} | |||
// Set any additional parameters, shared by both cases but | |||
// should absolutely last | |||
var applyFunctions = function() { | |||
if (ctx.pageobjectFunctions !== null && typeof ctx.pageobjectFunctions === 'object') { | |||
Object.keys(ctx.pageobjectFunctions).forEach(function(key) { | |||
usertalk[key] && usertalk[key](ctx.pageobjectFunctions[key]); | |||
}); | |||
} | |||
}; | |||
// Can't reliably use newSection as many/most notification | |||
// templates already include the section header, but | |||
// sectionTitle implies newSection instead of append | |||
if (ctx.sectionTitle) { | |||
usertalk.setNewSectionText(ctx.message); | |||
usertalk.setNewSectionTitle(ctx.sectionTitle); | |||
// Optional in newSection | |||
if (ctx.reason) { | |||
usertalk.setEditSummary(ctx.reason); | |||
} | |||
applyFunctions(); | |||
usertalk.newSection(ctx.onNotifySuccess, ctx.onNotifyFailure); | |||
} else { | |||
usertalk.setAppendText(ctx.message); | |||
usertalk.setEditSummary(ctx.reason); | |||
applyFunctions(); | |||
usertalk.append(ctx.onNotifySuccess, ctx.onNotifyFailure); | |||
} | |||
}; | |||
/** | |||
* Common checks for processing of the `block`, `unblock`, and | |||
* `groups` methods. Considers: user existance, performer perms, | |||
* reason is set, and token. Not used for notify. | |||
* | |||
* @param {string} action - The action being checked: `block`, | |||
* `unblock`, or `change groups`. | |||
* @param {string} onFailure - The ctx.on???Failure callback. | |||
* @returns {boolean} | |||
*/ | |||
var fnProcessChecks = function(action, onFailure) { | |||
if (!ctx.exists) { | |||
ctx.statusElement.error('Cannot ' + action + ' the user because the user does not exist'); | |||
onFailure(this); | |||
return false; | |||
} | |||
// Currently ignores non-sysop bureaucrats, etc. | |||
// Could be dealt with by adding siprop | |||
if (!Morebits.userIsSysop && (action === 'change groups' && (!Morebits.userIsInGroup('eventcoordinator') || ctx.addGroups !== 'confirmed'))) { | |||
ctx.statusElement.error('Cannot ' + action + ': only admins can do that'); | |||
onFailure(this); | |||
return false; | |||
} | |||
if (!ctx.reason) { | |||
ctx.statusElement.error('Internal error: ' + action + ' reason not set (use setReason function)!'); | |||
onFailure(this); | |||
return false; | |||
} | |||
if ((!ctx.csrfToken && (action === 'block' || action === 'unblock')) || (!ctx.userrightsToken && action === 'change groups')) { | |||
ctx.statusElement.error(msg('failed-token', 'Failed to retrieve token.')); | |||
onFailure(this); | |||
return false; | |||
} | |||
return true; // all OK | |||
}; | |||
/** | |||
* Construct the common base for block, unblock, and userrights | |||
* actions. Includes an api post to watch a user for unblock and | |||
* userrights actions, as they do not support the watchuser option. | |||
* | |||
* @param {string} action - The action being undertaken (`block`, `unblock`, or `userrights`). | |||
* @returns {object} Action-specific POST query. | |||
*/ | |||
var fnBaseAction = function(action) { | |||
var query = { | |||
action: action, | |||
user: ctx.userName, | |||
reason: ctx.reason, | |||
token: action === 'userrights' ? ctx.userrightsToken : ctx.csrfToken, | |||
format: 'json' | |||
}; | |||
if (ctx.changeTags) { | |||
query.tags = ctx.changeTags; | |||
} | |||
// block or userrights | |||
if (action !== 'unblock' && (ctx.expiry || (Array.isArray(ctx.expiry) && ctx.expiry.length))) { | |||
query.expiry = ctx.expiry; | |||
} | |||
if (ctx.watchuser) { | |||
if (action === 'block') { | |||
query.watchuser = ctx.watchuser; | |||
if (ctx.watchlistExpiry) { | |||
query.watchlistexpiry = ctx.watchlistExpiry; | |||
} | |||
} else { | |||
// Dumb hack: watchlist options not supported for | |||
// unblock [[phab:T257662]] or userrights [[phab:T272294]], so fake it. | |||
var watch_query = { | |||
action: 'watch', | |||
titles: mw.Title.newFromText(ctx.userName, 2).toText(), | |||
token: mw.user.tokens.get('watchToken') | |||
}; | |||
if (ctx.watchlistExpiry) { | |||
watch_query.expiry = ctx.watchlistExpiry; | |||
} | |||
new Morebits.wiki.api(msg('watching-user', 'Watching user page...'), watch_query).post(); | |||
} | |||
} | |||
return query; | |||
}; | |||
/** | |||
* Determine whether we need to first load the user. The only | |||
* exception is notifications that don't care whether the target user | |||
* is a bot or indefinitely blocked, or if the talk page if opted-out. | |||
* | |||
* @param {string} action - The action being undertaken, e.g. `notify` | |||
* or `block`. Only `notify` has any meaning. | |||
* @returns {boolean} | |||
*/ | |||
var fnDontNeedLoad = function(action) { | |||
if (ctx.userLoaded || | |||
(action === 'notify' && ctx.notifyBots && ctx.notifyIndef && !ctx.notifySkipLink && (!ctx.notifySkipTemplates || ctx.notifySkipTemplates.length === 0))) { | |||
return true; | |||
} | |||
return false; | |||
}; | |||
/* | |||
Wrappers for fnSuccess, the joint success function. At the moment, | |||
we're not doing anything unique for any of these, so this is just | |||
for the structure. If we do want to customize for specific | |||
scenarios, they should be broken out. | |||
*/ | |||
var fnBlockSuccess = function() { | |||
fnSuccess('block'); | |||
}; | |||
var fnUnblockSuccess = function() { | |||
fnSuccess('unblock'); | |||
}; | |||
var fnGroupsSuccess = function() { | |||
fnSuccess('groups'); | |||
}; | |||
var fnSuccess = function(action) { | |||
ctx.actionResponse = ctx[action + 'Api'].response; | |||
// `block: block` and `unblock: unblock`, but `groups: userrights` | |||
var exactName = action === 'groups' ? 'userrights' : action; | |||
// The API thinks we're successful if there's a response for the action, | |||
// i.e. there isn't `result: 'Success'` like action=edit | |||
// In theory, userrights could use the combined length of the | |||
// returned arrays as a measure of success? | |||
if (ctx.actionResponse[exactName]) { | |||
action = Morebits.string.toUpperCaseFirstChar(action); | |||
// Display link for user in question on success | |||
var userLink; | |||
if (ctx.isIP) { | |||
userLink = 'Special:Contributions/' + ctx.userName; | |||
} else { | |||
userLink = mw.Title.newFromText(ctx.userName, 2).toText(); | |||
} | |||
var link = document.createElement('a'); | |||
link.setAttribute('href', mw.util.getUrl(userLink)); | |||
link.appendChild(document.createTextNode(userLink)); | |||
ctx.statusElement.info(['completed (', link, ')']); | |||
if (ctx['on' + action + 'Success']) { | |||
ctx['on' + action + 'Success'](this); // invoke callback | |||
} | |||
return; | |||
} | |||
// I don't think getting here is possible? | |||
ctx.statusElement.error('Unknown error received from API'); | |||
++Morebits.wiki.numberOfActionsLeft; // force error to stay on the screen | |||
ctx['on' + action + 'Failure'](this); | |||
}; | |||
/* | |||
Wrappers for fnError, the joint error function. At the moment, | |||
we're not doing anything unique for any of these, so this is just | |||
for the structure. If we do preempt or customize for specific | |||
errors or scenarios, they should be broken out. | |||
*/ | |||
// Callback from blockApi.post(), most likely: alreadyblocked | |||
// (preempted in fnProcessBlock), invalidexpiry, invalidip, | |||
// invalidrange, canthide (preempted in fnProcessBlock) | |||
var fnBlockError = function() { | |||
fnError('block'); | |||
}; | |||
// Callback from unblockApi.post(), most likely: blockedasrange, | |||
// cantunblock (preempted in fnProcessUnblock) | |||
var fnUnblockError = function() { | |||
fnError('unblock'); | |||
}; | |||
// Callback from groupsApi.post(), seems unlikely given how forgiving | |||
// this API is, but could be toofewexpiries | |||
var fnGroupsError = function() { | |||
fnError('groups'); | |||
}; | |||
var fnError = function(action) { | |||
var actionApi = action + 'Api'; | |||
ctx.actionResponse = ctx[actionApi].response; | |||
ctx.statusElement.error('Failed (' + ctx[actionApi].getErrorCode() + ') to ' + | |||
(action === 'groups' ? 'change user groups' : action + ' user') + ': ' + ctx[actionApi].getErrorText()); | |||
action = Morebits.string.toUpperCaseFirstChar(action); | |||
if (ctx['on' + action + 'Error']) { | |||
ctx['on' + action + 'Error'](this); // invoke callback | |||
} | |||
}; | |||
/* Setters */ | |||
/** @param {string} reason - Text of the reason that will be used for the log entry, or the edit summary if provided to `notify`. */ | |||
this.setReason = function(reason) { | |||
ctx.reason = reason; | |||
}; | |||
/** | |||
* Set any custom tag(s) to be applied to the action. | |||
* | |||
* @param {string|string[]} tags - String or array of tag(s). | |||
*/ | |||
this.setChangeTags = function(tags) { | |||
ctx.changeTags = tags; | |||
}; | |||
/** | |||
* Set the expiration for a block or any added user groups. | |||
* | |||
* @param {string|number|string[]|number[]|Morebits.date|Date} [expiry=infinity] - | |||
* A date-like string or number or a date object, or an array of | |||
* strings or numbers. Strings and numbers 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;e60852d30c2d4ba0d249ac6ade638eb41b5191e6$60-107?as=source&blame=off} | |||
* | |||
* The `groups` method accepts an array of expirations for added | |||
* groups: it must list them in the same order and contain the same | |||
* number of entries; otherwise provide just one, which will be used | |||
* for all added groups. | |||
*/ | |||
this.setExpiry = function(expiry) { | |||
if (!expiry || (Array.isArray(expiry) && !expiry.length)) { | |||
expiry = 'infinity'; | |||
} else if (expiry instanceof Morebits.date || expiry instanceof Date) { | |||
expiry = expiry.toISOString(); | |||
} | |||
ctx.expiry = expiry; | |||
}; | |||
/** | |||
* Define an object for use in a callback function. | |||
* `callbackParameters` is for use by the caller only. The parameters | |||
* allow a caller to pass the proper context into its callback | |||
* function. | |||
* | |||
* @param {object} callbackParameters | |||
*/ | |||
this.setCallbackParameters = function(callbackParameters) { | |||
ctx.callbackParameters = callbackParameters; | |||
}; | |||
/** | |||
* @returns {object} - The object previously set by `setCallbackParameters()`. | |||
*/ | |||
this.getCallbackParameters = function() { | |||
return ctx.callbackParameters; | |||
}; | |||
/** | |||
* @param {Morebits.status} statusElement | |||
*/ | |||
this.setStatusElement = function(statusElement) { | |||
ctx.statusElement = statusElement; | |||
}; | |||
/** | |||
* @returns {Morebits.status} Status element created by the constructor. | |||
*/ | |||
this.getStatusElement = function() { | |||
return ctx.statusElement; | |||
}; | |||
/** | |||
* Whether or not to watch the user in question when performing the | |||
* chosen action. Note that unlike {@link Morebits.wiki.page#setWatchlist}, | |||
* this is a binary option. For the notify action, however, | |||
* {@link Morebits.wiki.user#setPageobjectFunctions} can be used to set | |||
* more complex watching options. Only works for unblock and | |||
* userrights by a hack in {@link Morebits.wiki.user#~fnBaseAction|fnBaseAction}. | |||
* | |||
* @param {boolean} watchuser - True to watch the user page, false to | |||
* make no change. | |||
*/ | |||
this.setWatchuser = function(watchuser) { | |||
ctx.watchUser = !!watchuser; | |||
}; | |||
// This does not, like Morebits.wiki.page, currently take into account | |||
// the prior watched status of the user page, including temporary | |||
// status. Likewise, there's currently no fnApplyWatchlistExpiry here | |||
// in Morebits.wiki.user to determine whether and how to provide the | |||
// expiry. We could, but it's a lot for little payoff. | |||
/** | |||
* @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; | |||
}; | |||
/* Block setters */ | |||
/** | |||
* Determine whether to default block parameters to the preexisting | |||
* block parameters, if present. Must be used before `load`ing the | |||
* user. | |||
* | |||
* @param {boolean} [useOriginalBlockParams=true] | |||
*/ | |||
this.useOriginalBlock = function(useOriginalBlockParams) { | |||
ctx.useOriginalBlockParams = !!useOriginalBlockParams; | |||
}; | |||
/** @param {boolean} allowusertalk */ | |||
this.setAllowusertalk = function(allowusertalk) { | |||
ctx.allowusertalk = !!allowusertalk; | |||
}; | |||
/** @param {boolean} anononly */ | |||
this.setAnononly = function(anononly) { | |||
ctx.anonOnly = !!anononly; | |||
}; | |||
/** @param {boolean} autoblock */ | |||
this.setAutoblock = function(autoblock) { | |||
ctx.autoblock = !!autoblock; | |||
}; | |||
/** @param {boolean} nocreate */ | |||
this.setNocreate = function(nocreate) { | |||
ctx.nocreate = !!nocreate; | |||
}; | |||
/** @param {boolean} noemail */ | |||
this.setNoemail = function(noemail) { | |||
ctx.noemail = !!noemail; | |||
}; | |||
/** @param {boolean} reblock */ | |||
this.setReblock = function(reblock) { | |||
ctx.reblock = !!reblock; | |||
}; | |||
/** @param {boolean} hidename */ | |||
this.setHidename = function(hidename) { | |||
ctx.hidename = !!hidename; | |||
}; | |||
/* Partial blocks */ | |||
/** @param {boolean} partial */ | |||
this.setPartial = function(partial) { | |||
ctx.partial = !!partial; | |||
}; | |||
/** @param {string|string[]} pages - String or array of page name(s). */ | |||
this.setPartialPages = function(pages) { | |||
ctx.pagerestrictions = pages; | |||
}; | |||
/** | |||
* @param {string|number|string[]|number[]} namespaces - String(s) or | |||
* numbers() of namespace number(s). If strings, separate namespaces | |||
* by `|`. | |||
*/ | |||
this.setPartialNamespaces = function(namespaces) { | |||
ctx.namespacerestrictions = namespaces; | |||
}; | |||
/* User group setters */ | |||
/** | |||
* @param {string|string[]} addGroups - String or array of user group(s) | |||
* Forgiving: anything invalid is simply ignored by the API with a warning. | |||
*/ | |||
this.setAddGroups = function(addGroups) { | |||
ctx.addGroups = addGroups; | |||
}; | |||
/** | |||
* @param {string|string[]} removeGroups - String or array of user group(s) | |||
* Forgiving: anything invalid is simply ignored by the API with a warning. | |||
*/ | |||
this.setRemoveGroups = function(removeGroups) { | |||
ctx.removeGroups = removeGroups; | |||
}; | |||
/* Notification setters */ | |||
/** @param {boolean} [notifyBots=false] */ | |||
this.setNotifyBots = function(notifyBots) { | |||
ctx.notifyBots = !!notifyBots; | |||
}; | |||
/** @param {boolean} [notifyIndef=false] - Whether to notify users who are indefinitely blocked sitewide. */ | |||
this.setNotifyIndef = function(notifyIndef) { | |||
ctx.notifyIndef = !!notifyIndef; | |||
}; | |||
/** @param {boolean} [notifySelf=false] */ | |||
this.setNotifySelf = function(notifySelf) { | |||
ctx.notifySelf = !!notifySelf; | |||
}; | |||
/** | |||
* Provide templates and/or an external link, any of which, if | |||
* detected, will result in skipping a talkpage notification. Can be | |||
* provided before or after the user is loaded. | |||
* | |||
* @param {string} [link] - An external link, either `http`, `https`, | |||
* or with no protocol provided. | |||
* @param {string|string[]} [templates] - A template or array of | |||
* templates; must include the namespace. | |||
*/ | |||
this.setNotifySkips = function(link, templates) { | |||
if (link) { | |||
// Remove leading protocol, be http/https insensitive | |||
ctx.notifySkipLink = link.replace(/^https?:\/\//, ''); | |||
} | |||
if (templates) { | |||
if (!Array.isArray(templates)) { | |||
templates = [templates]; | |||
} | |||
// The API will kindly ignore underscores, but if we set this | |||
// before loading the page, we'll need to be able to compare | |||
// the results to this list. Alternatively, we could do regex | |||
// matching in fnProcessNotify rather than checking for dups. | |||
ctx.notifySkipTemplates = Morebits.array.uniq(templates).map(function(template) { | |||
return template.replace(/_/, ' '); | |||
}); | |||
} | |||
}; | |||
/** | |||
* Set the text of the notification to be appended to user's talk | |||
* page. If `setSectionTitle` is not used, should also contain | |||
* wikitext for the section title. | |||
* | |||
* @param {string} message | |||
*/ | |||
this.setMessage = function(message) { | |||
ctx.message = message; | |||
}; | |||
/** | |||
* Create a new section, using this as the section title. | |||
* `setMessage` will set the section body. | |||
* | |||
* @param {string} title | |||
*/ | |||
this.setSectionTitle = function(title) { | |||
ctx.sectionTitle = title; | |||
}; | |||
/** | |||
* Define an object of functions and values to apply to the | |||
* Morebits.wiki.page object used to notify the user talk page in | |||
* question. Will be performed last, so is useful for applying | |||
* additional bespoke parameters, such as `setMinorEdit` or more complex | |||
* watch options to `setWatchlist`. | |||
* | |||
* @param {object} pageobjectFunctions - An object with `{function: | |||
* functionValue}` parameters. Each key is the name of a | |||
* {@link Morebits.wiki.page} function, and its value is what will be | |||
* provided to that function. | |||
*/ | |||
this.setPageobjectFunctions = function(pageobjectFunctions) { | |||
ctx.pageobjectFunctions = pageobjectFunctions; | |||
}; | |||
/* Getters */ | |||
/** @returns {string} */ | |||
this.getUserName = function() { | |||
return ctx.userName; | |||
}; | |||
/** | |||
* @returns {boolean} - True if the user is a registered account or an | |||
* IP, false if unregistered account. | |||
*/ | |||
this.exists = function() { | |||
return ctx.exists; | |||
}; | |||
/** @returns {number} */ | |||
this.getUserID = function() { | |||
return ctx.userID; | |||
}; | |||
/** @returns {string} - ISO 8601 timestamp at which the user account was registered locally. */ | |||
this.getRegistration = function() { | |||
return ctx.registration; | |||
}; | |||
/** @returns {number} */ | |||
this.getEditCount = function() { | |||
return ctx.editCount; | |||
}; | |||
/** @returns {boolean} */ | |||
this.isIP = function() { | |||
return ctx.isIP; | |||
}; | |||
/** @returns {boolean} */ | |||
this.isIPRange = function() { | |||
return ctx.isIPRange; | |||
}; | |||
/** @returns {string[]} Array of all groups the user has. */ | |||
this.getGroups = function() { | |||
return ctx.groups; | |||
}; | |||
/** @returns {string[]} Array of automatically added groups, e.g. `autoconfirmed`. */ | |||
this.getImplicitGroups = function() { | |||
return ctx.autoGroups; | |||
}; | |||
/** @returns {string[]} Array of all granted groups. */ | |||
this.getGrantedGroups = function() { | |||
return ctx.grantedGroups && Object.keys(ctx.grantedGroups); | |||
}; | |||
/** | |||
* @param {string} group - e.g. `rollbacker`, `founder`. | |||
* @returns {boolean} | |||
*/ | |||
this.isInGroup = function(group) { | |||
return ctx.groups && ctx.groups.indexOf(group) !== -1; | |||
}; | |||
/** | |||
* @param {string} group - Only valid for granted groups | |||
* (e.g. `rollbacker`, `founder`), not implicit groups like `autoconfirmed`. | |||
* @returns {string} - `Infinity` or ISO 8601 timestamp when the group will expire. | |||
*/ | |||
this.getGroupExpiry = function(group) { | |||
return ctx.grantedGroups && !!ctx.grantedGroups[group] && ctx.grantedGroups[group]; | |||
}; | |||
/** @returns {string[]} - All rights the user has. */ | |||
this.getRights = function() { | |||
return ctx.userRights; | |||
}; | |||
/** | |||
* @param {string} right - e.g. `minoredit`, `editsitejs`, etc. | |||
* @returns {boolean} | |||
*/ | |||
this.hasRight = function(right) { | |||
return ctx.userRights && ctx.userRights.indexOf(right) !== -1; | |||
}; | |||
/** @returns {boolean} */ | |||
this.isHidden = function() { | |||
return ctx.hidden; | |||
}; | |||
/** @returns {boolean} */ | |||
this.isSysop = function() { | |||
return ctx.grantedGroups && !!ctx.grantedGroups.sysop; | |||
}; | |||
/** | |||
* @returns {boolean} - True if the user has the bot group or their | |||
* username matches {@link Morebits.l10n.botUsernameRegex}. | |||
*/ | |||
this.isBot = function() { | |||
return (ctx.grantedGroups && !!ctx.grantedGroups.bot) || (Morebits.l10n.botUsernameRegex && Morebits.l10n.botUsernameRegex.test(ctx.userName)); | |||
}; | |||
/** @returns {string} - ISO 8601 timestamp at which the user was loaded. */ | |||
this.getLoadTime = function() { | |||
return ctx.loadTime; | |||
}; | |||
/** @returns {boolean} - Whether the user has a block log. */ | |||
this.hasBlockLog = function() { | |||
return ctx.hasBlockLog; | |||
}; | |||
/** | |||
* @returns {object} - The full parameters of the most recent block | |||
* log entry, e.g. logid, action, params, etc. If the user was not | |||
* directly blocked - i.e. was just rangeblocked - that block will no | |||
* appear here. | |||
*/ | |||
this.getLastBlockLogEntry = function() { | |||
return ctx.lastBlockLogEntry && $.extend({}, ctx.lastBlockLogEntry); | |||
}; | |||
/** | |||
* @returns {boolean} - Whether the user is covered by a block. True | |||
* regardless of whether that block is directly on the user in | |||
* question i.e. there's a rangeblock active. | |||
*/ | |||
this.isBlocked = function() { | |||
return ctx.isBlocked; | |||
}; | |||
/** @returns {boolean} */ | |||
this.isRangeBlocked = function() { | |||
return ctx.isRangeBlocked; | |||
}; | |||
/** @returns {string} - The widest active rangeblock. */ | |||
this.getBlockedRange = function() { | |||
return ctx.blockedRange; | |||
}; | |||
/** | |||
* @returns {object} - The full parameters of the current active | |||
* block, e.g. expiry, nocreate, partial restrictions, etc. If the | |||
* user is not directly blocked - i.e. there's just a rangeblock - | |||
* this will be the most recent active block. | |||
*/ | |||
this.getBlockInfo = function() { | |||
return ctx.blockInfo && $.extend({}, ctx.blockInfo); | |||
}; | |||
/** @returns {string} */ | |||
this.getBlockingSysop = function() { | |||
return ctx.blockInfo && ctx.blockInfo.by; | |||
}; | |||
/** @returns {string} */ | |||
this.getBlockTimestamp = function() { | |||
return ctx.blockInfo && ctx.blockInfo.timestamp; | |||
}; | |||
/** @returns {string} */ | |||
this.getBlockExpiry = function() { | |||
return ctx.blockInfo && ctx.blockInfo.expiry; | |||
}; | |||
/** @returns {string} */ | |||
this.getBlockReason = function() { | |||
return ctx.blockInfo && ctx.blockInfo.reason; | |||
}; | |||
/** @returns {boolean} */ | |||
this.getAllowusertalk = function() { | |||
return ctx.blockInfo && !!ctx.blockInfo.allowusertalk; | |||
}; | |||
/** @returns {boolean} */ | |||
this.getAnononly = function() { | |||
return ctx.blockInfo && !!ctx.blockInfo.anononly; | |||
}; | |||
/** @returns {boolean} */ | |||
this.getAutoblock = function() { | |||
return ctx.blockInfo && !!ctx.blockInfo.autoblock; | |||
}; | |||
/** @returns {boolean} */ | |||
this.getNocreate = function() { | |||
return ctx.blockInfo && !!ctx.blockInfo.nocreate; | |||
}; | |||
/** @returns {boolean} */ | |||
this.getNoemail = function() { | |||
return ctx.blockInfo && !!ctx.blockInfo.noemail; | |||
}; | |||
/** @returns {boolean} */ | |||
this.getHidename = function() { | |||
return ctx.blockInfo && !!ctx.blockInfo.hidename; | |||
}; | |||
/** @returns {boolean} */ | |||
this.getPartial = function() { | |||
return ctx.blockInfo && !!ctx.blockInfo.partial; | |||
}; | |||
/** @returns {string[]} */ | |||
this.getPartialPages = function() { | |||
// Force into array of titles, ditch ns (included in title) and page ID | |||
return ctx.blockInfo && !!ctx.blockInfo.restrictions.length && ctx.blockInfo.restrictions.pages.map(function(rp) { | |||
return rp.title; | |||
}); | |||
}; | |||
/** @returns {number[]} */ | |||
this.getPartialNamespaces = function() { | |||
return ctx.blockInfo && !!ctx.blockInfo.restrictions.length && ctx.blockInfo.restrictions.namespaces; | |||
}; | |||
/** @returns {string} - Title of the user talk page, or where it points if a redirect. */ | |||
this.getTalkTitle = function() { | |||
return ctx.talkTitle; | |||
}; | |||
/** @returns {string} - Text of the user talk page. */ | |||
this.getTalkText = function() { | |||
return ctx.talkText; | |||
}; | |||
/** @returns {boolean} */ | |||
this.getTalkExists = function() { | |||
return ctx.talkExists; | |||
}; | |||
/** @returns {string} - Timestamp of the last revision. */ | |||
this.getTalkTimestamp = function() { | |||
return ctx.talkTimestamp; | |||
}; | |||
/** @returns {string} - Username. */ | |||
this.getTalkLastEditor = function() { | |||
return ctx.talkLastEditor; | |||
}; | |||
/** | |||
* @returns {string[]} - The templates on the user's talk page, | |||
* including the namespace prefix. If `setNotifySkips` sets skip | |||
* templates before loading, this will only return the presence or | |||
* absence of those items. | |||
*/ | |||
this.getTalkTemplates = function() { | |||
return ctx.talkTemplates; | |||
}; | |||
/** | |||
* @returns {string[]} - The external links on the user's talk page. | |||
* If `setNotifySkips` sets a skip link before loading, this will only | |||
* return the presence or absence of that item. | |||
*/ | |||
this.getTalkLinks = function() { | |||
return ctx.talkLinks; | |||
}; | |||
/** | |||
* Get the post-action response object from the API. | |||
* | |||
* @returns {object} | |||
*/ | |||
this.getActionResponse = function() { | |||
return ctx.actionResponse; | |||
}; | |||
}; // end Morebits.wiki.user | |||
/* **************** Morebits.wiki.preview **************** */ | |||
/** | |||
* Use the API to parse a fragment of wikitext and render it as HTML. | |||
* | |||
* The suggested implementation pattern (in {@link Morebits.simpleWindow} and | |||
* {@link Morebits.quickForm} situations) is to construct a | |||
* `Morebits.wiki.preview` object after rendering a `Morebits.quickForm`, and | |||
* bind the object to an arbitrary property of the form (e.g. |previewer|). | |||
* For an example, see twinklewarn.js. | |||
* | |||
* @memberof Morebits.wiki | |||
* @class | |||
* @param {HTMLElement} previewbox - The element that will contain the rendered HTML, | |||
* usually a <div> element. | |||
*/ | |||
Morebits.wiki.preview = function(previewbox) { | |||
this.previewbox = previewbox; | |||
$(previewbox).addClass('morebits-previewbox').hide(); | |||
/** | |||
* Displays the preview box, and begins an asynchronous attempt | |||
* to render the specified wikitext. | |||
* | |||
* @param {string} wikitext - Wikitext to render; most things should work, including `subst:` and `~~~~`. | |||
* @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. | |||
* @returns {jQuery.promise} | |||
*/ | |||
this.beginRender = function(wikitext, pageTitle, sectionTitle) { | |||
$(previewbox).show(); | |||
var statusspan = document.createElement('span'); | |||
previewbox.appendChild(statusspan); | |||
Morebits.status.init(statusspan); | |||
var 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' | |||
}; | |||
if (sectionTitle) { | |||
query.section = 'new'; | |||
query.sectiontitle = sectionTitle; | |||
} | |||
var renderApi = new Morebits.wiki.api('loading...', query, fnRenderSuccess, new Morebits.status('Preview')); | |||
return renderApi.post(); | |||
}; | |||
var fnRenderSuccess = function(apiobj) { | |||
var response = apiobj.getResponse(); | |||
var html = response.parse.text; | |||
if (!html) { | |||
apiobj.statelem.error('failed to retrieve preview, or template was blanked'); | |||
return; | |||
} | |||
previewbox.innerHTML = html; | |||
mw.loader.load(response.parse.modulestyles); | |||
mw.loader.load(response.parse.modules); | |||
// this makes links open in new tab | |||
$(previewbox).find('a').attr('target', '_blank'); | |||
}; | |||
/** Hides the preview box and clears it. */ | |||
this.closePreview = function() { | |||
$(previewbox).empty().hide(); | |||
}; | |||
}; | |||
/* **************** Morebits.wikitext **************** */ | |||
/** | |||
* Wikitext manipulation. | |||
* | |||
* @namespace Morebits.wikitext | |||
* @memberof Morebits | |||
*/ | */ | ||
Morebits.wikitext = {}; | Morebits.wikitext = {}; | ||
Line 4,810: | Line 6,350: | ||
* @param {string} text - Wikitext containing a template. | * @param {string} text - Wikitext containing a template. | ||
* @param {number} [start=0] - Index noting where in the text the template begins. | * @param {number} [start=0] - Index noting where in the text the template begins. | ||
* @ | * @returns {object} `{name: templateName, parameters: {key: value}}`. | ||
*/ | */ | ||
Morebits.wikitext.parseTemplate = function(text, start) { | Morebits.wikitext.parseTemplate = function(text, start) { | ||
start = start || 0; | start = start || 0; | ||
var level = []; // Track of how deep we are ({{, {{{, or [[) | |||
var count = -1; // Number of parameters found | |||
var unnamed = 0; // Keep track of what number an unnamed parameter should receive | |||
var equals = -1; // After finding "=" before a parameter, the index; otherwise, -1 | |||
var current = ''; | |||
var result = { | |||
name: '', | name: '', | ||
parameters: {} | parameters: {} | ||
}; | }; | ||
var key, value; | |||
/** | /** | ||
Line 4,835: | Line 6,375: | ||
// Nothing found yet, this must be the template name | // Nothing found yet, this must be the template name | ||
if (count === -1) { | if (count === -1) { | ||
result.name = current. | result.name = current.substring(2).trim(); | ||
++count; | ++count; | ||
} else { | } else { | ||
Line 4,847: | Line 6,387: | ||
} else { | } else { | ||
// No equals, so it must be unnamed; no trim since whitespace allowed | // No equals, so it must be unnamed; no trim since whitespace allowed | ||
var param = final ? current.substring(equals + 1, current.length - 2) : current; | |||
if (param) { | if (param) { | ||
result.parameters[++unnamed] = param; | result.parameters[++unnamed] = param; | ||
Line 4,856: | Line 6,396: | ||
} | } | ||
for ( | for (var i = start; i < text.length; ++i) { | ||
var test3 = text.substr(i, 3); | |||
if (test3 === '{{{' || (test3 === '}}}' && level[level.length - 1] === 3)) { | if (test3 === '{{{' || (test3 === '}}}' && level[level.length - 1] === 3)) { | ||
current += test3; | current += test3; | ||
Line 4,868: | Line 6,408: | ||
continue; | continue; | ||
} | } | ||
var test2 = text.substr(i, 2); | |||
// Entering a template (or link) | // Entering a template (or link) | ||
if (test2 === '{{' || test2 === '[[') { | if (test2 === '{{' || test2 === '[[') { | ||
Line 4,930: | Line 6,470: | ||
* | * | ||
* @param {string} link_target | * @param {string} link_target | ||
* @ | * @returns {Morebits.wikitext.page} | ||
*/ | */ | ||
removeLink: function(link_target) { | removeLink: function(link_target) { | ||
// Remove a leading colon, to be handled later | |||
if (link_target.indexOf(':') === 0) { | |||
link_target = link_target.slice(1); | |||
} | |||
var link_re_string = '', ns = '', title = link_target; | |||
var idx = link_target.indexOf(':'); | |||
if (idx > 0) { | |||
ns = link_target.slice(0, idx); | |||
title = link_target.slice(idx + 1); | |||
link_re_string = Morebits.namespaceRegex(mw.config.get('wgNamespaceIds')[ns.toLowerCase().replace(/ /g, '_')]) + ':'; | |||
} | } | ||
link_re_string += Morebits.pageNameRegex(title); | |||
// | // Allow for an optional leading colon, e.g. [[:User:Test]] | ||
// | // Files and Categories become links with a leading colon, e.g. [[:File:Test.png]] | ||
var colon = new RegExp(Morebits.namespaceRegex([6, 14])).test(ns) ? ':' : ':?'; | |||
var link_simple_re = new RegExp('\\[\\[' + colon + '(' + link_re_string + ')\\]\\]', 'g'); | |||
var link_named_re = new RegExp('\\[\\[' + colon + link_re_string + '\\|(.+?)\\]\\]', 'g'); | |||
this.text = this.text.replace( | this.text = this.text.replace(link_simple_re, '$1').replace(link_named_re, '$1'); | ||
return this; | return this; | ||
}, | }, | ||
Line 4,960: | Line 6,504: | ||
* @param {string} image - Image name without `File:` prefix. | * @param {string} image - Image name without `File:` prefix. | ||
* @param {string} [reason] - Reason to be included in comment, alongside the commented-out image. | * @param {string} [reason] - Reason to be included in comment, alongside the commented-out image. | ||
* @ | * @returns {Morebits.wikitext.page} | ||
*/ | */ | ||
commentOutImage: function(image, reason) { | commentOutImage: function(image, reason) { | ||
var unbinder = new Morebits.unbinder(this.text); | |||
unbinder.unbind('<!--', '-->'); | unbinder.unbind('<!--', '-->'); | ||
reason = reason ? reason + ': ' : ''; | reason = reason ? reason + ': ' : ''; | ||
var image_re_string = Morebits.pageNameRegex(image); | |||
// Check for normal image links, i.e. [[File:Foobar.png|...]] | // Check for normal image links, i.e. [[File:Foobar.png|...]] | ||
// Will eat the whole link | // Will eat the whole link | ||
var links_re = new RegExp('\\[\\[' + Morebits.namespaceRegex(6) + ':\\s*' + image_re_string + '\\s*[\\|(?:\\]\\])]'); | |||
var allLinks = Morebits.string.splitWeightedByKeys(unbinder.content, '[[', ']]'); | |||
for ( | for (var i = 0; i < allLinks.length; ++i) { | ||
if (links_re.test(allLinks[i])) { | if (links_re.test(allLinks[i])) { | ||
var replacement = '<!-- ' + reason + allLinks[i] + ' -->'; | |||
unbinder.content = unbinder.content.replace(allLinks[i], replacement); | unbinder.content = unbinder.content.replace(allLinks[i], replacement); | ||
} | } | ||
} | } | ||
// unbind the newly created comments | |||
unbinder.unbind('<!--', '-->'); | |||
// Check for gallery images, i.e. instances that must start on a new line, | // Check for gallery images, i.e. instances that must start on a new line, | ||
// eventually preceded with some space, and must include File: prefix | // eventually preceded with some space, and must include File: prefix | ||
// Will eat the whole line. | // Will eat the whole line. | ||
var gallery_image_re = new RegExp('(^\\s*' + Morebits.namespaceRegex(6) + ':\\s*' + image_re_string + '\\s*(?:\\|.*?$|$))', 'mg'); | |||
unbinder.content = unbinder.content.replace(gallery_image_re, '<!-- ' + reason + '$1 -->'); | unbinder.content = unbinder.content.replace(gallery_image_re, '<!-- ' + reason + '$1 -->'); | ||
Line 4,993: | Line 6,537: | ||
// Check free image usages, for example as template arguments, might have the File: prefix excluded, but must be preceded by an | | // 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 | // Will only eat the image name and the preceding bar and an eventual named parameter | ||
var free_image_re = new RegExp('(\\|\\s*(?:[\\w\\s]+\\=)?\\s*(?:' + Morebits.namespaceRegex(6) + ':\\s*)?' + image_re_string + ')', 'mg'); | |||
unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->'); | unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->'); | ||
// Rebind the content now, we are done! | // Rebind the content now, we are done! | ||
Line 5,005: | Line 6,549: | ||
* @param {string} image - Image name without File: prefix. | * @param {string} image - Image name without File: prefix. | ||
* @param {string} data - The display options. | * @param {string} data - The display options. | ||
* @ | * @returns {Morebits.wikitext.page} | ||
*/ | */ | ||
addToImageComment: function(image, data) { | addToImageComment: function(image, data) { | ||
var image_re_string = Morebits.pageNameRegex(image); | |||
var links_re = new RegExp('\\[\\[' + Morebits.namespaceRegex(6) + ':\\s*' + image_re_string + '\\s*[\\|(?:\\]\\])]'); | |||
var allLinks = Morebits.string.splitWeightedByKeys(this.text, '[[', ']]'); | |||
for ( | for (var i = 0; i < allLinks.length; ++i) { | ||
if (links_re.test(allLinks[i])) { | if (links_re.test(allLinks[i])) { | ||
var replacement = allLinks[i]; | |||
// just put it at the end? | // just put it at the end? | ||
replacement = replacement.replace(/\]\]$/, '|' + data + ']]'); | replacement = replacement.replace(/\]\]$/, '|' + data + ']]'); | ||
Line 5,019: | Line 6,563: | ||
} | } | ||
} | } | ||
var gallery_re = new RegExp('^(\\s*' + image_re_string + '.*?)\\|?(.*?)$', 'mg'); | |||
var newtext = '$1|$2 ' + data; | |||
this.text = this.text.replace(gallery_re, newtext); | this.text = this.text.replace(gallery_re, newtext); | ||
return this; | return this; | ||
Line 5,030: | Line 6,574: | ||
* @param {string} template - Page name whose transclusions are to be removed, | * @param {string} template - Page name whose transclusions are to be removed, | ||
* include namespace prefix only if not in template namespace. | * include namespace prefix only if not in template namespace. | ||
* @ | * @returns {Morebits.wikitext.page} | ||
*/ | */ | ||
removeTemplate: function(template) { | removeTemplate: function(template) { | ||
var template_re_string = Morebits.pageNameRegex(template); | |||
var links_re = new RegExp('\\{\\{(?:' + Morebits.namespaceRegex(10) + ':)?\\s*' + template_re_string + '\\s*[\\|(?:\\}\\})]'); | |||
var allTemplates = Morebits.string.splitWeightedByKeys(this.text, '{{', '}}', [ '{{{', '}}}' ]); | |||
for ( | for (var i = 0; i < allTemplates.length; ++i) { | ||
if (links_re.test(allTemplates[i])) { | if (links_re.test(allTemplates[i])) { | ||
this.text = this.text.replace(allTemplates[i], ''); | this.text = this.text.replace(allTemplates[i], ''); | ||
Line 5,056: | Line 6,600: | ||
* @param {string|string[]} [preRegex] - Optional regex string or array to match | * @param {string|string[]} [preRegex] - Optional regex string or array to match | ||
* before any template matches (i.e. before `{{`), such as html comments. | * before any template matches (i.e. before `{{`), such as html comments. | ||
* @ | * @returns {Morebits.wikitext.page} | ||
*/ | */ | ||
insertAfterTemplates: function(tag, regex, flags, preRegex) { | insertAfterTemplates: function(tag, regex, flags, preRegex) { | ||
Line 5,080: | Line 6,624: | ||
preRegex = preRegex.join('|'); | preRegex = preRegex.join('|'); | ||
} | } | ||
// Regex is extra complicated to allow for templates with | // Regex is extra complicated to allow for templates with | ||
Line 5,114: | Line 6,659: | ||
* Get the manipulated wikitext. | * Get the manipulated wikitext. | ||
* | * | ||
* @ | * @returns {string} | ||
*/ | */ | ||
getText: function() { | getText: function() { | ||
Line 5,120: | Line 6,665: | ||
} | } | ||
}; | }; | ||
/* *********** Morebits.userspaceLogger ************ */ | /* *********** Morebits.userspaceLogger ************ */ | ||
Line 5,153: | Line 6,699: | ||
* @param {string} logText - Doesn't include leading `#` or `*`. | * @param {string} logText - Doesn't include leading `#` or `*`. | ||
* @param {string} summaryText - Edit summary. | * @param {string} summaryText - Edit summary. | ||
* @ | * @returns {JQuery.Promise} | ||
*/ | */ | ||
this.log = function(logText, summaryText) { | this.log = function(logText, summaryText) { | ||
var def = $.Deferred(); | |||
if (!logText) { | if (!logText) { | ||
return def.reject(); | return def.reject(); | ||
} | } | ||
var page = new Morebits.wiki.page('User:' + mw.config.get('wgUserName') + '/' + logPageName, | |||
'Adding entry to userspace log'); // make this '... to ' + logPageName ? | 'Adding entry to userspace log'); // make this '... to ' + logPageName ? | ||
page.load((pageobj) | page.load(function(pageobj) { | ||
// add blurb if log page doesn't exist or is blank | // add blurb if log page doesn't exist or is blank | ||
var text = pageobj.getPageText() || this.initialText; | |||
// create monthly header if it doesn't exist already | // create monthly header if it doesn't exist already | ||
var date = new Morebits.date(pageobj.getLoadTime()); | |||
if (!date.monthHeaderRegex().exec(text)) { | if (!date.monthHeaderRegex().exec(text)) { | ||
text += '\n\n' + date.monthHeader(this.headerLevel); | text += '\n\n' + date.monthHeader(this.headerLevel); | ||
Line 5,177: | Line 6,723: | ||
pageobj.setCreateOption('recreate'); | pageobj.setCreateOption('recreate'); | ||
pageobj.save(def.resolve, def.reject); | pageobj.save(def.resolve, def.reject); | ||
}); | }.bind(this)); | ||
return def; | return def; | ||
}; | }; | ||
}; | }; | ||
/* **************** Morebits.status **************** */ | /* **************** Morebits.status **************** */ | ||
Line 5,236: | Line 6,783: | ||
Morebits.status.errorEvent = handler; | Morebits.status.errorEvent = handler; | ||
} else { | } else { | ||
throw | throw 'Morebits.status.onError: handler is not a function'; | ||
} | } | ||
}; | }; | ||
Line 5,329: | Line 6,876: | ||
* @param {string} text - Before colon | * @param {string} text - Before colon | ||
* @param {string} status - After colon | * @param {string} status - After colon | ||
* @ | * @returns {Morebits.status} - `status`-type (blue) | ||
*/ | */ | ||
Morebits.status.status = function(text, status) { | Morebits.status.status = function(text, status) { | ||
Line 5,338: | Line 6,885: | ||
* @param {string} text - Before colon | * @param {string} text - Before colon | ||
* @param {string} status - After colon | * @param {string} status - After colon | ||
* @ | * @returns {Morebits.status} - `info`-type (green) | ||
*/ | */ | ||
Morebits.status.info = function(text, status) { | Morebits.status.info = function(text, status) { | ||
Line 5,347: | Line 6,894: | ||
* @param {string} text - Before colon | * @param {string} text - Before colon | ||
* @param {string} status - After colon | * @param {string} status - After colon | ||
* @ | * @returns {Morebits.status} - `warn`-type (red) | ||
*/ | */ | ||
Morebits.status.warn = function(text, status) { | Morebits.status.warn = function(text, status) { | ||
Line 5,356: | Line 6,903: | ||
* @param {string} text - Before colon | * @param {string} text - Before colon | ||
* @param {string} status - After colon | * @param {string} status - After colon | ||
* @ | * @returns {Morebits.status} - `error`-type (bold red) | ||
*/ | */ | ||
Morebits.status.error = function(text, status) { | Morebits.status.error = function(text, status) { | ||
Line 5,370: | Line 6,917: | ||
*/ | */ | ||
Morebits.status.actionCompleted = function(text) { | Morebits.status.actionCompleted = function(text) { | ||
var node = document.createElement('div'); | |||
node.appendChild(document.createElement('b')).appendChild(document.createTextNode(text)); | node.appendChild(document.createElement('b')).appendChild(document.createTextNode(text)); | ||
node.className = 'morebits_status_info morebits_action_complete'; | node.className = 'morebits_status_info morebits_action_complete'; | ||
Line 5,387: | Line 6,934: | ||
*/ | */ | ||
Morebits.status.printUserText = function(comments, message) { | Morebits.status.printUserText = function(comments, message) { | ||
var p = document.createElement('p'); | |||
p.innerHTML = message; | p.innerHTML = message; | ||
var div = document.createElement('div'); | |||
div.className = ' | div.className = 'toccolours'; | ||
div.style.marginTop = '0'; | div.style.marginTop = '0'; | ||
div.style.whiteSpace = 'pre-wrap'; | div.style.whiteSpace = 'pre-wrap'; | ||
Line 5,397: | Line 6,944: | ||
Morebits.status.root.appendChild(p); | Morebits.status.root.appendChild(p); | ||
}; | }; | ||
/** | /** | ||
Line 5,404: | Line 6,953: | ||
* @param {string} content - Text content. | * @param {string} content - Text content. | ||
* @param {string} [color] - Font color. | * @param {string} [color] - Font color. | ||
* @ | * @returns {HTMLElement} | ||
*/ | */ | ||
Morebits.htmlNode = function (type, content, color) { | Morebits.htmlNode = function (type, content, color) { | ||
var node = document.createElement(type); | |||
if (color) { | if (color) { | ||
node.style.color = color; | node.style.color = color; | ||
Line 5,414: | Line 6,963: | ||
return node; | return node; | ||
}; | }; | ||
/** | /** | ||
Line 5,424: | Line 6,975: | ||
*/ | */ | ||
Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) { | Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) { | ||
var lastCheckbox = null; | |||
function clickHandler(event) { | function clickHandler(event) { | ||
var thisCb = this; | |||
if (event.shiftKey && lastCheckbox !== null) { | if (event.shiftKey && lastCheckbox !== null) { | ||
var cbs = $(jQuerySelector, jQueryContext); // can't cache them, obviously, if we want to support resorting | |||
var index = -1, lastIndex = -1, i; | |||
for (i = 0; i < | for (i = 0; i < cbs.length; i++) { | ||
if ( | if (cbs[i] === thisCb) { | ||
index = i; | index = i; | ||
if (lastIndex > -1) { | if (lastIndex > -1) { | ||
Line 5,438: | Line 6,989: | ||
} | } | ||
} | } | ||
if ( | if (cbs[i] === lastCheckbox) { | ||
lastIndex = i; | lastIndex = i; | ||
if (index > -1) { | if (index > -1) { | ||
Line 5,448: | Line 6,999: | ||
if (index > -1 && lastIndex > -1) { | if (index > -1 && lastIndex > -1) { | ||
// inspired by wikibits | // inspired by wikibits | ||
var endState = thisCb.checked; | |||
var start, finish; | |||
if (index < lastIndex) { | if (index < lastIndex) { | ||
start = index + 1; | start = index + 1; | ||
Line 5,459: | Line 7,010: | ||
for (i = start; i <= finish; i++) { | for (i = start; i <= finish; i++) { | ||
if ( | if (cbs[i].checked !== endState) { | ||
cbs[i].click(); | |||
} | } | ||
} | } | ||
Line 5,469: | Line 7,020: | ||
} | } | ||
$(jQuerySelector, jQueryContext). | $(jQuerySelector, jQueryContext).click(clickHandler); | ||
}; | }; | ||
/* **************** Morebits.batchOperation **************** */ | /* **************** Morebits.batchOperation **************** */ | ||
Line 5,499: | Line 7,052: | ||
* | * | ||
* If using `preserveIndividualStatusLines`, you should try to ensure that the | * If using `preserveIndividualStatusLines`, you should try to ensure that the | ||
* `workerSuccess` callback has access to the page title. This is no problem | * `workerSuccess` callback has access to the page title. This is no problem | ||
* {@link Morebits.wiki.page} objects. But when using the API, please set the | * for {@link Morebits.wiki.page} or {@link Morebits.wiki.user} objects. But | ||
* when using the API, please set the |pageName| property on the {@link Morebits.wiki.api} object. | |||
* | * | ||
* There are sample batchOperation implementations using Morebits.wiki.page in | * There are sample batchOperation implementations using Morebits.wiki.page in | ||
Line 5,511: | Line 7,064: | ||
*/ | */ | ||
Morebits.batchOperation = function(currentAction) { | Morebits.batchOperation = function(currentAction) { | ||
var ctx = { | |||
// backing fields for public properties | // backing fields for public properties | ||
pageList: null, | pageList: null, | ||
Line 5,585: | Line 7,138: | ||
ctx.pageChunks = []; | ctx.pageChunks = []; | ||
var total = ctx.pageList.length; | |||
if (!total) { | if (!total) { | ||
ctx.statusElement.info(msg('batch-no-pages', 'no pages specified')); | ctx.statusElement.info(msg('batch-no-pages', 'no pages specified')); | ||
Line 5,607: | Line 7,160: | ||
* To be called by worker before it terminates successfully. | * To be called by worker before it terminates successfully. | ||
* | * | ||
* @param {(Morebits.wiki.page|Morebits.wiki.api|string)} arg - | * @param {(Morebits.wiki.page|Morebits.wiki.user|Morebits.wiki.api|string)} arg - | ||
* This should be the `Morebits.wiki.page` or `Morebits.wiki.api` object used by worker | * This should be the `Morebits.wiki.page`, `Morebits.wiki.user`, or | ||
* `Morebits.wiki.api` object used by worker (for the adjustment of | |||
* status lines emitted by them). If no Morebits.wiki.* object is | |||
* `preserveIndividualStatusLines` option is on, give the page name (string) as argument. | * used (e.g. you're using `mw.Api()` or something else), and | ||
* `preserveIndividualStatusLines` option is on, give the page name | |||
* (string) as argument. | |||
*/ | */ | ||
this.workerSuccess = function(arg) { | this.workerSuccess = function(arg) { | ||
if (arg instanceof Morebits.wiki.api || arg instanceof Morebits.wiki.page) { | if (arg instanceof Morebits.wiki.api || arg instanceof Morebits.wiki.page || arg instanceof Morebits.wiki.user) { | ||
// update or remove status line | // update or remove status line | ||
var statelem = arg.getStatusElement(); | |||
if (ctx.options.preserveIndividualStatusLines) { | if (ctx.options.preserveIndividualStatusLines) { | ||
if (arg. | var pageName; | ||
if (arg instanceof Morebits.wiki.api) { | |||
pageName = arg.pageName || arg.query.title; | |||
} else if (arg instanceof Morebits.wiki.page) { | |||
pageName = arg.getPageName(); | |||
} else { // Morebits.wiki.user | |||
pageName = mw.Title.newFromText(arg.getUserName(), 2).toText(); | |||
} | |||
if (pageName) { | |||
// we know the page title - display a relevant message | // we know the page title - display a relevant message | ||
statelem.info(msg('batch-done-page', pageName, 'completed ([[' + pageName + ']])')); | statelem.info(msg('batch-done-page', pageName, 'completed ([[' + pageName + ']])')); | ||
} else { | } else { | ||
Line 5,646: | Line 7,208: | ||
// private functions | // private functions | ||
var thisProxy = this; | |||
var fnStartNewChunk = function() { | var fnStartNewChunk = function() { | ||
var chunk = ctx.pageChunks[++ctx.currentChunkIndex]; | |||
if (!chunk) { | if (!chunk) { | ||
return; // done! yay | return; // done! yay | ||
} | } | ||
// start workers for the current chunk | // start workers for the current chunk | ||
ctx.countStarted += chunk.length; | ctx.countStarted += chunk.length; | ||
chunk.forEach((page) | chunk.forEach(function(page) { | ||
ctx.worker(page, thisProxy); | ctx.worker(page, thisProxy); | ||
}); | }); | ||
Line 5,665: | Line 7,227: | ||
// update overall status line | // update overall status line | ||
var total = ctx.pageList.length; | |||
if (ctx.countFinished < total) { | if (ctx.countFinished < total) { | ||
var progress = Math.round(100 * ctx.countFinished / total); | |||
ctx.statusElement.status(msg('percent', progress, progress + '%')); | ctx.statusElement.status(msg('percent', progress, progress + '%')); | ||
Line 5,677: | Line 7,239: | ||
} | } | ||
} else if (ctx.countFinished === total) { | } else if (ctx.countFinished === total) { | ||
var statusString = msg('batch-progress', ctx.countFinishedSuccess, ctx.countFinished, 'Done (' + ctx.countFinishedSuccess + | |||
'/' + ctx.countFinished + ' actions completed successfully)'); | '/' + ctx.countFinished + ' actions completed successfully)'); | ||
if (ctx.countFinishedSuccess < ctx.countFinished) { | if (ctx.countFinishedSuccess < ctx.countFinished) { | ||
Line 5,714: | Line 7,276: | ||
this.failureCallbackMap = new Map(); | this.failureCallbackMap = new Map(); | ||
this.deferreds = new Map(); | this.deferreds = new Map(); | ||
this.allDeferreds = []; // Hack: IE doesn't support Map.prototype.values | |||
this.context = context || window; | this.context = context || window; | ||
Line 5,729: | Line 7,292: | ||
this.add = function(func, deps, onFailure) { | this.add = function(func, deps, onFailure) { | ||
this.taskDependencyMap.set(func, deps); | this.taskDependencyMap.set(func, deps); | ||
this.failureCallbackMap.set(func, onFailure || | this.failureCallbackMap.set(func, onFailure || function() {}); | ||
var deferred = $.Deferred(); | |||
this.deferreds.set(func, deferred); | this.deferreds.set(func, deferred); | ||
this.allDeferreds.push(deferred); | |||
}; | }; | ||
Line 5,737: | Line 7,301: | ||
* Run all the tasks. Multiple tasks may be run at once. | * Run all the tasks. Multiple tasks may be run at once. | ||
* | * | ||
* @ | * @returns {jQuery.Promise} - Resolved if all tasks succeed, rejected otherwise. | ||
*/ | */ | ||
this.execute = function() { | this.execute = function() { | ||
var self = this; // proxy for `this` for use inside functions where `this` is something else | |||
this.taskDependencyMap.forEach((deps, task) | this.taskDependencyMap.forEach(function(deps, task) { | ||
var dependencyPromisesArray = deps.map(function(dep) { | |||
return self.deferreds.get(dep); | |||
}); | |||
$.when.apply(self.context, dependencyPromisesArray).then(function() { | $.when.apply(self.context, dependencyPromisesArray).then(function() { | ||
var result = task.apply(self.context, arguments); | |||
if (result === undefined) { // maybe the function threw, or it didn't return anything | if (result === undefined) { // maybe the function threw, or it didn't return anything | ||
mw.log.error('Morebits.taskManager: task returned undefined'); | mw.log.error('Morebits.taskManager: task returned undefined'); | ||
Line 5,760: | Line 7,326: | ||
}); | }); | ||
}); | }); | ||
return $.when.apply(null, | return $.when.apply(null, this.allDeferreds); // resolved when everything is done! | ||
}; | }; | ||
Line 5,770: | Line 7,336: | ||
* @memberof Morebits | * @memberof Morebits | ||
* @class | * @class | ||
* @requires | * @requires jquery.ui.dialog | ||
* @param {number} width | * @param {number} width | ||
* @param {number} height - The maximum allowable height for the content area. | * @param {number} height - The maximum allowable height for the content area. | ||
*/ | */ | ||
Morebits.simpleWindow = function SimpleWindow(width, height) { | Morebits.simpleWindow = function SimpleWindow(width, height) { | ||
var content = document.createElement('div'); | |||
this.content = content; | this.content = content; | ||
content.className = 'morebits-dialog-content'; | content.className = 'morebits-dialog-content'; | ||
Line 5,786: | Line 7,352: | ||
buttons: { 'Placeholder button': function() {} }, | buttons: { 'Placeholder button': function() {} }, | ||
dialogClass: 'morebits-dialog', | dialogClass: 'morebits-dialog', | ||
width: Math.min(parseInt(window.innerWidth, 10), parseInt(width | 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 | // give jQuery the given height value (which represents the anticipated height of the dialog) here, so | ||
// it can position the dialog appropriately | // it can position the dialog appropriately | ||
Line 5,813: | Line 7,379: | ||
}); | }); | ||
var $widget = $(this.content).dialog('widget'); | |||
// delete the placeholder button (it's only there so the buttonpane gets created) | // delete the placeholder button (it's only there so the buttonpane gets created) | ||
$widget.find('button').each((key, value) | $widget.find('button').each(function(key, value) { | ||
value.parentNode.removeChild(value); | value.parentNode.removeChild(value); | ||
}); | }); | ||
// add container for the buttons we add, and the footer links (if any) | // add container for the buttons we add, and the footer links (if any) | ||
var buttonspan = document.createElement('span'); | |||
buttonspan.className = 'morebits-dialog-buttons'; | buttonspan.className = 'morebits-dialog-buttons'; | ||
var linksspan = document.createElement('span'); | |||
linksspan.className = 'morebits-dialog-footerlinks'; | linksspan.className = 'morebits-dialog-footerlinks'; | ||
$widget.find('.ui-dialog-buttonpane').append(buttonspan, linksspan); | $widget.find('.ui-dialog-buttonpane').append(buttonspan, linksspan); | ||
Line 5,829: | Line 7,395: | ||
// resize the scrollbox with the dialog, if one is present | // resize the scrollbox with the dialog, if one is present | ||
$widget.resizable('option', 'alsoResize', '#' + this.content.id + ' .morebits-scrollbox, #' + this.content.id); | $widget.resizable('option', 'alsoResize', '#' + this.content.id + ' .morebits-scrollbox, #' + this.content.id); | ||
}; | }; | ||
Line 5,843: | Line 7,406: | ||
* Focuses the dialog. This might work, or on the contrary, it might not. | * Focuses the dialog. This might work, or on the contrary, it might not. | ||
* | * | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
focus: function() { | focus: function() { | ||
Line 5,855: | Line 7,418: | ||
* | * | ||
* @param {event} [event] | * @param {event} [event] | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
close: function(event) { | close: function(event) { | ||
Line 5,869: | Line 7,432: | ||
* might work, but it is not guaranteed. | * might work, but it is not guaranteed. | ||
* | * | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
display: function() { | display: function() { | ||
if (this.scriptName) { | if (this.scriptName) { | ||
var $widget = $(this.content).dialog('widget'); | |||
$widget.find('.morebits-dialog-scriptname').remove(); | $widget.find('.morebits-dialog-scriptname').remove(); | ||
var scriptnamespan = document.createElement('span'); | |||
scriptnamespan.className = 'morebits-dialog-scriptname'; | scriptnamespan.className = 'morebits-dialog-scriptname'; | ||
scriptnamespan.textContent = this.scriptName + ' \u00B7 '; // U+00B7 MIDDLE DOT = · | scriptnamespan.textContent = this.scriptName + ' \u00B7 '; // U+00B7 MIDDLE DOT = · | ||
$widget.find('.ui-dialog-title').prepend(scriptnamespan); | $widget.find('.ui-dialog-title').prepend(scriptnamespan); | ||
} | } | ||
var dialog = $(this.content).dialog('open'); | |||
if (window.setupTooltips && window.pg && window.pg.re && window.pg.re.diff) { // tie in with NAVPOP | if (window.setupTooltips && window.pg && window.pg.re && window.pg.re.diff) { // tie in with NAVPOP | ||
dialog.parent()[0].ranSetupTooltipsAlready = false; | dialog.parent()[0].ranSetupTooltipsAlready = false; | ||
window.setupTooltips(dialog.parent()[0]); | window.setupTooltips(dialog.parent()[0]); | ||
} | } | ||
this.setHeight(this.height); // init height algorithm | this.setHeight(this.height); // init height algorithm | ||
return this; | return this; | ||
}, | }, | ||
Line 5,894: | Line 7,457: | ||
* | * | ||
* @param {string} title | * @param {string} title | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
setTitle: function(title) { | setTitle: function(title) { | ||
Line 5,906: | Line 7,469: | ||
* | * | ||
* @param {string} name | * @param {string} name | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
setScriptName: function(name) { | setScriptName: function(name) { | ||
Line 5,917: | Line 7,480: | ||
* | * | ||
* @param {number} width | * @param {number} width | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
setWidth: function(width) { | setWidth: function(width) { | ||
Line 5,929: | Line 7,492: | ||
* | * | ||
* @param {number} height | * @param {number} height | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
setHeight: function(height) { | setHeight: function(height) { | ||
Line 5,955: | Line 7,518: | ||
* | * | ||
* @param {HTMLElement} content | * @param {HTMLElement} content | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
setContent: function(content) { | setContent: function(content) { | ||
Line 5,967: | Line 7,530: | ||
* | * | ||
* @param {HTMLElement} content | * @param {HTMLElement} content | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
addContent: function(content) { | addContent: function(content) { | ||
Line 5,973: | Line 7,536: | ||
// look for submit buttons in the content, hide them, and add a proxy button to the button pane | // look for submit buttons in the content, hide them, and add a proxy button to the button pane | ||
var thisproxy = this; | |||
$(this.content).find('input[type="submit"], button[type="submit"]').each((key, value) | $(this.content).find('input[type="submit"], button[type="submit"]').each(function(key, value) { | ||
value.style.display = 'none'; | value.style.display = 'none'; | ||
var button = document.createElement('button'); | |||
button.textContent = value.hasAttribute('value') ? value.getAttribute('value') : value.textContent ? value.textContent : msg('submit', 'Submit Query'); | |||
button.className = value.className || 'submitButtonProxy'; | button.className = value.className || 'submitButtonProxy'; | ||
// here is an instance of cheap coding, probably a memory-usage hit in using a closure here | // here is an instance of cheap coding, probably a memory-usage hit in using a closure here | ||
button.addEventListener('click', () | button.addEventListener('click', function() { | ||
value.click(); | value.click(); | ||
}, false); | }, false); | ||
Line 5,997: | Line 7,552: | ||
$(this.content).dialog('widget').find('.morebits-dialog-buttons').empty().append(this.buttons)[0].removeAttribute('data-empty'); | $(this.content).dialog('widget').find('.morebits-dialog-buttons').empty().append(this.buttons)[0].removeAttribute('data-empty'); | ||
} else { | } else { | ||
$(this.content).dialog('widget').find('.morebits-dialog-buttons')[0].setAttribute('data-empty', 'data-empty'); // used by CSS | $(this.content).dialog('widget').find('.morebits-dialog-buttons')[0].setAttribute('data-empty', 'data-empty'); // used by CSS | ||
} | } | ||
return this; | return this; | ||
Line 6,005: | Line 7,560: | ||
* Removes all contents from the dialog, barring any footer links. | * Removes all contents from the dialog, barring any footer links. | ||
* | * | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
purgeContent: function() { | purgeContent: function() { | ||
Line 6,027: | Line 7,582: | ||
* @param {string} wikiPage - Link target. | * @param {string} wikiPage - Link target. | ||
* @param {boolean} [prep=false] - Set true to prepend rather than append. | * @param {boolean} [prep=false] - Set true to prepend rather than append. | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
addFooterLink: function(text, wikiPage, prep) { | addFooterLink: function(text, wikiPage, prep) { | ||
var $footerlinks = $(this.content).dialog('widget').find('.morebits-dialog-footerlinks'); | |||
if (this.hasFooterLinks) { | if (this.hasFooterLinks) { | ||
var bullet = document.createElement('span'); | |||
bullet.textContent = msg('bullet-separator', ' \u2022 '); // U+2022 BULLET | bullet.textContent = msg('bullet-separator', ' \u2022 '); // U+2022 BULLET | ||
if (prep) { | if (prep) { | ||
$footerlinks.prepend(bullet); | $footerlinks.prepend(bullet); | ||
Line 6,040: | Line 7,595: | ||
} | } | ||
} | } | ||
var link = document.createElement('a'); | |||
link.setAttribute('href', mw.util.getUrl(wikiPage)); | link.setAttribute('href', mw.util.getUrl(wikiPage)); | ||
link.setAttribute('title', wikiPage); | link.setAttribute('title', wikiPage); | ||
Line 6,061: | Line 7,616: | ||
* @param {boolean} [modal=false] - If set to true, other items on the | * @param {boolean} [modal=false] - If set to true, other items on the | ||
* page will be disabled, i.e., cannot be interacted with. | * page will be disabled, i.e., cannot be interacted with. | ||
* @ | * @returns {Morebits.simpleWindow} | ||
*/ | */ | ||
setModality: function(modal) { | setModality: function(modal) { | ||
Line 6,084: | Line 7,639: | ||
}; | }; | ||
}()); | }(window, document, jQuery)); // End wrap with anonymous function | ||
/** | /** | ||
Line 6,110: | Line 7,652: | ||
*/ | */ | ||
if (typeof arguments === 'undefined') { // typeof is here for a reason... | if (typeof arguments === 'undefined') { // typeof is here for a reason... | ||
/* global Morebits */ | /* global Morebits */ | ||
window.SimpleWindow = Morebits.simpleWindow; | window.SimpleWindow = Morebits.simpleWindow; |