MediaWiki:Gadget-morebits.js: Difference between revisions

m
no edit summary
m (104 revisions imported: re-import original)
mNo edit summary
Line 16:
* - The whole thing relies on jQuery. But most wikis should provide this by default.
* - Morebits.quickForm, Morebits.simpleWindow, and Morebits.status rely on the "morebits.css" file for their styling.
* - Morebits.simpleWindow reliesand Morebits.quickForm tooltips rely on jquery UI Dialog (from ResourceLoader module name 'jquery.ui').
* - Morebits.quickForm tooltips rely on Tipsy (ResourceLoader module name 'jquery.tipsy').
* For external installations, Tipsy is available at [http://onehackoranother.com/projects/jquery/tipsy].
* - To create a gadget based on morebits.js, use this syntax in MediaWiki:Gadgets-definition:
* * GadgetName[ResourceLoader|dependencies=mediawiki.user,mediawiki.util,jquerymediawiki.uiTitle,jquery.tipsyui]|morebits.js|morebits.css|GadgetName.js
* - Alternatively, you can configure morebits.js as a hidden gadget in MediaWiki:Gadgets-definition:
* * morebits[ResourceLoader|dependencies=mediawiki.user,mediawiki.util,mediawiki.Title,jquery.ui|hidden]|morebits.js|morebits.css
* and then load ext.gadget.morebits as one of the dependencies for the new gadget
*
* Most ofAll the stuff here doesn't workworks on IE < 9. Itall isbrowsers yourfor script'swhich responsibilityMediaWiki toprovides enforceJavaScript thissupport.
*
* This library is maintained by the maintainers of Twinkle.
Line 30 ⟶ 31:
 
 
(function (window, document, $, undefined) { // Wrap entire file with anonymous function
 
var Morebits = {};
Line 46 ⟶ 47:
return mw.config.get('wgUserGroups').indexOf(group) !== -1;
};
// Used a lot
Morebits.userIsSysop = Morebits.userIsInGroup('sysop');
 
 
Line 54 ⟶ 57:
* includes/utils/IP.php.
* Converts an IPv6 address to the canonical form stored and used by MediaWiki.
* @param {string} address - The IPv6 address
* @returns {string}
*/
Morebits.sanitizeIPv6 = function (address) {
Line 113 ⟶ 118:
*
* select A combo box (aka drop-down).
* - Attributes: name, label, multiple, size, list, event, disabled
* option An element for a combo box.
* - Attributes: value, label, selected, disabled
Line 127 ⟶ 132:
* - Attributes (within list): name, label, value, checked, disabled, event, subgroup
* input A text box.
* - Attributes: name, label, value, size, disabled, required, readonly, maxlength, event
* dyninput A set of text boxes with "Remove" buttons and an "Add" button.
* - Attributes: name, label, min, max, sublabel, value, size, maxlength, event
Line 141 ⟶ 146:
* - Attributes: name, label, disabled, event
* textarea A big, multi-line text box.
* - Attributes: name, label, value, cols, rows, disabled, required, readonly
* fragment A DocumentFragment object.
* - No attributes, and no global attributes except adminonly
Line 150 ⟶ 155:
/**
* @constructor
* @param {event} event - Function to execute when form is submitted
* @param {*string} [eventType=submit] - Type of the event (default: submit)
*/
Morebits.quickForm = function QuickForm(event, eventType) {
Line 169 ⟶ 174:
/**
* Append element to the form
* @param {(Object|Morebits.quickForm.element)} data - a quickform element, or the object with which
* a quickform element is constructed.
* @returns {Morebits.quickForm.element} - same as what is passed to the function
*/
Morebits.quickForm.prototype.append = function QuickFormAppend(data) {
Line 177 ⟶ 184:
/**
* @constructor
* @param {Object} data - Object representing the quickform element. See class documentation
* @param {Object}
* comment for available types and attributes for each.
*/
Morebits.quickForm.element = function QuickFormElement(data) {
Line 224 ⟶ 232:
var label;
var id = (in_id ? in_id + '_' : '') + 'node_' + this.id;
if (data.adminonly && !Morebits.userIsInGroup('sysop')userIsSysop) {
// hell hack alpha
data.type = 'hidden';
Line 261 ⟶ 269:
if (data.size) {
select.setAttribute('size', data.size);
}
if (data.disabled) {
select.setAttribute('disabled', 'disabled');
}
select.setAttribute('name', data.name);
Line 341 ⟶ 352:
subnode.values = current.value;
subnode.setAttribute('value', current.value);
subnode.setAttribute('name', current.name || data.name);
subnode.setAttribute('type', data.type);
subnode.setAttribute('id', cur_id);
subnode.setAttribute('name', current.name || data.name);
 
// If name is provided on the individual checkbox, add a data-single
// attribute which indicates it isn't part of a list of checkboxes with
// same name. Used in getInputData()
if (current.name) {
subnode.setAttribute('data-single', 'data-single');
}
 
if (current.checked) {
Line 425 ⟶ 443:
}
}
}
if (data.shiftClickSupport && data.type === 'checkbox') {
Morebits.checkboxShiftClickSupport(Morebits.quickForm.getElements(node, data.name));
}
break;
Line 434 ⟶ 455:
label = node.appendChild(document.createElement('label'));
label.appendChild(document.createTextNode(data.label));
label.setAttribute('for', data.id || id);
}
 
Line 442 ⟶ 463:
}
subnode.setAttribute('name', data.name);
subnode.setAttribute('id', id);
subnode.setAttribute('type', 'text');
if (data.size) {
Line 449 ⟶ 469:
if (data.disabled) {
subnode.setAttribute('disabled', 'disabled');
}
if (data.required) {
subnode.setAttribute('required', 'required');
}
if (data.readonly) {
Line 459 ⟶ 482:
subnode.addEventListener('keyup', data.event, false);
}
childContainder = subnode;
break;
case 'dyninput':
Line 623 ⟶ 647:
if (data.label) {
label = node.appendChild(document.createElement('h5'));
label.appendChild(var labelElement = document.createTextNodecreateElement(data.'label)');
labelElement.textContent = data.label;
// TODO need to nest a <label> tag in here without creating extra vertical space
// label labelElement.setAttribute( 'for', data.id || id);
label.appendChild(labelElement);
}
subnode = node.appendChild(document.createElement('textarea'));
Line 637 ⟶ 662:
if (data.disabled) {
subnode.setAttribute('disabled', 'disabled');
}
if (data.required) {
subnode.setAttribute('required', 'required');
}
if (data.readonly) {
Line 644 ⟶ 672:
subnode.value = data.value;
}
childContainder = subnode;
break;
default:
Line 670 ⟶ 699:
 
return [ node, childContainder ];
};
 
Morebits.quickForm.element.autoNWSW = function() {
return $(this).offset().top > ($(document).scrollTop() + ($(window).height() / 2)) ? 'sw' : 'nw';
};
 
/**
* Create a jquery.ui-based tooltip.
* @param {HTMLElement} node
* @requires jquery.ui
* @param {Object} data
* @param {HTMLElement} node - the HTML element beside which a tooltip is to be generated
* @param {Object} data - tooltip-related configuration data
*/
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) {
var tooltipButton = node.appendChild(document.createElement('span'));
$('<span/>', {
tooltipButton.className = 'morebits-tooltipButton';
'class': 'ui-icon ui-icon-help ui-icon-inline morebits-tooltip'
tooltipButton.title = data.tooltip; // Provides the content for jQuery UI
}).appendTo(node).tipsy({
tooltipButton.appendChild(document.createTextNode('?'));
'fallback': data.tooltip,
$(tooltipButton).tooltip({
'fade': true,
position: { my: 'left top', at: 'center bottom', collision: 'flipfit' },
'gravity': data.type === 'input' || data.type === 'select' ?
// Deprecated in UI 1.12, but MW stuck on 1.9.2 indefinitely; see #398 and T71386
Morebits.quickForm.element.autoNWSW : $.fn.tipsy.autoWE,
tooltipClass: 'morebits-ui-tooltip'
'html': true,
'delayOut': 250
});
};
Line 696 ⟶ 722:
// Some utility methods for manipulating quickForms after their creation:
// (None of these work for "dyninput" type fields at present)
 
/**
* Returns an object containing all filled form data entered by the user, with the object
* keys being the form element names. Disabled fields will be ignored, but not hidden fields.
* @param {HTMLFormElement} form
* @returns {Object} with field names as keys, input data as values
*/
Morebits.quickForm.getInputData = function(form) {
var result = {};
 
for (var i = 0; i < form.elements.length; i++) {
var field = form.elements[i];
if (field.disabled || !field.name || !field.type ||
field.type === 'submit' || field.type === 'button') {
continue;
}
 
// For elements in subgroups, quickform prepends element names with
// 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) {
case 'radio':
if (field.checked) {
result[fieldNameNorm] = field.value;
}
break;
case 'checkbox':
if (field.dataset.single) {
result[fieldNameNorm] = field.checked; // boolean
} else {
result[fieldNameNorm] = result[fieldNameNorm] || [];
if (field.checked) {
result[fieldNameNorm].push(field.value);
}
}
break;
case 'select-multiple':
result[fieldNameNorm] = $(field).val(); // field.value doesn't work
break;
case 'text': // falls through
case 'textarea':
result[fieldNameNorm] = field.value.trim();
break;
default: // could be select-one, date, number, email, etc
if (field.value) {
result[fieldNameNorm] = field.value;
}
break;
}
}
return result;
};
 
 
/**
* Returns all form elements with a given field name or ID
* @returnsparam {HTMLElement[]HTMLFormElement} form
* @param {string} fieldName - the name or id of the fields
* @returns {HTMLElement[]} - array of matching form elements
*/
Morebits.quickForm.getElements = function QuickFormGetElements(form, fieldName) {
var $form = $(form);
fieldName = $.escapeSelector(fieldName); // sanitize input
var $elements = $form.find('[name="' + fieldName + '"]');
if ($elements.length > 0) {
Line 709 ⟶ 791:
}
$elements = $form.find('#' + fieldName);
ifreturn ($elements.length > 0toArray() {;
return $elements.toArray();
}
return null;
};
 
Line 718 ⟶ 797:
* Searches the array of elements for a checkbox or radio button with a certain
* `value` attribute, and returns the first such element. Returns null if not found.
* @param {HTMLInputElement[]} elementArray - array of checkbox or radio elements
* @param {string} value - value to search for
* @returns {HTMLInputElement}
*/
Line 841 ⟶ 920:
*/
Morebits.quickForm.setElementTooltipVisibility = function QuickFormSetElementTooltipVisibility(element, visibility) {
$(Morebits.quickForm.getElementContainer(element)).find('.morebits-tooltiptooltipButton').toggle(visibility);
};
 
Line 857 ⟶ 936:
* Type is optional and can specify if either radio or checkbox (for the event
* that both checkboxes and radiobuttons have the same name.
*
* XXX: Doesn't seem to work reliably across all browsers at the moment. -- see getChecked2
* in twinkleunlink.js, which is better
*/
HTMLFormElement.prototype.getChecked = function(name, type) {
var elements = this.elements[name];
if (!elements) {
return [];
// if the element doesn't exists, return null.
return null;
}
var return_array = [];
Line 912 ⟶ 987:
var elements = this.elements[name];
if (!elements) {
return [];
// if the element doesn't exists, return null.
return null;
}
var return_array = [];
Line 954 ⟶ 1,028:
 
/**
* @deprecated as of September 2020, use Morebits.string.escapeRegExp or
* **************** RegExp ****************
* mw.util.escapeRegExp
*
* Escapes a string to be used in a RegExp
* @param {string} text - string to be escaped
* @param {boolean} [space_fix] - Set this true to replace spaces and underscore with `[ _]` as they are often equivalent
*/
 
RegExp.escape = function(text, space_fix) {
text = mw.util.escapeRegExp(text);
 
// Special MediaWiki escape - underscore/space are often equivalent
if (space_fix) {
console.log('NOTE: RegExp.escape from Morebits was deprecated September 2020, please replace it with Morebits.string.escapeRegExp'); // eslint-disable-line no-console
text = text.replace(/ |_/g, '[_ ]');
return Morebits.string.escapeRegExp(text);
}
console.log('NOTE: RegExp.escape from Morebits was deprecated September 2020, please replace it with mw.util.escapeRegExp'); // eslint-disable-line no-console
 
return mw.util.escapeRegExp(text);
};
 
Line 1,054 ⟶ 1,122:
 
/**
* Formats a "reason" (from a textarea) for inclusion in a userspace log
* Replacement for `String.prototype.replace()` when the second parameter
* @param {string} str
* (the replacement string) is arbitrary, such as a username or freeform user input,
* @returns {string}
* and may contain dollar signs
*/
formatReasonForLog: function(str) {
return str
// handle line breaks, which otherwise break numbering
.replace(/\n+/g, '{{pb}}')
// put an extra # in front before bulleted or numbered list items
.replace(/^(#+)/mg, '#$1')
.replace(/^(\*+)/mg, '#$1');
},
 
/**
* Like `String.prototype.replace()`, but escapes any dollar signs in the replacement string.
* Useful when the the replacement string is arbitrary, such as a username or freeform user input,
* and could contain dollar signs.
* @param {string} string - text in which to replace
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @returns {string}
*/
safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) {
return string.replace(pattern, replacement.replace(/\$/g, '$$$$'));
},
 
/**
* Determine if user input expiration will be translated to an
* infinite-length by MW: https://phabricator.wikimedia.org/T68646
* @param {string} expiry
* @returns {boolean}
*/
isInfinity: function morebitsStringIsInfinity(expiry) {
return ['indefinite', 'infinity', 'infinite', 'never'].indexOf(expiry) !== -1;
},
 
/**
* Escapes a string to be used in a RegExp, replacing spaces and
* underscores with `[ _]` as they are often equivalent
* Replaced RegExp.escape September 2020
* @param {string} text - string to be escaped
* @returns {string} - the escaped text
*/
escapeRegExp: function(text) {
return mw.util.escapeRegExp(text).replace(/ |_/g, '[_ ]');
}
};
Line 1,076 ⟶ 1,183:
throw 'A non-array object passed to Morebits.array.uniq';
}
return arr.filter(function(item, idx) {
var result = [];
return arr.indexOf(item) === idx;
for (var i = 0; i < arr.length; ++i) {
});
var current = arr[i];
if (result.indexOf(current) === -1) {
result.push(current);
}
}
return result;
},
 
Line 1,094 ⟶ 1,196:
throw 'A non-array object passed to Morebits.array.dups';
}
return arr.filter(function(item, idx) {
var uniques = [];
return arr.indexOf(item) !== idx;
var result = [];
});
for (var i = 0; i < arr.length; ++i) {
var current = arr[i];
if (uniques.indexOf(current) === -1) {
uniques.push(current);
} else {
result.push(current);
}
}
return result;
},
 
 
/**
* breaksBreak up `arr`an array into smaller arrays of length `size`, and.
* @param {Array} arr
* @returns an array of these "chunked" arrays
* @param {number} size - Size of each chunk (except the last, which could be different)
* @param {array} arr
* @returns {Array} an array of these smaller arrays
* @param {number} size
* @returns {Array}
*/
chunk: function(arr, size) {
Line 1,122 ⟶ 1,215:
return [ arr ]; // we return an array consisting of this array.
}
var resultnumChunks = []Math.ceil(arr.length / size);
var result = new Array(numChunks);
var current;
for (var i = 0; i < arr.lengthnumChunks; i++i) {
result[i] = arr.slice(i * size, (i + 1) * size);
if (i % size === 0) { // when 'i' is 0, this is always true, so we start by creating one.
current = [];
result.push(current);
}
current.push(arr[i]);
}
return result;
}
};
 
/**
* ************ Morebits.select2 ***************
* Utilities to enhance select2 menus
* See twinklewarn, twinklexfd, twinkleblock for sample usages
*/
Morebits.select2 = {
 
matchers: {
/**
* Custom matcher in which if the optgroup name matches, all options in that
* group are shown, like in jquery.chosen
*/
optgroupFull: function(params, data) {
var originalMatcher = $.fn.select2.defaults.defaults.matcher;
var result = originalMatcher(params, data);
 
if (result && params.term &&
data.text.toUpperCase().indexOf(params.term.toUpperCase()) !== -1) {
result.children = data.children;
}
return result;
},
 
/** Custom matcher that matches from the beginning of words only */
wordBeginning: function(params, data) {
var originalMatcher = $.fn.select2.defaults.defaults.matcher;
var result = originalMatcher(params, data);
if (!params.term || (result &&
new RegExp('\\b' + mw.util.escapeRegExp(params.term), 'i').test(result.text))) {
return result;
}
return null;
}
},
 
/** Underline matched part of options */
highlightSearchMatches: function(data) {
var searchTerm = Morebits.select2SearchQuery;
if (!searchTerm || data.loading) {
return data.text;
}
var idx = data.text.toUpperCase().indexOf(searchTerm.toUpperCase());
if (idx < 0) {
return data.text;
}
 
return $('<span>').append(
data.text.slice(0, idx),
$('<span>').css('text-decoration', 'underline').text(data.text.slice(idx, idx + searchTerm.length)),
data.text.slice(idx + searchTerm.length)
);
},
 
/** Intercept query as it is happening, for use in highlightSearchMatches */
queryInterceptor: function(params) {
Morebits.select2SearchQuery = params && params.term;
},
 
/**
* Open dropdown and begin search when the .select2-selection has focus and a key is pressed
* https://github.com/select2/select2/issues/3279#issuecomment-442524147
*/
autoStart: function(ev) {
if (ev.which < 48) {
return;
}
var target = $(ev.target).closest('.select2-container');
if (!target.length) {
return;
}
target = target.prev();
target.select2('open');
var search = target.data('select2').dropdown.$search ||
target.data('select2').selection.$search;
search.focus();
}
 
};
 
Line 1,148 ⟶ 1,316:
* For a page name 'Foo bar', returns the string '[Ff]oo bar'
* @param {string} pageName - page name without namespace
* @returns {string}
*/
Morebits.pageNameRegex = function(pageName) {
Line 1,194 ⟶ 1,363:
},
 
/** @returns {string} The output */
/**
* @returns {string} The output
*/
rebind: function UnbinderRebind() {
var content = this.content;
Line 1,226 ⟶ 1,393:
 
/**
* **************** DateMorebits.date ****************
* Helper functions to get the month as a string instead of a number
*
* Normally it is poor form to play with prototypes of primitive types, but it
* is fairly unlikely that anyone will iterate over a Date object.
*/
 
/**
Date.prototype.getUTCMonthName = function() {
* @constructor
return mw.config.get('wgMonthNames')[this.getUTCMonth() + 1];
* Create a date object. MediaWiki timestamp format is also acceptable,
* in addition to everything that JS Date() accepts.
*/
Morebits.date = function() {
var args = Array.prototype.slice.call(arguments);
 
// Date.parse implementations vary too much between browsers, and
// MediaWiki's format is too non-standard, so we just convert MW
// timestamps to ISO-8601. A paren-wrapped 'UTC' messes everyone up,
// and the comma after the time is only okay in modern Firefox. After
// this first replace, Chrome and Firefox are content. The second
// replace is mainly for Safari, which basically *only* accepts the
// simplified ECMA-262 implementation of ISO-8601.
if (typeof args[0] === 'string') {
args[0] = args[0].replace(/(\d\d:\d\d),/, '$1').replace(/\(UTC\)/, 'UTC');
// Safari is particular about timezone offsets, so this is intentionally specific
args[0] = args[0].replace(/(\d\d:\d\d) (\d{1,2}) ([A-Z][a-z]+) (\d{4}) UTC$/, function(match, time, date, monthname, year) {
// zero-pad date
if (date.length === 1) {
date = '0' + date;
}
return [year, mw.config.get('wgMonthNames').indexOf(monthname), date].join('-') + 'T' + time + 'Z';
});
}
this._d = new (Function.prototype.bind.apply(Date, [Date].concat(args)));
};
 
Morebits.date.localeData = {
Date.prototype.getUTCMonthNameAbbrev = function() {
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
return mw.config.get('wgMonthNamesShort')[this.getUTCMonth() + 1];
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
relativeTimes: {
thisDay: '[Today at] h:mm A',
prevDay: '[Yesterday at] h:mm A',
nextDay: '[Tomorrow at] h:mm A',
thisWeek: 'dddd [at] h:mm A',
pastWeek: '[Last] dddd [at] h:mm A',
other: 'YYYY-MM-DD'
}
};
 
// Allow native Date.prototype methods to be used on Morebits.date objects
// Morebits.wikipedia.namespaces is deprecated - use mw.config.get('wgFormattedNamespaces') or mw.config.get('wgNamespaceIds') instead
Object.getOwnPropertyNames(Date.prototype).forEach(function(func) {
Morebits.date.prototype[func] = function() {
return this._d[func].apply(this._d, Array.prototype.slice.call(arguments));
};
});
 
$.extend(Morebits.date.prototype, {
 
isValid: function() {
return !isNaN(this.getTime());
},
 
/** @param {(Date|Morebits.date)} date */
isBefore: function(date) {
return this.getTime() < date.getTime();
},
isAfter: function(date) {
return this.getTime() > date.getTime();
},
 
/** @return {string} */
getUTCMonthName: function() {
return Morebits.date.localeData.months[this.getUTCMonth()];
},
getUTCMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getUTCMonth()];
},
getMonthName: function() {
return Morebits.date.localeData.months[this.getMonth()];
},
getMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getMonth()];
},
getUTCDayName: function() {
return Morebits.date.localeData.days[this.getUTCDay()];
},
getUTCDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getUTCDay()];
},
getDayName: function() {
return Morebits.date.localeData.days[this.getDay()];
},
getDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getDay()];
},
 
/**
* Add a given number of minutes, hours, days, months or years to the date.
* This is done in-place. The modified date object is also returned, allowing chaining.
* @param {number} number - should be an integer
* @param {string} unit
* @throws {Error} if invalid or unsupported unit is given
* @returns {Morebits.date}
*/
add: function(number, unit) {
// mapping time units with getter/setter function names
var unitMap = {
seconds: 'Seconds',
minutes: 'Minutes',
hours: 'Hours',
days: 'Date',
months: 'Month',
years: 'FullYear'
};
var unitNorm = unitMap[unit] || unitMap[unit + 's']; // so that both singular and plural forms work
if (unitNorm) {
this['set' + unitNorm](this['get' + unitNorm]() + number);
return this;
}
throw new Error('Invalid unit "' + unit + '": Only ' + Object.keys(unitMap).join(', ') + ' are allowed.');
},
 
/**
* Subtracts a given number of minutes, hours, days, months or years to the date.
* This is done in-place. The modified date object is also returned, allowing chaining.
* @param {number} number - should be an integer
* @param {string} unit
* @throws {Error} if invalid or unsupported unit is given
* @returns {Morebits.date}
*/
subtract: function(number, unit) {
return this.add(-number, unit);
},
 
/**
* Formats the date into a string per the given format string.
* Replacement syntax is a subset of that in moment.js.
* @param {string} formatstr
* @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.
* @returns {string}
*/
format: function(formatstr, zone) {
var udate = this;
// create a new date object that will contain the date to display as system time
if (zone === 'utc') {
udate = new Morebits.date(this.getTime()).add(this.getTimezoneOffset(), 'minutes');
} else if (typeof zone === 'number') {
// convert to utc, then add the utc offset given
udate = new Morebits.date(this.getTime()).add(this.getTimezoneOffset() + zone, 'minutes');
}
 
var pad = function(num) {
return num < 10 ? '0' + num : num;
};
var h24 = udate.getHours(), m = udate.getMinutes(), s = udate.getSeconds();
var D = udate.getDate(), M = udate.getMonth() + 1, Y = udate.getFullYear();
var h12 = h24 % 12 || 12, amOrPm = h24 >= 12 ? 'PM' : 'AM';
var replacementMap = {
'HH': pad(h24), 'H': h24, 'hh': pad(h12), 'h': h12, 'A': amOrPm,
'mm': pad(m), 'm': m,
'ss': pad(s), 's': s,
'dddd': udate.getDayName(), 'ddd': udate.getDayNameAbbrev(), 'd': udate.getDay(),
'DD': pad(D), 'D': D,
'MMMM': udate.getMonthName(), 'MMM': udate.getMonthNameAbbrev(), 'MM': pad(M), 'M': M,
'YYYY': Y, 'YY': pad(Y % 100), 'Y': Y
};
 
var unbinder = new Morebits.unbinder(formatstr); // escape stuff between [...]
unbinder.unbind('\\[', '\\]');
unbinder.content = unbinder.content.replace(
/* 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}|d(d{2,3})?|D{1,2}|M{1,4}|Y{1,2}(Y{2})?|A/g,
function(match) {
return replacementMap[match];
}
);
return unbinder.rebind().replace(/\[(.*?)\]/g, '$1');
},
 
/**
* Gives a readable relative time string such as "Yesterday at 6:43 PM" or "Last Thursday at 11:45 AM".
* Similar to calendar in moment.js, but with time zone support.
* @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
* @returns {string}
*/
calendar: function(zone) {
// Zero out the hours, minutes, seconds and milliseconds - keeping only the date;
// find the difference. Note that setHours() returns the same thing as getTime().
var dateDiff = (new Date().setHours(0, 0, 0, 0) -
new Date(this).setHours(0, 0, 0, 0)) / 8.64e7;
switch (true) {
case dateDiff === 0:
return this.format(Morebits.date.localeData.relativeTimes.thisDay, zone);
case dateDiff === 1:
return this.format(Morebits.date.localeData.relativeTimes.prevDay, zone);
case dateDiff > 0 && dateDiff < 7:
return this.format(Morebits.date.localeData.relativeTimes.pastWeek, zone);
case dateDiff === -1:
return this.format(Morebits.date.localeData.relativeTimes.nextDay, zone);
case dateDiff < 0 && dateDiff > -7:
return this.format(Morebits.date.localeData.relativeTimes.thisWeek, zone);
default:
return this.format(Morebits.date.localeData.relativeTimes.other, zone);
}
},
 
/**
* @returns {RegExp} that matches wikitext section titles such as ==December 2019== or
* === Jan 2018 ===
*/
monthHeaderRegex: function() {
return new RegExp('^==+\\s*(?:' + this.getUTCMonthName() + '|' + this.getUTCMonthNameAbbrev() +
')\\s+' + this.getUTCFullYear() + '\\s*==+', 'mg');
},
 
/**
* Creates a section header with the month and year.
* @param {number} [level=2] - Header level (default 2). Pass 0 for
* just the text with no wikitext markers (==)
* @returns {string}
*/
monthHeader: function(level) {
// Default to 2, but allow for 0 or stringy numbers
level = parseInt(level, 10);
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
return header + ' ' + text + ' ' + header;
}
return text; // Just the string
 
}
 
});
 
 
/**
Line 1,252 ⟶ 1,644:
* Determines whether the current page is a redirect or soft redirect
* (fails to detect soft redirects on edit, history, etc. pages)
* @returns {boolean}
*/
Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() {
Line 1,299 ⟶ 1,692:
// Change per action wanted
Morebits.wiki.actionCompleted.event = function() {
newif Morebits.status(Morebits.wiki.actionCompleted.notice,) Morebits.wiki.actionCompleted.postfix, 'info');{
Morebits.status.actionCompleted(Morebits.wiki.actionCompleted.notice);
}
if (Morebits.wiki.actionCompleted.redirect) {
// if it isn't a URL, make it one. TODO: This breaks on the articles 'http://', 'ftp://', and similar ones.
Line 1,316 ⟶ 1,711:
Morebits.wiki.actionCompleted.timeOut = typeof window.wpActionCompletedTimeOut === 'undefined' ? 5000 : window.wpActionCompletedTimeOut;
Morebits.wiki.actionCompleted.redirect = null;
Morebits.wiki.actionCompleted.notice = 'Action'null;
Morebits.wiki.actionCompleted.postfix = 'completed';
 
Morebits.wiki.addCheckpoint = function() {
Line 1,335 ⟶ 1,729:
 
/**
* In new code, the use of the last 3 parameters should be avoided, instead use setStatusElement() to bind the
* status element (if needed) and use .then() or .catch() on the promise returned by post(), rather than specify
* the onSuccess or onFailure callbacks.
* @constructor
* @param {string} currentAction - The current action (required)
* @param {Object} query - The query (required)
* @param {Function} [onSuccess] - The function to call when request gotten
* @param {ObjectMorebits.status} [statusElement] - A Morebits.status object to use for status messages (optional)
* @param {Function} [onError] - The function to call if an error occurs (optional)
*/
Line 1,345 ⟶ 1,742:
this.currentAction = currentAction;
this.query = query;
this.query.format = 'xml';
this.query.assert = 'user';
this.onSuccess = onSuccess;
this.onError = onError;
if (statusElement) {
this.statelem = setStatusElement(statusElement);
this.statelem.status(currentAction);
} else {
this.statelem = new Morebits.status(currentAction);
}
if (!query.format) {
this.query.format = 'xml';
} else if (query.format === 'json' && !query.formatversion) {
this.query.formatversion = '2';
} else if (['xml', 'json'].indexOf(query.format) === -1) {
this.statelem.error('Invalid API format: only xml and json are supported.');
}
 
// Ignore tags for queries and most common unsupported actions, produces warnings
if (query.action && ['query', 'review', 'stabilize', 'pagetriageaction', 'watch'].indexOf(query.action) !== -1) {
delete query.tags;
} else if (!query.tags && morebitsWikiChangeTag) {
query.tags = morebitsWikiChangeTag;
}
};
Line 1,363 ⟶ 1,772:
parent: window, // use global context if there is no parent object
query: null,
responseXMLresponse: null,
responseXML: null, // use `response` instead; retained for backwards compatibility
setParent: function(parent) {
this.parent = parent;
}, // keep track of parent object for callbacks
statelem: null, // this non-standard name kept for backwards compatibility
statusText: null, // result received from the API, normally "success" or "error"
errorCode: null, // short text error code, if any, as documented in the MediaWiki API
errorText: null, // full error description, if any
badtokenRetry: false, // set to true if this on a retry attempted after a badtoken error
 
/**
* Keep track of parent object for callbacks
* @param {*} parent
*/
setParent: function(parent) {
this.parent = parent;
},
 
/** @param {Morebits.status} statusElement */
setStatusElement: function(statusElement) {
this.statelem = statusElement;
this.statelem.status(this.currentAction);
},
 
/**
Line 1,376 ⟶ 1,798:
* @param {Object} callerAjaxParameters Do not specify a parameter unless you really
* 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) {
 
++Morebits.wiki.numberOfActionsLeft;
 
var queryString = $.map(this.query, function(val, i) {
if (Array.isArray(val)) {
return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|');
} else if (val !== undefined) {
return encodeURIComponent(i) + '=' + encodeURIComponent(val);
}
}).join('&').replace(/^(.*?)(\btoken=[^&]*)&(.*)/, '$1$3&$2');
// token should always be the last item in the query string (bug TW-B-0013)
 
var ajaxparams = $.extend({}, {
context: this,
type: this.query.action === 'query' ? 'GET' : 'POST',
url: mw.util.wikiScript('api'),
data: Morebits.queryString.create(this.query),
dataType: 'xml'this.query.format,
headers: {
'Api-User-Agent': morebitsWikiApiUserAgent
Line 1,392 ⟶ 1,824:
}, callerAjaxParameters);
 
return $.ajax(ajaxparams).donethen(
 
function(xml, statusText) {
function onAPIsuccess(response, statusText) {
this.statusText = statusText;
this.response = this.responseXML = xmlresponse;
if (this.errorCodequery.format === $(xml).find('errorjson').attr('code'); {
this.errorTexterrorCode = $(xml)response.error && response.find('error').attr('info')code;
this.errorText = response.error && response.error.info;
} else {
this.errorCode = $(response).find('error').attr('code');
this.errorText = $(response).find('error').attr('info');
}
 
if (typeof this.errorCode === 'string') {
 
// the API didn't like what we told it, e.g., bad edit token or an error creating a page
return this.returnError(callerAjaxParameters);
return;
}
 
// invoke success callback if one was supplied
if (this.onSuccess) {
 
// set the callback context to this.parent for new code and supply the API object
// as the first argument to the callback (for legacy code)
Line 1,417 ⟶ 1,852:
 
Morebits.wiki.actionCompleted();
 
}
return $.Deferred().resolveWith(this.parent, [this]);
).fail(
},
// only network and server errors reach here – complaints from the API itself are caught in success()
 
function(jqXHR, statusText, errorThrown) {
// only network and server errors reach here - complaints from the API itself are caught in success()
function onAPIfailure(jqXHR, statusText, errorThrown) {
this.statusText = statusText;
this.errorThrown = errorThrown; // frequently undefined
this.errorText = statusText + ' "' + jqXHR.statusText + '" occurred while contacting the API.';
return this.returnError();
}
 
); // the return value should be ignored, unless using callerAjaxParameters with |async: false|
);
},
 
returnError: function(callerAjaxParameters) {
if (this.errorCode === 'badtoken' && !this.badtokenRetry) {
this.statelem.errorwarn('Invalid token. RefreshGetting thea pagenew token and try againretrying...');
this.badtokenRetry = true;
} else {
// Get a new CSRF token and retry. If the original action needs a different
this.statelem.error(this.errorText);
// type of action than CSRF, we do one pointless retry before bailing out
return Morebits.wiki.api.getToken().then(function(token) {
this.query.token = token;
return this.post(callerAjaxParameters);
}.bind(this));
}
 
this.statelem.error(this.errorText + ' (' + this.errorCode + ')');
 
// invoke failure callback if one was supplied
Line 1,444 ⟶ 1,889:
}
// don't complete the action so that the error remains displayed
 
return $.Deferred().rejectWith(this.parent, [this]);
},
 
Line 1,458 ⟶ 1,905:
},
 
getXML: function() { // retained for backwards compatibility, use getResponse() instead
return this.responseXML;
},
 
getResponse: function() {
return this.response;
}
 
};
 
// Custom user agent header, used by WMF for server-side logging
// See https://lists.wikimedia.org/pipermail/mediawiki-api-announce/2014-November/000075.html
var morebitsWikiApiUserAgent = 'morebits.js/2.0 ([[w:WT:TW]])';
 
/**
Line 1,472 ⟶ 1,924:
*/
Morebits.wiki.api.setApiUserAgent = function(ua) {
morebitsWikiApiUserAgent = (ua ? ua + ' ' : '') + 'morebits.js/2.0 ([[w:WT:TW]])';
};
 
// Default change/revision tag applied to Morebits actions when no other tags are specified
// Off by default per [[Special:Permalink/970618849#Adding tags to Twinkle edits and actions]]
var morebitsWikiChangeTag = '';
 
 
/** Get a new CSRF token on encountering token errors */
Morebits.wiki.api.getToken = function() {
var tokenApi = new Morebits.wiki.api('Getting token', {
action: 'query',
meta: 'tokens',
type: 'csrf'
});
return tokenApi.post().then(function(apiobj) {
return $(apiobj.responseXML).find('tokens').attr('csrftoken');
});
};
 
 
Line 1,518 ⟶ 1,986:
* prepend([onSuccess], [onFailure]): Adds the text provided via setPrependText() to the start
* of the page. Does not require calling load() first.
*
* newSection([onSuccess], [onFailure]): Creates a new section with the text provided via setNewSectionText()
* and section title via setNewSetionTitle(). Does not require calling load() first.
*
* move([onSuccess], [onFailure]): Moves a page to another title
*
* patrol(): Patrols a page; ignores errors
*
* triage(): Marks page as reviewed using PageTriage, which implies patrolled; ignores most errors
*
* deletePage([onSuccess], [onFailure]): Deletes a page (for admins only)
Line 1,534 ⟶ 2,009:
*
* setPrependText(prependText) sets the text that will be prepended to the page when prepend() is called
*
* setNewSectionText(newSectionText) sets the text that will be added in a new section when newSection() is called
*
* setNewSectionTitle(newSectionTitle) sets the title for the new section when newSection() is called
*
* setCallbackParameters(callbackParameters)
Line 1,580 ⟶ 2,059:
* ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()
*
* Append to a page (similar for prepend and newSection):
* .append() -> ctx.loadApi.post() -> ctx.loadApi.post.success() ->
* ctx.fnLoadSuccess() -> ctx.fnAutoSave() -> .save() ->
Line 1,588 ⟶ 2,067:
* 1. All functions following Morebits.wiki.api.post() are invoked asynchronously
* from the jQuery AJAX library.
* 2. The sequence for append/prepend/newSection could be slightly shortened, but it would require
* significant duplication of code for little benefit.
*/
Line 1,615 ⟶ 2,094:
pageExists: false,
editSummary: null,
changeTags: null,
callbackParameters: null,
statusElement: new Morebits.status(currentAction),
Line 1,623 ⟶ 2,103:
appendText: null, // can't reuse pageText for this because pageText is needed to follow a redirect
prependText: null, // can't reuse pageText for this because pageText is needed to follow a redirect
newSectionText: null,
newSectionTitle: null,
createOption: null,
minorEdit: false,
Line 1,630 ⟶ 2,112:
maxRetries: 2,
followRedirect: false,
followCrossNsRedirect: true,
watchlistOption: 'nochange',
creator: null,
Line 1,648 ⟶ 2,131:
protectCreate: null,
protectCascade: false,
 
// - creation lookup
lookupNonRedirectCreator: false,
 
// - stabilize (FlaggedRevs)
Line 1,654 ⟶ 2,140:
// internal status
pageLoaded: false,
editTokencsrfToken: null,
loadTime: null,
lastEditTime: null,
pageID: null,
revertCurID: null,
revertUser: null,
Line 1,688 ⟶ 2,175:
moveApi: null,
moveProcessApi: null,
patrolApi: null,
patrolProcessApi: null,
triageApi: null,
triageProcessApi: null,
deleteApi: null,
deleteProcessApi: null,
Line 1,719 ⟶ 2,210:
action: 'query',
prop: 'info|revisions',
curtimestamp: '',
intoken: 'edit', // fetch an edit token
meta: 'tokens',
type: 'csrf',
titles: ctx.pageName
// don't need rvlimit=1 because we don't need rvstartid here and only one actual rev is returned by default
Line 1,738 ⟶ 2,231:
ctx.loadQuery.rvsection = ctx.pageSection;
}
if (Morebits.userIsInGroup('sysop')userIsSysop) {
ctx.loadQuery.inprop = 'protection';
}
Line 1,764 ⟶ 2,257:
ctx.onSaveFailure = onFailure || emptyFunction;
 
// are we getting our editediting token from mw.user.tokens?
var canUseMwUserToken = fnCanUseMwUserToken('edit');
 
Line 1,773 ⟶ 2,266:
}
if (!ctx.editSummary) {
// new section mode allows (nay, encourages) using the
ctx.statusElement.error('Internal error: edit summary not set before save!');
// title as the edit summary, but the query needs
ctx.onSaveFailure(this);
// editSummary to be undefined or '', not null
return;
if (ctx.editMode === 'new' && ctx.newSectionTitle) {
ctx.editSummary = '';
} else {
ctx.statusElement.error('Internal error: edit summary not set before save!');
ctx.onSaveFailure(this);
return;
}
}
 
Line 1,781 ⟶ 2,281:
if (ctx.fullyProtected && !ctx.suppressProtectWarning &&
!confirm('You are about to make an edit to the fully protected page "' + ctx.pageName +
(ctx.fullyProtected === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + new Morebits.date(ctx.fullyProtected).calendar('utc') + ' (UTC))') +
'. \n\nClick OK to proceed with the edit, or Cancel to skip this edit.')) {
ctx.statusElement.error('Edit to fully protected page was aborted.');
Line 1,794 ⟶ 2,294:
title: ctx.pageName,
summary: ctx.editSummary,
token: canUseMwUserToken ? mw.user.tokens.get('csrfToken') : ctx.editTokencsrfToken,
watchlist: ctx.watchlistOption
};
 
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
if (typeof ctx.pageSection === 'number') {
Line 1,816 ⟶ 2,320:
switch (ctx.editMode) {
case 'append':
if (ctx.appendText === null) {
ctx.statusElement.error('Internal error: append text not set before save!');
ctx.onSaveFailure(this);
return;
}
query.appendtext = ctx.appendText; // use mode to append to current page contents
break;
case 'prepend':
if (ctx.prependText === null) {
ctx.statusElement.error('Internal error: prepend text not set before save!');
ctx.onSaveFailure(this);
return;
}
query.prependtext = ctx.prependText; // use mode to prepend to current page contents
break;
case 'new':
if (!ctx.newSectionText) { // API doesn't allow empty new section text
ctx.statusElement.error('Internal error: new section text not set before save!');
ctx.onSaveFailure(this);
return;
}
query.section = 'new';
query.text = ctx.newSectionText; // add a new section to current page
query.sectiontitle = ctx.newSectionTitle || ctx.editSummary; // done by the API, but non-'' values would get treated as text
break;
case 'revert':
Line 1,829 ⟶ 2,353:
query.starttimestamp = ctx.loadTime; // check that page hasn't been deleted since it was loaded (don't recreate bad stuff)
break;
default: // 'all'
query.text = ctx.pageText; // replace entire contents of the page
if (ctx.lastEditTime) {
Line 1,888 ⟶ 2,412:
 
/**
* Creates a new section with the text provided by setNewSectionText()
* @returns {string} string containing the name of the loaded page, including the namespace
* and section title from setNewSectionTitle()
* If editSummary is provided, that will be used instead of the
* autogenerated "->Title (new section" edit summary
* Does not require calling load() first
* @param {Function} [onSuccess] - callback function which is called when the method has succeeded (optional)
* @param {Function} [onFailure] - callback function which is called when the method fails (optional)
*/
this.newSection = function(onSuccess, onFailure) {
ctx.editMode = 'new';
 
if (fnCanUseMwUserToken('edit')) {
this.save(onSuccess, onFailure);
} else {
ctx.onSaveSuccess = onSuccess;
ctx.onSaveFailure = onFailure || emptyFunction;
this.load(fnAutoSave, ctx.onSaveFailure);
}
};
 
/** @returns {string} string containing the name of the loaded page, including the namespace */
this.getPageName = function() {
return ctx.pageName;
};
 
/** @returns {string} string containing the text of the page after a successful load() */
/**
* @returns {string} string containing the text of the page after a successful load()
*/
this.getPageText = function() {
return ctx.pageText;
};
 
/** @param {string} pageText - updated page text that will be saved when save() is called */
/**
* `pageText` - string containing the updated page text that will be saved when save() is called
*/
this.setPageText = function(pageText) {
ctx.editMode = 'all';
Line 1,909 ⟶ 2,448:
};
 
/** @param {string} appendText - text that will be appended to the page when append() is called */
/**
* `appendText` - string containing the text that will be appended to the page when append() is called
*/
this.setAppendText = function(appendText) {
ctx.editMode = 'append';
Line 1,917 ⟶ 2,454:
};
 
/** @param {string} prependText - text that will be prepended to the page when prepend() is called */
/**
* `prependText` - string containing the text that will be prepended to the page when prepend() is called
*/
this.setPrependText = function(prependText) {
ctx.editMode = 'prepend';
ctx.prependText = prependText;
};
 
/** @param {string} newSectionText - text that will be added in a new section on the page when newSection() is called */
this.setNewSectionText = function(newSectionText) {
ctx.editMode = 'new';
ctx.newSectionText = newSectionText;
};
 
/**
* @param {string} newSectionTitle - title for the new section created when newSection() is called
* If missing, ctx.editSummary will be used. Issues may occur if a substituted template is used
*/
this.setNewSectionTitle = function(newSectionTitle) {
ctx.editMode = 'new';
ctx.newSectionTitle = newSectionTitle;
};
 
Line 1,929 ⟶ 2,479:
// Edit-related setter methods:
/**
* `summary` -@param {string} containingsummary the- text of the edit summary that will be used when save() is called
* Unnecessary if editMode is 'new' and newSectionTitle is provided
*/
this.setEditSummary = function(summary) {
Line 1,936 ⟶ 2,487:
 
/**
* Set any custom tag(s) to be applied to the API action
* `createOption` is a string value:
* A number of actions don't support it, most notably watch, review
* 'recreate' - create the page if it does not exist, or edit it if it exists
* and stabilize (T247721), and pagetriageaction (T252980)
* 'createonly' - create the page if it does not exist, but return an error if it
* already exists
* 'nocreate' - don't create the page, only edit it if it already exists
* null - create the page if it does not exist, unless it was deleted in the moment
* between retrieving the edit token and saving the edit (default)
*
* @param {string|string[]} tags - String or array of tag(s)
*/
this.setCreateOptionsetChangeTags = function(createOptiontags) {
ctx.createOptionchangeTags = createOptiontags;
};
 
 
/**
* @param {string} createOption - can take the following four values:
* `minorEdit` - boolean value:
* True - When save`recreate` is called, - create the resultingpage editif willit does not exist, or edit beit markedif asit "minor"exists.
* False - When save is`createonly` called,- create the resultingpage editif willit does not beexist, but return markedan aserror "minor".if (default)it
* already exists.
* `nocreate` - don't create the page, only edit it if it already exists.
* null - create the page if it does not exist, unless it was deleted in the moment
* between loading the page and saving the edit (default)
*
*/
this.setCreateOption = function(createOption) {
ctx.createOption = createOption;
};
 
/** @param {boolean} minorEdit - set true to mark the edit as a minor edit. */
this.setMinorEdit = function(minorEdit) {
ctx.minorEdit = minorEdit;
};
 
/** @param {boolean} botEdit - set true to mark the edit as a bot edit */
/**
* `botEdit` is a boolean value:
* True - When save is called, the resulting edit will be marked as "bot".
* False - When save is called, the resulting edit will not be marked as "bot". (default)
*/
this.setBotEdit = function(botEdit) {
ctx.botEdit = botEdit;
Line 1,968 ⟶ 2,523:
 
/**
* `@param {number} pageSection` - integer specifying the section number to load or save.
* TheIf defaultspecified isas `null`, which means that the entire page will be retrieved.
*/
this.setPageSection = function(pageSection) {
Line 1,976 ⟶ 2,531:
 
/**
* `maxRetries`@param {number} maxConflictRetries - number of retries for save errors involving an edit conflict or loss of edit token.Default: 2
* loss of token. Default: 2
*/
this.setMaxConflictRetries = function(maxRetriesmaxConflictRetries) {
ctx.maxConflictRetries = maxRetriesmaxConflictRetries;
};
 
/**
* `@param {number} maxRetries` - number of retries for save errors not involving an edit conflict or loss of edit token
* loss of token. Default: 2
*/
this.setMaxRetries = function(maxRetries) {
Line 1,991 ⟶ 2,547:
 
/**
* @param `watchlistOption` is a {boolean} value:watchlistOption
* True - page will be added to the user's watchlist when save() is called
* False - watchlist status of the page will not be changed (default)
*/
this.setWatchlist = function(watchlistOption) {
Line 2,004 ⟶ 2,560:
 
/**
* @param {boolean} `watchlistOption` is a boolean value:
* True - page watchlist status will be set based on the user's
* preference settings when save() is called.
* False - watchlist status of the page will not be changed (default)
*
* Watchlist notes:
Line 2,028 ⟶ 2,584:
 
/**
* @param {boolean} `followRedirect` is a boolean value:
* Truetrue - a maximum of one redirect will be followed.
* In the event of a redirect, a message is displayed to the user and
* the redirect target can be retrieved with getPageName().
* false - False -(default) the requested pageName will be used without regard to any redirect. (default)
* redirect.
* @param {boolean} followCrossNsRedirect
* Not applicable if followRedirect is not set true.
* true - (default) follow redirect even if it is a cross-namespace redirect
* false - don't follow redirect if it is cross-namespace, edit the redirect itself
*/
this.setFollowRedirect = function(followRedirect, followCrossNsRedirect) {
if (ctx.pageLoaded) {
ctx.statusElement.error('Internal error: cannot change redirect setting after the page has been loaded!');
Line 2,040 ⟶ 2,601:
}
ctx.followRedirect = followRedirect;
ctx.followCrossNsRedirect = typeof followCrossNsRedirect !== 'undefined' ? followCrossNsRedirect : ctx.followCrossNsRedirect;
};
 
// lookup-creation setter function
/**
* @param {boolean} flag - if set true, the author and timestamp of the first non-redirect
* version of the page is retrieved.
*
* Warning:
* 1. If there are no revisions among the first 50 that are non-redirects, or if there are
* less 50 revisions and all are redirects, the original creation is retrived.
* 2. Revisions that the user is not privileged to access (revdeled/suppressed) will be treated
* as non-redirects.
* 3. Must not be used when the page has a non-wikitext contentmodel
* such as Modulespace Lua or user JavaScript/CSS
*/
this.setLookupNonRedirectCreator = function(flag) {
ctx.lookupNonRedirectCreator = flag;
};
 
// Move-related setter functions
/** @param {string} destination */
this.setMoveDestination = function(destination) {
ctx.moveDestination = destination;
};
 
/** @param {boolean} flag */
this.setMoveTalkPage = function(flag) {
ctx.moveTalkPage = !!flag;
};
 
/** @param {boolean} flag */
this.setMoveSubpages = function(flag) {
ctx.moveSubpages = !!flag;
};
 
/** @param {boolean} flag */
this.setMoveSuppressRedirect = function(flag) {
ctx.moveSuppressRedirect = !!flag;
Line 2,060 ⟶ 2,643:
 
// Protect-related setter functions
/**
* @param {string} level The right required for the specific action
* e.g. autoconfirmed, sysop, templateeditor, extendedconfirmed (enWiki)
* @param {string} [expiry=infinity]
*/
this.setEditProtection = function(level, expiry) {
ctx.protectEdit = { level: level, expiry: expiry || 'infinity' };
};
 
this.setMoveProtection = function(level, expiry) {
ctx.protectMove = { level: level, expiry: expiry || 'infinity' };
};
 
this.setCreateProtection = function(level, expiry) {
ctx.protectCreate = { level: level, expiry: expiry || 'infinity' };
};
 
Line 2,085 ⟶ 2,673:
};
 
/** @returns {string} string containing the current revision ID of the page */
/**
* @returns {string} string containing the current revision ID of the page
*/
this.getCurrentID = function() {
return ctx.revertCurID;
};
 
/** @returns {string} last editor of the page */
this.getRevisionUser = function() {
return ctx.revertUser;
};
 
/** @returns {string} ISO 8601 timestamp at which the page was last edited. */
this.getLastEditTime = function() {
return ctx.lastEditTime;
};
 
Line 2,125 ⟶ 2,717:
};
 
/**
 
* @param {string} level The right required for edits not to require
* review. Possible options: none, autoconfirmed, review (not on enWiki).
* @param {string} [expiry=infinity]
*/
this.setFlaggedRevs = function(level, expiry) {
ctx.flaggedRevs = { level: level, expiry: expiry || 'infinity' };
};
 
Line 2,135 ⟶ 2,731:
this.exists = function() {
return ctx.pageExists;
};
 
/**
* @returns {string} Page ID of the page loaded. 0 if the page doesn't
* exist.
*/
this.getPageID = function() {
return ctx.pageID;
};
 
/**
* @returns {string} ISO 8601 timestamp at which the page was last loaded
*/
this.getLoadTime = function() {
return ctx.loadTime;
};
 
Line 2,158 ⟶ 2,769:
* The username can be retrieved using the getCreator() function;
* the timestamp can be retrieved using the getCreationTimestamp() function
* Prior to June 2019 known as lookupCreator
*/
this.lookupCreation = function(onSuccess) {
Line 2,174 ⟶ 2,786:
'rvdir': 'newer'
};
 
// Only the wikitext content model can reliably handle
// rvsection, others return an error when paired with the
// content rvprop. Relatedly, non-wikitext models don't
// understand the #REDIRECT concept, so we shouldn't attempt
// the redirect resolution in fnLookupCreationSuccess
if (ctx.lookupNonRedirectCreator) {
query.rvsection = 0;
query.rvprop += '|content';
}
 
if (ctx.followRedirect) {
Line 2,182 ⟶ 2,804:
ctx.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
};
/**
* @deprecated since May/June 2019, renamed to lookupCreation
*/
this.lookupCreator = function(onSuccess) {
console.warn("NOTE: lookupCreator() from Twinkle's Morebits has been deprecated since May/June 2019, please use lookupCreation() instead"); // eslint-disable-line no-console
Morebits.status.warn('NOTE', "lookupCreator() from Twinkle's Morebits has been deprecated since May/June 2019, please use lookupCreation() instead");
return this.lookupCreation(onSuccess);
};
 
/**
* marks the page as patrolled, if possible
*/
this.patrol = function() {
// There's no patrol link on page, so we can't patrol
if (!$('.patrollink').length) {
return;
}
 
// Extract the rcid token from the "Mark page as patrolled" link on page
var patrolhref = $('.patrollink a').attr('href'),
rcid = mw.util.getParamValue('rcid', patrolhref);
 
if (rcid) {
 
var patrolstat = new Morebits.status('Marking page as patrolled');
 
var wikipedia_api = new Morebits.wiki.api('doing...', {
action: 'patrol',
rcid: rcid,
token: mw.user.tokens.get('patrolToken')
}, null, patrolstat);
 
// We don't really care about the response
wikipedia_api.post();
}
};
 
Line 2,259 ⟶ 2,845:
}
 
if (fnCanUseMwUserToken('move')) {
var query = {
fnProcessMove.call(this, this);
action: 'query',
} else {
prop: 'info',
intoken:var query = fnNeedTokenInfoQuery('move',);
 
titles: ctx.pageName
ctx.moveApi = new Morebits.wiki.api('retrieving token...', query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
};
ctx.moveApi.setParent(this);
if (ctx.followRedirect) {
ctx.moveApi.post();
query.redirects = ''; // follow all redirects
}
};
if (Morebits.userIsInGroup('sysop')) {
 
query.inprop = 'protection';
/**
* Marks the page as patrolled, using rcid (if available) or revid
*
* Patrolling as such doesn't need to rely on loading the page in
* question; simply passing a revid to the API is sufficient, so in
* those cases just using Morebits.wiki.api is probably preferable.
*
* No error handling since we don't actually care about the errors
*/
this.patrol = function() {
if (!Morebits.userIsSysop && !Morebits.userIsInGroup('patroller')) {
return;
}
 
// If a link is present, don't need to check if it's patrolled
ctx.moveApi = new Morebits.wiki.api('retrieving move token...', query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
if ($('.patrollink').length) {
ctx.moveApi.setParent(this);
var patrolhref = $('.patrollink a').attr('href');
ctx.moveApi.post();
ctx.rcid = mw.util.getParamValue('rcid', patrolhref);
fnProcessPatrol(this, this);
} else {
var patrolQuery = {
action: 'query',
prop: 'info',
meta: 'tokens',
type: 'patrol', // as long as we're querying, might as well get a token
list: 'recentchanges', // check if the page is unpatrolled
titles: ctx.pageName,
rcprop: 'patrolled',
rctitle: ctx.pageName,
rclimit: 1
};
 
ctx.patrolApi = new Morebits.wiki.api('retrieving token...', patrolQuery, fnProcessPatrol);
ctx.patrolApi.setParent(this);
ctx.patrolApi.post();
}
};
 
/**
* Marks the page as reviewed by the PageTriage extension
* https://www.mediawiki.org/wiki/Extension:PageTriage
*
* Referred to as "review" on-wiki
*
* Will, by it's nature, mark as patrolled as well. Falls back to
* patrolling if not in an appropriate namespace.
*
* Doesn't inherently rely on loading the page in question; simply
* passing a pageid to the API is sufficient, so in those cases just
* using Morebits.wiki.api is probably preferable.
*
* No error handling since we don't actually care about the errors
*/
this.triage = function() {
// Fall back to patrol if not a valid triage namespace
if (mw.config.get('pageTriageNamespaces').indexOf(new mw.Title(ctx.pageName).getNamespaceId()) === -1) {
this.patrol();
} else {
if (!Morebits.userIsSysop && !Morebits.userIsInGroup('patroller')) {
return;
}
 
// If on the page in question, don't need to query for page ID
if (new mw.Title(Morebits.pageNameNorm).getPrefixedText() === new mw.Title(ctx.pageName).getPrefixedText()) {
ctx.pageID = mw.config.get('wgArticleId');
fnProcessTriage(this, this);
} else {
var query = fnNeedTokenInfoQuery('triage');
 
ctx.triageApi = new Morebits.wiki.api('retrieving token...', query, fnProcessTriage);
ctx.triageApi.setParent(this);
ctx.triageApi.post();
}
}
};
 
Line 2,288 ⟶ 2,943:
 
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsInGroup('sysop')userIsSysop) {
ctx.statusElement.error('Cannot delete page: only admins can do that');
ctx.onDeleteFailure(this);
Line 2,302 ⟶ 2,957:
fnProcessDelete.call(this, this);
} else {
var query = {fnNeedTokenInfoQuery('delete');
action: 'query',
prop: 'info',
inprop: 'protection',
intoken: 'delete',
titles: ctx.pageName
};
if (ctx.followRedirect) {
query.redirects = ''; // follow all redirects
}
 
ctx.deleteApi = new Morebits.wiki.api('retrieving delete token...', query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure);
ctx.deleteApi.setParent(this);
ctx.deleteApi.post();
Line 2,329 ⟶ 2,975:
 
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsInGroup('sysop')userIsSysop) {
ctx.statusElement.error('Cannot undelete page: only admins can do that');
ctx.onUndeleteFailure(this);
Line 2,343 ⟶ 2,989:
fnProcessUndelete.call(this, this);
} else {
var query = {fnNeedTokenInfoQuery('undelete');
action: 'query',
prop: 'info',
inprop: 'protection',
intoken: 'undelete',
titles: ctx.pageName
};
 
ctx.undeleteApi = new Morebits.wiki.api('retrieving undelete token...', query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure);
ctx.undeleteApi.setParent(this);
ctx.undeleteApi.post();
Line 2,367 ⟶ 3,007:
 
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsInGroup('sysop')userIsSysop) {
ctx.statusElement.error('Cannot protect page: only admins can do that');
ctx.onProtectFailure(this);
Line 2,383 ⟶ 3,023:
}
 
// because of the way MW API interprets protection levels (absolute, not
// (absolute, not differential), we always need to request protection levels from the server
// protection levels from the server
var query = {
var query = fnNeedTokenInfoQuery('protect');
action: 'query',
prop: 'info',
inprop: 'protection',
intoken: 'protect',
titles: ctx.pageName,
watchlist: ctx.watchlistOption
};
if (ctx.followRedirect) {
query.redirects = ''; // follow all redirects
}
 
ctx.protectApi = new Morebits.wiki.api('retrieving protect token...', query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure);
ctx.protectApi.setParent(this);
ctx.protectApi.post();
};
 
/**
// apply FlaggedRevs protection-style settings
* Apply FlaggedRevs protection-style settings
// only works where $wgFlaggedRevsProtection = true (i.e. where FlaggedRevs
* only works where $wgFlaggedRevsProtection = true (i.e. where FlaggedRevs
// settings appear on the wiki's "protect" tab)
* settings appear on the wiki's "protect" tab)
* @param {function} [onSuccess]
* @param {function} [onFailure]
*/
this.stabilize = function(onSuccess, onFailure) {
ctx.onStabilizeSuccess = onSuccess;
Line 2,410 ⟶ 3,045:
 
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsInGroup('sysop')userIsSysop) {
ctx.statusElement.error('Cannot apply FlaggedRevs settings: only admins can do that');
ctx.onStabilizeFailure(this);
Line 2,426 ⟶ 3,061:
}
 
if (fnCanUseMwUserToken('stabilize')) {
var query = {
fnProcessStabilize.call(this, this);
action: 'query',
} else {
prop: 'info|flagged',
var query = fnNeedTokenInfoQuery('stabilize');
intoken: 'edit',
 
titles: ctx.pageName
ctx.stabilizeApi = new Morebits.wiki.api('retrieving token...', query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure);
};
ctx.stabilizeApi.setParent(this);
if (ctx.followRedirect) {
ctx.stabilizeApi.post();
query.redirects = ''; // follow all redirects
}
 
ctx.stabilizeApi = new Morebits.wiki.api('retrieving stabilize token...', query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure);
ctx.stabilizeApi.setParent(this);
ctx.stabilizeApi.post();
};
 
Line 2,447 ⟶ 3,078:
 
/**
* Determines whether we can save an API call by using the editcsrf token sent with the page
* HTML, or whether we need to ask the server for more info (e.g. protection expiry).
*
* Currently only used for append, prepend, andnewSection, deletePage.move, stabilize,
* deletePage, and undeletePage. Can't use for protect since it always
* needs to request protection status.
*
* @param {string} [action=edit] The action being undertaken, e.g. "edit", "delete".
* "edit" or "delete". In practice, only "edit" or "notedit" matters.
* @returns {boolean}
*/
var fnCanUseMwUserToken = function(action) {
action = typeof action !== 'undefined' ? action : 'edit'; // IE doesn't support default parameters
 
// API-based redirect resolution only works for action=query and
// action=edit in append/prepend/new modes (and section=new, but we don't
if (ctx.followRedirect) {
// really support that)
if (!ctx.followRedirect && (action !== 'edit'followCrossNsRedirect) ||{
return false; // must load the page to check for cross namespace redirects
(ctx.editMode !== 'append' && ctx.editMode !== 'prepend'))) {
}
return false;
if (action !== 'edit' || (ctx.editMode === 'all' || ctx.editMode === 'revert')) {
return false;
}
}
 
// do we need to fetch the edit protection expiry?
if (Morebits.userIsInGroup('sysop')userIsSysop && !ctx.suppressProtectWarning) {
if (new mw.Title(Morebits.pageNameNorm).getPrefixedText() !== new mw.Title(ctx.pageName).getPrefixedText()) {
// poor man's normalisation
if (Morebits.string.toUpperCaseFirstChar(mw.config.get('wgPageName')).replace(/ /g, '_').trim() !==
Morebits.string.toUpperCaseFirstChar(ctx.pageName).replace(/ /g, '_').trim()) {
return false;
}
 
// wgRestrictionEdit is null on non-existent pages,
// so this neatly handles nonexistent pages
var editRestriction = mw.config.get('wgRestrictionEdit');
if (!editRestriction || editRestriction.indexOf('sysop') !== -1) {
Line 2,481 ⟶ 3,120:
};
 
/**
// callback from loadSuccess() for append() and prepend() threads
* When functions can't use fnCanUseMwUserToken or require checking
* protection, maintain the query in one place. Used for delete,
* undelete, protect, stabilize, and move (basically, just not load)
*
* @param {string} action The action being undertaken, e.g. "edit" or
* "delete"
*/
var fnNeedTokenInfoQuery = function(action) {
var query = {
action: 'query',
meta: 'tokens',
type: 'csrf',
titles: ctx.pageName
};
// Protection not checked for flagged-revs or non-sysop moves
if (action !== 'stabilize' && (action !== 'move' || Morebits.userIsSysop)) {
query.prop = 'info';
query.inprop = 'protection';
}
if (ctx.followRedirect && action !== 'undelete') {
query.redirects = ''; // follow all redirects
}
return query;
};
 
// callback from loadSuccess() for append(), prepend(), and newSection() threads
var fnAutoSave = function(pageobj) {
pageobj.save(ctx.onSaveSuccess, ctx.onSaveFailure);
Line 2,497 ⟶ 3,162:
if (ctx.pageExists) {
ctx.pageText = $(xml).find('rev').text();
ctx.pageID = $(xml).find('page').attr('pageid');
} else {
ctx.pageText = ''; // allow for concatenation, etc.
ctx.pageID = 0; // nonexistent in response, matches wgArticleId
}
ctx.csrfToken = $(xml).find('tokens').attr('csrftoken');
if (!ctx.csrfToken) {
ctx.statusElement.error('Failed to retrieve edit token.');
ctx.onLoadFailure(this);
return;
}
ctx.loadTime = $(xml).find('api').attr('curtimestamp');
if (!ctx.loadTime) {
ctx.statusElement.error('Failed to retrieve current timestamp.');
ctx.onLoadFailure(this);
return;
}
 
// extract protection info, to alert admins when they are about to edit a protected page
if (Morebits.userIsInGroup('sysop')userIsSysop) {
var editprot = $(xml).find('pr[type="edit"]');
if (editprot.length > 0 && editprot.attr('level') === 'sysop') {
Line 2,511 ⟶ 3,190:
}
 
ctx.editToken = $(xml).find('page').attr('edittoken');
if (!ctx.editToken) {
ctx.statusElement.error('Failed to retrieve edit token.');
ctx.onLoadFailure(this);
return;
}
ctx.loadTime = $(xml).find('page').attr('starttimestamp');
if (!ctx.loadTime) {
ctx.statusElement.error('Failed to retrieve start timestamp.');
ctx.onLoadFailure(this);
return;
}
ctx.lastEditTime = $(xml).find('rev').attr('timestamp');
ctx.revertCurID = $(xml).find('page').attr('lastrevid');
Line 2,570 ⟶ 3,237:
var resolvedName = $(xml).find('page').attr('title');
 
// only notify user for redirects, not normalization
if ($(xml).find('redirects').length > 0) {
// 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) {
ctx.statusElement.error(ctx.pageName + ' is a cross-namespace redirect to ' + resolvedName + ', aborted');
onFailure(this);
return false;
}
 
// only notify user for redirects, not normalization
Morebits.status.info('Info', 'Redirected from ' + ctx.pageName + ' to ' + resolvedName);
}
 
ctx.pageName = resolvedName; // always update in case of normalization
ctx.pageName = resolvedName; // update to redirect target or normalized name
 
} else {
// could be a circular redirect or other problem
Line 2,589 ⟶ 3,267:
// callback from saveApi.post()
var fnSaveSuccess = function() {
ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes
var xml = ctx.saveApi.getXML();
 
Line 2,634 ⟶ 3,312:
};
 
var purgeApi = new Morebits.wiki.api('Edit conflict detected, purging server cache', purgeQuery, null, ctx.statusElementfunction(); {
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
purgeApi.post({ async: false }); // just wait for it, result is for debugging
 
ctx.statusElement.info('Edit conflict detected, reapplying edit');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
if (fnCanUseMwUserToken('edit')) {
 
ctx.saveApi.post(); // necessarily append, prepend, or newSection, so this should work as desired
ctx.statusElement.info('Edit conflict detected, reapplying edit');
} else {
if (fnCanUseMwUserToken('edit')) {
ctx.saveApiloadApi.post(); // necessarilyreload appendthe orpage prepend,and soreapply thisthe should work as desirededit
} else {
}, ctx.statusElement);
ctx.loadApi.post(); // reload the page and reapply the edit
purgeApi.post();
}
 
// check for loss of edit token
// it's impractical to request a new token here, so invoke edit conflict logic when this happens
} else if (errorCode === 'notoken' && ctx.conflictRetries++ < ctx.maxConflictRetries) {
 
ctx.statusElement.info('Edit token is invalid, retrying');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
if (fnCanUseMwUserToken('edit')) {
this.load(fnAutoSave, ctx.onSaveFailure); // try the append or prepend again
} else {
ctx.loadApi.post(); // reload the page and reapply the edit
}
 
// check for network or server error
} else if ((errorCode === 'null || errorCode === undefined') && ctx.retries++ < ctx.maxRetries) {
 
// the error might be transient, so try again
ctx.statusElement.info('Save failed, retrying in 2 seconds ...');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
 
ctx.saveApi.post(); // give it another go!
// wait for sometime for client to regain connnectivity
sleep(2000).then(function() {
ctx.saveApi.post(); // give it another go!
});
 
// hard error, give up
} else {
 
switch (errorCode) {
// non-admin attempting to edit a protected page - this gives a friendlier message than the default
 
if (errorCode === 'protectedpage') {
case 'protectedpage':
ctx.statusElement.error('Failed to save edit: Page is protected');
// non-admin attempting to edit a protected page - this gives a friendlier message than the default
// check for absuefilter hits: disallowed or warning
ctx.statusElement.error('Failed to save edit: Page is protected');
} else if (errorCode.indexOf('abusefilter') === 0) {
break;
var desc = $(ctx.saveApi.getXML()).find('abusefilter').attr('description');
 
if (errorCode === 'abusefilter-disallowed') {
case 'abusefilter-disallowed':
ctx.statusElement.error('The edit was disallowed by the edit filter: "' + desc + '".');
ctx.statusElement.error('The edit was disallowed by the edit filter: "' + $(ctx.saveApi.getXML()).find('abusefilter').attr('description') + '".');
} else if (errorCode === 'abusefilter-warning') {
break;
ctx.statusElement.error([ 'A warning was returned by the edit filter: "', desc, '". If you wish to proceed with the edit, please carry it out again. This warning will not appear a second time.' ]);
 
case 'abusefilter-warning':
ctx.statusElement.error([ 'A warning was returned by the edit filter: "', $(ctx.saveApi.getXML()).find('abusefilter').attr('description'), '". If you wish to proceed with the edit, please carry it out again. This warning will not appear a second time.' ]);
// We should provide the user with a way to automatically retry the action if they so choose -
// I can't see how to do this without creating a UI dependency on Morebits.wiki.page though -- TTO
break;
} else { // shouldn't happen but...
 
ctx.statusElement.error('The edit was disallowed by the edit filter.');
case 'spamblacklist':
}
// .find('matches') returns an array in case multiple items are blacklisted, we only return the first
// check for blacklist hits
var spam = $(ctx.saveApi.getXML()).find('spamblacklist').find('matches').children()[0].textContent;
} else if (errorCode === 'spamblacklist') {
ctx.statusElement.error(ctx.saveApi.getErrorText()'Could not save the page because the URL ' + spam + ' is on the spam blacklist');
} else { break;
 
ctx.statusElement.error('Failed to save edit: ' + ctx.saveApi.getErrorText());
default:
ctx.statusElement.error('Failed to save edit: ' + ctx.saveApi.getErrorText());
}
 
ctx.editMode = 'all'; // cancel append/prepend/revert modes
ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes
if (ctx.onSaveFailure) {
ctx.onSaveFailure(this); // invoke callback
Line 2,704 ⟶ 3,380:
}
 
if (!ctx.creatorlookupNonRedirectCreator =|| !/^\s*#redirect/i.test($(xml).find('rev').attrtext('user');)) {
 
ctx.creator = $(xml).find('rev').attr('user');
if (!ctx.creator) {
ctx.statusElement.error('Could not find name of page creator');
return;
}
ctx.timestamp = $(xml).find('rev').attr('timestamp');
if (!ctx.timestamp) {
ctx.statusElement.error('Could not find timestamp of page creation');
return;
}
ctx.onLookupCreationSuccess(this);
 
} else {
ctx.lookupCreationApi.query.rvlimit = 50; // modify previous query to fetch more revisions
ctx.lookupCreationApi.query.titles = ctx.pageName; // update pageName if redirect resolution took place in earlier query
 
ctx.lookupCreationApi = new Morebits.wiki.api('Retrieving page creation information', ctx.lookupCreationApi.query, fnLookupNonRedirectCreator, ctx.statusElement);
ctx.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
}
 
};
 
var fnLookupNonRedirectCreator = function() {
var xml = ctx.lookupCreationApi.getXML();
 
$(xml).find('rev').each(function(_, rev) {
if (!/^\s*#redirect/i.test(rev.textContent)) { // inaccessible revisions also check out
ctx.creator = rev.getAttribute('user');
ctx.timestamp = rev.getAttribute('timestamp');
return false; // break
}
});
 
if (!ctx.creator) {
// fallback to give first revision author if no non-redirect version in the first 50
ctx.statusElement.error('Could not find name of page creator');
ctx.creator = $(xml).find('rev')[0].getAttribute('user');
return;
ctx.timestamp = $(xml).find('rev')[0].getAttribute('timestamp');
if (!ctx.creator) {
ctx.statusElement.error('Could not find name of page creator');
return;
}
 
}
ctx.timestamp = $(xml).find('rev').attr('timestamp');
if (!ctx.timestamp) {
ctx.statusElement.error('Could not find timestamp of page creation');
Line 2,716 ⟶ 3,432:
 
ctx.onLookupCreationSuccess(this);
 
};
 
var fnProcessMove = function() {
var pageTitle, token;
var xml = ctx.moveApi.getXML();
 
if ($(xml).findfnCanUseMwUserToken('pagemove').attr('missing') === '') {
token = mw.user.tokens.get('csrfToken');
ctx.statusElement.error('Cannot move the page, because it no longer exists');
pageTitle = ctx.onMoveFailure(this)pageName;
} else {
return;
var xml = ctx.moveApi.getXML();
}
 
if ($(xml).find('page').attr('missing') === '') {
// extract protection info
ctx.statusElement.error('Cannot move the page, because it no longer exists');
if (Morebits.userIsInGroup('sysop')) {
var editprot = $(xml).find('pr[type="edit"]');
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
!confirm('You are about to move the fully protected page "' + ctx.pageName +
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + editprot.attr('expiry') + ')') +
'. \n\nClick OK to proceed with the move, or Cancel to skip this move.')) {
ctx.statusElement.error('Move of fully protected page was aborted.');
ctx.onMoveFailure(this);
return;
}
}
 
// extract protection info
var moveToken = $(xml).find('page').attr('movetoken');
if (!moveTokenMorebits.userIsSysop) {
var editprot = $(xml).find('pr[type="edit"]');
ctx.statusElement.error('Failed to retrieve move token.');
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
ctx.onMoveFailure(this);
!confirm('You are about to move the fully protected page "' + ctx.pageName +
return;
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + new Morebits.date(editprot.attr('expiry')).calendar('utc') + ' (UTC))') +
'. \n\nClick OK to proceed with the move, or Cancel to skip this move.')) {
ctx.statusElement.error('Move of fully protected page was aborted.');
ctx.onMoveFailure(this);
return;
}
}
 
token = $(xml).find('tokens').attr('csrftoken');
if (!token) {
ctx.statusElement.error('Failed to retrieve move token.');
ctx.onMoveFailure(this);
return;
}
 
pageTitle = $(xml).find('page').attr('title');
}
 
var query = {
'action': 'move',
'from': $(xml).find('page').attr('title')pageTitle,
'to': ctx.moveDestination,
'token': moveTokentoken,
'reason': ctx.editSummary,
'watchlist': ctx.watchlistOption
};
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
if (ctx.moveTalkPage) {
query.movetalk = 'true';
}
if (ctx.moveSubpages) {
query.movesubpages = 'true'; // XXX don't know whether this works for non-admins
}
if (ctx.moveSuppressRedirect) {
query.noredirect = 'true';
}
if (ctx.watchlistOption === 'watch') {
query.watch = 'true';
}
 
Line 2,770 ⟶ 3,498:
ctx.moveProcessApi.setParent(this);
ctx.moveProcessApi.post();
};
 
var fnProcessPatrol = function() {
var query = {
action: 'patrol'
};
 
// Didn't need to load the page
if (ctx.rcid) {
query.rcid = ctx.rcid;
query.token = mw.user.tokens.get('patrolToken');
} else {
var xml = ctx.patrolApi.getResponse();
 
// Don't patrol if not unpatrolled
if ($(xml).find('rc').attr('unpatrolled') !== '') {
return;
}
 
var lastrevid = $(xml).find('page').attr('lastrevid');
if (!lastrevid) {
return;
}
query.revid = lastrevid;
 
var token = $(xml).find('tokens').attr('patroltoken');
if (!token) {
return;
}
 
query.token = token;
}
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
var patrolStat = new Morebits.status('Marking page as patrolled');
 
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat);
ctx.patrolProcessApi.setParent(this);
ctx.patrolProcessApi.post();
};
 
var fnProcessTriage = function() {
var pageID, token;
 
if (ctx.pageID) {
token = mw.user.tokens.get('csrfToken');
pageID = ctx.pageID;
} else {
var xml = ctx.triageApi.getXML();
 
pageID = $(xml).find('page').attr('pageid');
if (!pageID) {
return;
}
 
token = $(xml).find('tokens').attr('csrftoken');
if (!token) {
return;
}
}
 
var query = {
action: 'pagetriageaction',
pageid: pageID,
reviewed: 1,
// tags: ctx.changeTags, // pagetriage tag support: [[phab:T252980]]
// Could use an adder to modify/create note:
// summaryAd, but that seems overwrought
token: token
};
 
var triageStat = new Morebits.status('Marking page as curated');
 
ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, fnProcessTriageSuccess, triageStat, fnProcessTriageError);
ctx.triageProcessApi.setParent(this);
ctx.triageProcessApi.post();
};
 
// callback from triageProcessApi.post()
var fnProcessTriageSuccess = function() {
// Swallow succesful return if nothing changed i.e. page in queue and already triaged
if ($(ctx.triageProcessApi.getResponse()).find('pagetriageaction').attr('pagetriage_unchanged_status')) {
ctx.triageProcessApi.getStatusElement().unlink();
}
};
 
// callback from triageProcessApi.post()
var fnProcessTriageError = function() {
// Ignore error if page not in queue, see https://github.com/azatoth/twinkle/pull/930
if (ctx.triageProcessApi.getErrorCode() === 'bad-pagetriage-page') {
ctx.triageProcessApi.getStatusElement().unlink();
}
};
 
Line 2,791 ⟶ 3,613:
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
!confirm('You are about to delete the fully protected page "' + ctx.pageName +
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + new Morebits.date(editprot.attr('expiry')).calendar('utc') + ' (UTC))') +
'. \n\nClick OK to proceed with the deletion, or Cancel to skip this deletion.')) {
ctx.statusElement.error('Deletion of fully protected page was aborted.');
Line 2,798 ⟶ 3,620:
}
 
token = $(xml).find('pagetokens').attr('deletetokencsrftoken');
if (!token) {
ctx.statusElement.error('Failed to retrieve delete token.');
Line 2,812 ⟶ 3,634:
'title': pageTitle,
'token': token,
'reason': ctx.editSummary,
'watchlist': ctx.watchlistOption
};
if (ctx.watchlistOption === 'watch'changeTags) {
query.watchtags = 'true'ctx.changeTags;
}
 
 
ctx.deleteProcessApi = new Morebits.wiki.api('deleting page...', query, ctx.onDeleteSuccess, ctx.statusElement, fnProcessDeleteError);
Line 2,833 ⟶ 3,657:
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.deleteProcessApi.post(); // give it another go!
 
} else if (errorCode === 'badtoken') {
// this is pathetic, but given the current state of Morebits.wiki.page it would
// be a dog's breakfast to try and fix this
ctx.statusElement.error('Invalid token. Please refresh the page and try again.');
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, this, ctx.deleteProcessApi);
}
} else if (errorCode === 'missingtitle') {
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
Line 2,857 ⟶ 3,675:
var pageTitle, token;
 
// The whole handling of tokens in Morebits is outdated (#615)
// but has generally worked since intoken has been deprecated
// but remains. intoken does not, however, take undelete, so
// fnCanUseMwUserToken('undelete') is no good. Everything
// except watching and patrolling should eventually use csrf,
// but until then (#615) the stupid hack below should work for
// undeletion.
if (fnCanUseMwUserToken('undelete')) {
token = mw.user.tokens.get('csrfToken');
Line 2,880 ⟶ 3,691:
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
!confirm('You are about to undelete the fully create protected page "' + ctx.pageName +
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + new Morebits.date(editprot.attr('expiry')).calendar('utc') + ' (UTC))') +
'. \n\nClick OK to proceed with the undeletion, or Cancel to skip this undeletion.')) {
ctx.statusElement.error('Undeletion of fully create protected page was aborted.');
Line 2,887 ⟶ 3,698:
}
 
token = $(xml).find('tokens').attr('csrftoken');
// KLUDGE:
if (!token) {
token = mw.user.tokens.get('csrfToken');
ctx.statusElement.error('Failed to retrieve undelete token.');
pageTitle = ctx.pageName;
ctx.onUndeleteFailure(this);
return;
}
 
pageTitle = $(xml).find('page').attr('title');
}
 
Line 2,896 ⟶ 3,712:
'title': pageTitle,
'token': token,
'reason': ctx.editSummary,
'watchlist': ctx.watchlistOption
};
if (ctx.watchlistOption === 'watch'changeTags) {
query.watchtags = 'true'ctx.changeTags;
}
 
 
ctx.undeleteProcessApi = new Morebits.wiki.api('undeleting page...', query, ctx.onUndeleteSuccess, ctx.statusElement, fnProcessUndeleteError);
Line 2,913 ⟶ 3,731:
 
// check for "Database query error"
if (errorCode === 'internal_api_error_DBQueryError' && 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 if (errorCode === 'badtoken') {
} else {
// this is pathetic, but given the current state of Morebits.wiki.page it would
ctx.statusElement.error('Repeated database query error, please try again');
// be a dog's breakfast to try and fix this
if (ctx.onUndeleteFailure) {
ctx.statusElement.error('Invalid token. Please refresh the page and try again.');
if ( ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke {callback
}
ctx.onUndeleteFailure.call(this, this, ctx.undeleteProcessApi);
}
} else if (errorCode === 'cantundelete') {
Line 2,955 ⟶ 3,773:
// TODO cascading protection not possible on edit<sysop
 
var protectTokentoken = $(xml).find('pagetokens').attr('protecttokencsrftoken');
if (!protectTokentoken) {
ctx.statusElement.error('Failed to retrieve protect token.');
ctx.onProtectFailure(this);
return;
}
 
var pageTitle = $(xml).find('page').attr('title');
 
// fetch existing protection levels
Line 2,997 ⟶ 3,817:
var query = {
action: 'protect',
title: $(xml).find('page').attr('title')pageTitle,
token: protectTokentoken,
protections: protections.join('|'),
expiry: expirys.join('|'),
reason: ctx.editSummary,
watchlist: ctx.watchlistOption
};
// Only shows up in logs, not page history [[phab:T259983]]
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
if (ctx.protectCascade) {
query.cascade = 'true';
}
if (ctx.watchlistOption === 'watch') {
query.watch = 'true';
}
 
Line 3,016 ⟶ 3,839:
 
var fnProcessStabilize = function() {
var pageTitle, token;
var xml = ctx.stabilizeApi.getXML();
 
if (fnCanUseMwUserToken('stabilize')) {
var missing = $(xml).find('page').attr('missing') === '';
token = mw.user.tokens.get('csrfToken');
if (missing) {
pageTitle = ctx.pageName;
ctx.statusElement.error('Cannot protect the page, because it no longer exists');
} else {
ctx.onStabilizeFailure(this);
var xml = ctx.stabilizeApi.getXML();
return;
}
 
var stabilizeTokenmissing = $(xml).find('page').attr('edittokenmissing') === '';
if (!stabilizeTokenmissing) {
ctx.statusElement.error('FailedCannot toprotect retrievethe stabilizepage, token.because it no longer exists');
ctx.onStabilizeFailure(this);
return;
}
 
token = $(xml).find('tokens').attr('csrftoken');
if (!token) {
ctx.statusElement.error('Failed to retrieve stabilize token.');
ctx.onStabilizeFailure(this);
return;
}
 
pageTitle = $(xml).find('page').attr('title');
}
 
var query = {
action: 'stabilize',
title: $(xml).find('page').attr('title')pageTitle,
token: stabilizeTokentoken,
protectlevel: ctx.flaggedRevs.level,
expiry: ctx.flaggedRevs.expiry,
// tags: ctx.changeTags, // flaggedrevs tag support: [[phab:T247721]]
reason: ctx.editSummary
reason: ctx.editSummary,
watchlist: ctx.watchlistOption
};
if (ctx.watchlistOption === 'watch') {
query.watch = 'true';
}
 
ctx.stabilizeProcessApi = new Morebits.wiki.api('configuring stabilization settings...', query, ctx.onStabilizeSuccess, ctx.statusElement, ctx.onStabilizeFailure);
Line 3,048 ⟶ 3,879:
ctx.stabilizeProcessApi.post();
};
 
var sleep = function(milliseconds) {
var deferred = $.Deferred();
setTimeout(deferred.resolve, milliseconds);
return deferred;
};
 
}; // end Morebits.wiki.page
 
Line 3,083 ⟶ 3,921:
* @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
*/
this.beginRender = function(wikitext, pageTitle, sectionTitle) {
$(previewbox).show();
 
Line 3,096 ⟶ 3,935:
pst: 'true', // PST = pre-save transform; this makes substitution work properly
text: wikitext,
title: pageTitle || mw.config.get('wgPageName'),
disablelimitreport: true
};
if (sectionTitle) {
query.section = 'new';
query.sectiontitle = sectionTitle;
}
var renderApi = new Morebits.wiki.api('loading...', query, fnRenderSuccess, new Morebits.status('Preview'));
renderApi.post();
Line 3,113 ⟶ 3,957:
};
 
/** Hides the preview box and clears it. */
/**
* Hides the preview box and clears it.
*/
this.closePreview = function() {
$(previewbox).empty().hide();
Line 3,130 ⟶ 3,972:
Morebits.wikitext = {};
 
/**
Morebits.wikitext.template = {
* Get the value of every parameter found in a given template
parse: function(text, start) {
* @param {string} text Wikitext containing a template
var count = -1;
* @param {number} [start=0] Index noting where in the text the template begins
var level = -1;
* @returns {Object} {name: templateName, parameters: {key: value}}
var equals = -1;
*/
var current = '';
Morebits.wikitext.parseTemplate = function(text, start) {
var result = {
start = start || 0;
name: '',
parameters: {}
};
var key, value;
 
var count = -1;
for (var i = start; i < text.length; ++i) {
var test3level = text.substr(i, 3)-1;
var equals = -1;
if (test3 === '{{{') {
var current += '{{{';
var result = {
i += 2;
name: '',
++level;
parameters: {}
continue;
};
}
var key, value;
if (test3 === '}}}') {
current += '}}}';
i += 2;
--level;
continue;
}
var test2 = text.substr(i, 2);
if (test2 === '{{' || test2 === '[[') {
current += test2;
++i;
++level;
continue;
}
if (test2 === ']]') {
current += ']]';
++i;
--level;
continue;
}
if (test2 === '}}') {
current += test2;
++i;
--level;
 
for (var i = start; i < text.length; ++i) {
if (level <= 0) {
var test3 = text.substr(i, 3);
if (count === -1) {
if (test3 === '{{{') {
result.name = current.substring(2).trim();
current ++count= '{{{';
}i else+= {2;
++level;
if (equals !== -1) {
continue;
key = current.substring(0, equals).trim();
}
value = current.substring(equals).trim();
if (test3 === '}}}') {
result.parameters[key] = value;
equalscurrent += -1'}}}';
}i else+= {2;
--level;
result.parameters[count] = current;
++countcontinue;
}
var test2 = text.substr(i, 2);
}
if (test2 === '{{' || test2 === '[[') {
break;
current += test2;
}
continue++i;
}++level;
continue;
}
if (test2 === ']]') {
current += ']]';
++i;
--level;
continue;
}
if (test2 === '}}') {
current += test2;
++i;
--level;
 
if (text.charAt(i) === '|' && level <= 0) {
if (count === -1) {
result.name = current.substring(2).trim();
Line 3,201 ⟶ 4,030:
if (equals !== -1) {
key = current.substring(0, equals).trim();
value = current.substring(equals + 1).trim();
result.parameters[key] = value;
equals = -1;
Line 3,209 ⟶ 4,038:
}
}
current = ''break;
} else if (equals === -1 && text.charAt(i) === '=' && level <= 0) {
equals = current.length;
current += text.charAt(i);
} else {
current += text.charAt(i);
}
continue;
}
 
if (text.charAt(i) === '|' && level <= 0) {
return result;
if (count === -1) {
result.name = current.substring(2).trim();
++count;
} else {
if (equals !== -1) {
key = current.substring(0, equals).trim();
value = current.substring(equals + 1).trim();
result.parameters[key] = value;
equals = -1;
} else {
result.parameters[count] = current;
++count;
}
}
current = '';
} else if (equals === -1 && text.charAt(i) === '=' && level <= 0) {
equals = current.length;
current += text.charAt(i);
} else {
current += text.charAt(i);
}
}
 
return result;
};
 
Line 3,236 ⟶ 4,084:
* Removes links to `link_target` from the page text.
* @param {string} link_target
*
* @returns {Morebits.wikitext.page}
*/
removeLink: function(link_target) {
var first_char = link_target.substr(0, 1);
var link_re_string = '[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExpMorebits.escapestring.escapeRegExp(link_target.substr(1), true);
 
// Files and Categories become links with a leading colon, e.g. [[:File:Test.png]]
// Otherwise, allow for an optional leading colon, e.g. [[:FileUser:Test.png]]
var special_ns_re = /^(?:[Ff]ile|[Ii]mage|[Cc]ategory):/;
var colon = special_ns_re.test(link_target) ? ':' : ':?';
 
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(link_simple_re, '$1').replace(link_named_re, '$1');
return this;
},
 
Line 3,256 ⟶ 4,107:
* @param {string} image - Image name without File: prefix
* @param {string} reason - Reason to be included in comment, alongside the commented-out image
*
* @returns {Morebits.wikitext.page}
*/
commentOutImage: function(image, reason) {
Line 3,263 ⟶ 4,116:
reason = reason ? reason + ': ' : '';
var first_char = image.substr(0, 1);
var image_re_string = '[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExpMorebits.escapestring.escapeRegExp(image.substr(1), true);
 
// Check for normal image links, i.e. [[File:Foobar.png|...]]
Line 3,293 ⟶ 4,146:
// Rebind the content now, we are done!
this.text = unbinder.rebind();
return this;
},
 
Line 3,299 ⟶ 4,153:
* @param {string} image - Image name without File: prefix
* @param {string} data
*
* @returns {Morebits.wikitext.page}
*/
addToImageComment: function(image, data) {
var first_char = image.substr(0, 1);
var first_char_regex = RegExpMorebits.escapestring.escapeRegExp(first_char, true);
if (first_char.toUpperCase() !== first_char.toLowerCase()) {
first_char_regex = '[' + RegExpMorebits.escapestring.escapeRegExp(first_char.toUpperCase(), true) + RegExpMorebits.escapestring.escapeRegExp(first_char.toLowerCase(), true) + ']';
}
var image_re_string = '(?:[Ii]mage|[Ff]ile):\\s*' + first_char_regex + RegExpMorebits.escapestring.escapeRegExp(image.substr(1), true);
var links_re = new RegExp('\\[\\[' + image_re_string);
var allLinks = Morebits.array.uniq(Morebits.string.splitWeightedByKeys(this.text, '[[', ']]'));
Line 3,320 ⟶ 4,176:
var newtext = '$1|$2 ' + data;
this.text = this.text.replace(gallery_re, newtext);
return this;
},
 
Line 3,326 ⟶ 4,183:
* @param {string} template - Page name whose transclusions are to be removed,
* include namespace prefix only if not in template namespace
*
* @returns {Morebits.wikitext.page}
*/
removeTemplate: function(template) {
var first_char = template.substr(0, 1);
var template_re_string = '(?:[Tt]emplate:)?\\s*[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExpMorebits.escapestring.escapeRegExp(template.substr(1), true);
var links_re = new RegExp('\\{\\{' + template_re_string);
var allTemplates = Morebits.array.uniq(Morebits.string.splitWeightedByKeys(this.text, '{{', '}}', [ '{{{', '}}}' ]));
Line 3,337 ⟶ 4,196:
}
}
return this;
},
 
/**
getText: function() {
* Smartly insert a tag atop page text but after specified templates,
return this.text;
* such as hatnotes, short description, or deletion and protection templates.
}
* Notably, does *not* insert a newline after the tag
};
*
* @param {string} tag - The tag to be inserted
* @param {string|string[]} regex - Templates after which to insert tag,
* given as either as a (regex-valid) string or an array to be joined by pipes
* @param {string} [flags=i] - Regex flags to apply. Optional, defaults to /i
* @param {string|string[]} preRegex - Optional regex string or array to match
* before any template matches (i.e. before `{{`), such as html comments
*
* @returns {Morebits.wikitext.page}
*/
insertAfterTemplates: function(tag, regex, flags, preRegex) {
if (typeof tag === 'undefined') {
throw new Error('No tag provided');
}
 
// .length is only a property of strings and arrays so we
// shouldn't need to check type
if (typeof regex === 'undefined' || !regex.length) {
throw new Error('No regex provided');
} else if (Array.isArray(regex)) {
regex = regex.join('|');
}
 
flags = flags || 'i';
 
if (!preRegex || !preRegex.length) {
/**
preRegex = '';
* **************** Morebits.queryString ****************
} else if (Array.isArray(preRegex)) {
* Maps the querystring to an JS object
preRegex = preRegex.join('|');
*
}
* In static context, the value of location.search.substring(1), else the value given
* to the constructor is going to be used. The mapped hash is saved in the object.
*
* Example:
*
* var value = Morebits.queryString.get('key');
* var obj = new Morebits.queryString('foo=bar&baz=quux');
* value = obj.get('foo');
*/
 
/**
* @constructor
* @param {string} qString The query string
*/
Morebits.queryString = function QueryString(qString) {
this.string = qString;
this.params = {};
 
// Regex is extra complicated to allow for templates with
if (!qString.length) {
// parameters and to handle whitespace properly
return;
this.text = this.text.replace(
}
new RegExp(
// leading whitespace
'^\\s*' +
// capture template(s)
'(?:((?:\\s*' +
// Pre-template regex, such as leading html comments
preRegex + '|' +
// begin template format
'\\{\\{\\s*(?:' +
// Template regex
regex +
// end main template name, optionally with a number
// Probably remove the (?:) though
')\\d*\\s*' +
// template parameters
'(\\|(?:\\{\\{[^{}]*\\}\\}|[^{}])*)?' +
// end template format
'\\}\\})+' +
// end capture
'(?:\\s*\\n)?)' +
// trailing whitespace
'\\s*)?',
flags), '$1' + tag
);
return this;
},
 
/** @returns {string} */
qString = qString.replace(/\+/g, ' ');
getText: function() {
var args = qString.split('&');
return this.text;
 
for (var i = 0; i < args.length; ++i) {
var pair = args[i].split('=');
var key = decodeURIComponent(pair[0]), value = key;
 
if (pair.length === 2) {
value = decodeURIComponent(pair[1]);
}
 
this.params[key] = value;
}
};
 
/**
Morebits.queryString.staticstr = null;
* *********** Morebits.userspaceLogger ************
* Handles logging actions to a userspace log, used in
* twinklespeedy and twinkleprod.
*/
 
Morebits.queryString.staticInituserspaceLogger = function(logPageName) {
if (!Morebits.queryString.staticstrlogPageName) {
throw new Error('no log page name specified');
Morebits.queryString.staticstr = new Morebits.queryString(location.search.substring(1));
}
this.initialText = '';
};
this.headerLevel = 3;
this.changeTags = '';
 
Morebits this.queryString.getlog = function(keylogText, summaryText) {
if (!logText) {
Morebits.queryString.staticInit();
return;
return Morebits.queryString.staticstr.get(key);
};
var page = new Morebits.wiki.page('User:' + mw.config.get('wgUserName') + '/' + logPageName,
'Adding entry to userspace log'); // make this '... to ' + logPageName ?
return page.load(function(pageobj) {
// add blurb if log page doesn't exist or is blank
var text = pageobj.getPageText() || this.initialText;
 
// create monthly header if it doesn't exist already
Morebits.queryString.exists = function(key) {
var date = new Morebits.queryStringdate(pageobj.staticInitgetLoadTime());
if (!date.monthHeaderRegex().exec(text)) {
return Morebits.queryString.staticstr.exists(key);
text += '\n\n' + date.monthHeader(this.headerLevel);
};
 
Morebits.queryString.equals = function(key, value) {
Morebits.queryString.staticInit();
return Morebits.queryString.staticstr.equals(key, value);
};
 
Morebits.queryString.toString = function() {
Morebits.queryString.staticInit();
return Morebits.queryString.staticstr.toString();
};
 
Morebits.queryString.create = function(arr) {
var resarr = [];
var editToken; // KLUGE: this should always be the last item in the query string (bug TW-B-0013)
for (var i in arr) {
if (arr[i] === undefined) {
continue;
}
var res;
if (Array.isArray(arr[i])) {
var v = [];
for (var j = 0; j < arr[i].length; ++j) {
v[j] = encodeURIComponent(arr[i][j]);
}
res = v.join('|');
} else {
res = encodeURIComponent(arr[i]);
}
if (i === 'token') {
editToken = res;
} else {
resarr.push(encodeURIComponent(i) + '=' + res);
}
}
if (editToken !== undefined) {
resarr.push('token=' + editToken);
}
return resarr.join('&');
};
 
pageobj.setPageText(text + '\n' + logText);
/**
pageobj.setEditSummary(summaryText);
* @returns {string} the value associated to the given `key`
pageobj.setChangeTags(this.changeTags);
* @param {string} key
pageobj.setCreateOption('recreate');
*/
pageobj.save();
Morebits.queryString.prototype.get = function(key) {
}.bind(this));
return this.params[key] || null;
};
};
 
/**
* **************** Morebits.status ****************
* @returns {boolean} true if the given `key` is set
* @param {string} key
*/
Morebits.queryString.prototype.exists = function(key) {
return !!this.params[key];
};
 
/**
* @constructor
* @returns {boolean} true if the value associated with given `key` equals given `value`
* Morebits.status.init() must be called before any status object is created, otherwise
* @param {string} key
* those statuses won't be visible.
* @param {string} value
* @param {String} text - Text before the the colon `:`
* @param {String} stat - Text after the colon `:`
* @param {String} [type=status] - This parameter determines the font color of the status line,
* this can be 'status' (blue), 'info' (green), 'warn' (red), or 'error' (bold red)
* The default is 'status'
*/
Morebits.queryString.prototype.equals = function(key, value) {
return this.params[key] === value;
};
 
/**
* @returns {string}
*/
Morebits.queryString.prototype.toString = function() {
return this.string || null;
};
 
/**
* Creates a querystring and encodes strings via `encodeURIComponent` and joins arrays with `|`
* @param {Array} arr
* @returns {string}
*/
Morebits.queryString.prototype.create = Morebits.queryString.create;
 
 
 
/**
* **************** Morebits.status ****************
*/
 
/**
* @constructor
* Morebits.status.init() must be called before any status object is created, otherwise
* those statuses won't be visible.
* @param {String} text - Text before the the colon `:`
* @param {String} stat - Text after the colon `:`
* @param {String} [type='status'] - This parameter determines the font color of the status line,
* this can be 'status' (blue), 'info' (green), 'warn' (red), or 'error' (bold red)
* The default is 'status'
*/
 
Morebits.status = function Status(text, stat, type) {
Line 3,527 ⟶ 4,352:
Morebits.status.root = null;
 
/** @param {Function} handler - function to execute on error */
Morebits.status.onError = function(handler) {
if (typeof handler === 'function') {
Line 3,544 ⟶ 4,370:
linked: false,
 
/** Add the status element node to the DOM */
/**
* Add the status element node to the DOM
*/
link: function() {
if (!this.linked && Morebits.status.root) {
Line 3,554 ⟶ 4,378:
},
 
/** Remove the status element node from the DOM */
/**
* Remove the status element node from the DOM
*/
unlink: function() {
if (this.linked) {
Line 3,566 ⟶ 4,388:
/**
* Create a document fragment with the status text
* @param {(string|Element|Array)} obj
* @returns {DocumentFragment}
*/
codify: function(obj) {
Line 3,609 ⟶ 4,433:
},
 
/** Produce the html for first part of the status message */
/**
* Produce the html for first part of the status message
*/
generate: function() {
this.node = document.createElement('div');
Line 3,620 ⟶ 4,442:
},
 
/** Complete the html, for the second part of the status message */
/**
* Complete the html, for the second part of the status message
*/
render: function() {
this.node.className = 'tw_status_morebits_status_' + this.type;
while (this.target.hasChildNodes()) {
this.target.removeChild(this.target.firstChild);
Line 3,655 ⟶ 4,475:
Morebits.status.error = function(text, status) {
return new Morebits.status(text, status, 'error');
};
 
/**
* For the action complete message at the end, create a status line without
* a colon separator.
* @param {String} text
*/
Morebits.status.actionCompleted = function(text) {
var node = document.createElement('div');
node.appendChild(document.createElement('b')).appendChild(document.createTextNode(text));
node.className = 'morebits_status_info';
if (Morebits.status.root) {
Morebits.status.root.appendChild(node);
}
};
 
Line 3,665 ⟶ 4,499:
Morebits.status.printUserText = function(comments, message) {
var p = document.createElement('p');
p.textContentinnerHTML = message;
var div = document.createElement('div');
div.className = 'toccolours';
Line 3,680 ⟶ 4,514:
* **************** Morebits.htmlNode() ****************
* Simple helper function to create a simple node
* @param {string} type - type of HTML element
* @param {string} text - text content
* @param {string} [color] - font color
* @returns {HTMLElement}
*/
 
Morebits.htmlNode = function (type, content, color) {
var node = document.createElement(type);
Line 3,699 ⟶ 4,536:
* doesn't work with checkboxes inside a sortable table, so let's build our own.
*/
 
Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) {
var lastCheckbox = null;
Line 3,752 ⟶ 4,588:
 
/** **************** Morebits.batchOperation ****************
* Iterates over a group of pages (or arbitrary objects) and executes a worker function for each.
* for each.
*
* Constructor: Morebits.batchOperation(currentAction)
Line 3,761 ⟶ 4,598:
* setOption(optionName, optionValue): Sets a known option:
* - chunkSize (integer): the size of chunks to break the array into (default 50).
* Setting this to a small value (<5) can cause problems.
* - preserveIndividualStatusLines (boolean): keep each page's status element visible
* when worker is complete? See note below
*
* run(worker, postFinish): Runs the given callback `worker` for each page in the list.
* The callback must call workerSuccess when succeeding, or workerFailure
* when failing. If using Morebits.wiki.api or Morebits.wiki.page, this is easily
Line 3,774 ⟶ 4,611:
* chunk! Also ensure that either workerSuccess or workerFailure is called no more
* than once.
* The second callback `postFinish` is executed when the entire batch has been processed.
*
* If using preserveIndividualStatusLines, you should try to ensure that the
Line 3,816 ⟶ 4,654:
/**
* Sets the list of pages to work on
* @param {String[]Array} pageList Array of pageobjects over which you wish to execute the namesworker (strings)function
* This is usually the list of page names (strings).
*/
this.setPageList = function(pageList) {
Line 3,858 ⟶ 4,697:
var total = ctx.pageList.length;
if (!total) {
ctx.statusElement.info('nothingno topages dospecified');
ctx.running = false;
if (ctx.postFinish) {
ctx.postFinish();
}
return;
}
Line 3,872 ⟶ 4,714:
};
 
/**
this.workerSuccess = function(apiobj) {
* To be called by worker before it terminates succesfully
// update or remove status line
* @param {(Morebits.wiki.page|Morebits.wiki.api|string)} arg
if (apiobj && apiobj.getStatusElement) {
* This should be the `Morebits.wiki.page` or `Morebits.wiki.api` object used by worker
var statelem = apiobj.getStatusElement();
* (for the adjustment of status lines emitted by them).
* If no Morebits.wiki.* object is used (eg. you're using mw.Api() or something else), and
* `preserveIndividualStatusLines` option is on, give the page name (string) as argument.
*/
this.workerSuccess = function(arg) {
 
var createPageLink = function(pageName) {
var link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(pageName));
link.appendChild(document.createTextNode(pageName));
return link;
};
 
if (arg instanceof Morebits.wiki.api || arg instanceof Morebits.wiki.page) {
// update or remove status line
var statelem = arg.getStatusElement();
if (ctx.options.preserveIndividualStatusLines) {
if (apiobjarg.getPageName || apiobjarg.pageName || (apiobjarg.query && apiobjarg.query.title)) {
// we know the page title - display a relevant message
var pageName = apiobjarg.getPageName ? apiobjarg.getPageName() : arg.pageName || arg.query.title;
statelem.info(['completed (', createPageLink(pageName), ')']);
apiobj.pageName || apiobj.query.title;
var link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(pageName));
link.appendChild(document.createTextNode(pageName));
statelem.info(['completed (', link, ')']);
} else {
// we don't know the page title - just display a generic message
Line 3,890 ⟶ 4,744:
}
} else {
// remove the status line fromautomatically displayproduced by Morebits.wiki.*
statelem.unlink();
}
 
} else if (typeof arg === 'string' && ctx.options.preserveIndividualStatusLines) {
new Morebits.status(arg, ['done (', createPageLink(arg), ')']);
}
 
ctx.countFinishedSuccess++;
fnDoneOne(apiobj);
};
 
this.workerFailure = function(apiobj) {
fnDoneOne(apiobj);
};
 
Line 3,925 ⟶ 4,782:
// update overall status line
var total = ctx.pageList.length;
if (ctx.countFinished ===< total) {
ctx.statusElement.status(parseInt(100 * ctx.countFinished / total, 10) + '%');
 
// start a new chunk if we're close enough to the end of the previous chunk, and
// we haven't already started the next one
if (ctx.countFinished >= (ctx.countStarted - Math.max(ctx.options.chunkSize / 10, 2)) &&
Math.floor(ctx.countFinished / ctx.options.chunkSize) > ctx.currentChunkIndex) {
fnStartNewChunk();
}
} else if (ctx.countFinished === total) {
var statusString = 'Done (' + ctx.countFinishedSuccess +
'/' + ctx.countFinished + ' actions completed successfully)';
Line 3,938 ⟶ 4,804:
Morebits.wiki.removeCheckpoint();
ctx.running = false;
} else {
return;
// ctx.countFinished > total
}
// just for giggles! (well, serious debugging, actually)
 
// just for giggles! (well, serious debugging, actually)
if (ctx.countFinished > total) {
ctx.statusElement.warn('Done (overshot by ' + (ctx.countFinished - total) + ')');
Morebits.wiki.removeCheckpoint();
ctx.running = false;
return;
}
};
};
 
/** ********** Morebits.taskManager ****************
ctx.statusElement.status(parseInt(100 * ctx.countFinished / total, 10) + '%');
*
* Given a set of asynchronous functions to run along with their dependencies,
* Morebits.taskManager figures out an efficient sequence of running them so
* that multiple functions that don't depend on each other are triggered
* simultaneously. Where dependencies exist, it ensures that the dependency
* functions finish running before the dependent function runs. The values
* resolved by the dependencies are made available to the dependant as arguments.
*/
Morebits.taskManager = function() {
this.taskDependencyMap = new Map();
this.deferreds = new Map();
this.allDeferreds = []; // Hack: IE doesn't support Map.prototype.values
 
/**
// start a new chunk if we're close enough to the end of the previous chunk, and
* Register a task along with its dependencies (tasks which should have finished
// we haven't already started the next one
* execution before we can begin this one). Each task is a function that must return
if (ctx.countFinished >= (ctx.countStarted - Math.max(ctx.options.chunkSize / 10, 2)) &&
* a promise. The function will get the values resolved by the dependency functions
Math.floor(ctx.countFinished / ctx.options.chunkSize) > ctx.currentChunkIndex) {
* as arguments.
fnStartNewChunk();
* @param {function} func - a task
}
* @param {function[]} deps - its dependencies
*/
this.add = function(func, deps) {
this.taskDependencyMap.set(func, deps);
var deferred = $.Deferred();
this.deferreds.set(func, deferred);
this.allDeferreds.push(deferred);
};
};
 
/**
* Run all the tasks. Multiple tasks may be run at once.
*/
this.execute = function() {
var self = this; // proxy for `this` for use inside functions where `this` is something else
this.taskDependencyMap.forEach(function(deps, task) {
var dependencyPromisesArray = deps.map(function(dep) {
return self.deferreds.get(dep);
});
$.when.apply(null, dependencyPromisesArray).then(function() {
task.apply(null, arguments).then(function() {
self.deferreds.get(task).resolve.apply(null, arguments);
});
});
});
return $.when.apply(null, this.allDeferreds); // resolved when everything is done!
};
 
};
 
/**
Line 3,966 ⟶ 4,867:
* A simple draggable window
* now a wrapper for jQuery UI's dialog feature
* @requires {jquery.ui.dialog}
*/
 
Line 4,013 ⟶ 4,915:
 
var $widget = $(this.content).dialog('widget');
 
// add background gradient to titlebar
var $titlebar = $widget.find('.ui-dialog-titlebar');
var oldstyle = $titlebar.attr('style');
$titlebar.attr('style', (oldstyle ? oldstyle : '') + '; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAkCAMAAAB%2FqqA%2BAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAEhQTFRFr73ZobTPusjdsMHZp7nVwtDhzNbnwM3fu8jdq7vUt8nbxtDkw9DhpbfSvMrfssPZqLvVztbno7bRrr7W1d%2Fs1N7qydXk0NjpkW7Q%2BgAAADVJREFUeNoMwgESQCAAAMGLkEIi%2FP%2BnbnbpdB59app5Vdg0sXAoMZCpGoFbK6ciuy6FX4ABAEyoAef0BXOXAAAAAElFTkSuQmCC) !important;');
 
// delete the placeholder button (it's only there so the buttonpane gets created)
Line 4,169 ⟶ 5,066:
var button = document.createElement('button');
button.textContent = value.hasAttribute('value') ? value.getAttribute('value') : value.textContent ? value.textContent : 'Submit Query';
button.className = value.className || 'submitButtonProxy';
// here is an instance of cheap coding, probably a memory-usage hit in using a closure here
button.addEventListener('click', function() {
Line 4,206 ⟶ 5,104:
* @param {string} text Link's text content
* @param {string} wikiPage Link target
* @param {boolean} [prep=false] Set true to prepend rather than append
* @returns {Morebits.simpleWindow}
*/
addFooterLink: function(text, wikiPage, prep) {
var $footerlinks = $(this.content).dialog('widget').find('.morebits-dialog-footerlinks');
if (this.hasFooterLinks) {
var bullet = document.createElement('span');
bullet.textContent = ' \u2022 '; // U+2022 BULLET
if (prep) {
$footerlinks.append(bullet);
$footerlinks.prepend(bullet);
} else {
$footerlinks.append(bullet);
}
}
var link = document.createElement('a');
Line 4,220 ⟶ 5,123:
link.setAttribute('target', '_blank');
link.textContent = text;
if (prep) {
$footerlinks.append(link);
$footerlinks.prepend(link);
} else {
$footerlinks.append(link);
}
this.hasFooterLinks = true;
return this;
Line 4,253 ⟶ 5,160:
$('.morebits-dialog-buttons button').prop('disabled', !enabled);
};
 
 
// Twinkle blacklist was removed per consensus at http://en.wikipedia.org/wiki/Wikipedia:Administrators%27_noticeboard/Archive221#New_Twinkle_blacklist_proposal
 
 
 
Line 4,277 ⟶ 5,180:
window.Wikipedia = Morebits.wiki;
window.Status = Morebits.status;
window.QueryString = Morebits.queryString;
}