"मीडियाविकि:Gadget-morebits.js": अवतरणों में अंतर

Content deleted Content added
update
टैग: Reverted
reverted back
टैग: Manual revert
पंक्ति 1,707:
};
 
/* **************** Morebits.wiki.page **************** */
/**
* **************** Morebits.wiki.page ****************
* Use the MediaWiki API to load a page and optionally edit it, move it, etc.
* Uses the MediaWiki API to load a page and optionally edit it, move it, etc.
*
* Callers are not permitted to directly access the properties of this class!
* All property access is through the appropriate get___() or set___() method.
*
* Callers should set {@link Morebits.wiki.actionCompleted.notice} and {@link Morebits.wiki.actionCompleted.redirect}
* before the first call to {@link Morebits.wiki.page.load()}.
*
* Each of the callback functions takes one parameter, which is a
पंक्ति 1,722:
*
*
* HIGHLIGHTS:
* Call sequence for common operations (optional final user callbacks not shown):
*
* Constructor: Morebits.wiki.page(pageName, currentAction)
* - Edit current contents of a page (no edit conflict):
* pageName - the name of the page, prefixed by the namespace (if any)
* `.load(userTextEditCallback) -> ctx.loadApi.post() ->
* (for the current page, use mw.config.get('wgPageName'))
* ctx.loadApi.post.success() -> ctx.fnLoadSuccess() -> userTextEditCallback() ->
* currentAction - a string describing the action about to be undertaken (optional)
* .save() -> ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()`
*
* onSuccess and onFailure are callback functions called when the operation is a success or failure
* - Edit current contents of a page (with edit conflict):
* if enclosed in [brackets], it indicates that it is optional
* `.load(userTextEditCallback) -> ctx.loadApi.post() ->
* ctx.loadApi.post.success() -> ctx.fnLoadSuccess() -> userTextEditCallback() ->
* .save() -> ctx.saveApi.post() -> ctx.loadApi.post.success() ->
* ctx.fnSaveError() -> ctx.loadApi.post() -> ctx.loadApi.post.success() ->
* ctx.fnLoadSuccess() -> userTextEditCallback() -> .save() ->
* ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()`
*
* load(onSuccess, [onFailure]): Loads the text for the page
* - Append to a page (similar for prepend and newSection):
* `.append() -> ctx.loadApi.post() -> ctx.loadApi.post.success() ->
* ctx.fnLoadSuccess() -> ctx.fnAutoSave() -> .save() -> ctx.saveApi.post() ->
* ctx.loadApi.post.success() -> ctx.fnSaveSuccess()`
*
* getPageText(): returns a string containing the text of the page after a successful load()
* Notes:
* 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.
*
* save([onSuccess], [onFailure]): Saves the text set via setPageText() for the page.
* Must be preceded by calling load().
* Warning: Calling save() can result in additional calls to the previous load() callbacks to
* recover from edit conflicts!
* In this case, callers must make the same edit to the new pageText and reinvoke save().
* This behavior can be disabled with setMaxConflictRetries(0).
*
* append([onSuccess], [onFailure]): Adds the text provided via setAppendText() to the end of
* the page. Does not require calling load() first.
*
* prepend([onSuccess], [onFailure]): Adds the text provided via setPrependText() to the start
* of the page. Does not require calling load() first.
*
* move([onSuccess], [onFailure]): Moves a page to another title
*
* deletePage([onSuccess], [onFailure]): Deletes a page (for admins only)
*
* undeletePage([onSuccess], [onFailure]): Undeletes a page (for admins only)
*
* protect([onSuccess], [onFailure]): Protects a page
*
* getPageName(): returns a string containing the name of the loaded page, including the namespace
*
* setPageText(pageText) sets the updated page text that will be saved when save() is called
*
* setAppendText(appendText) sets the text that will be appended to the page when append() is called
*
* setPrependText(prependText) sets the text that will be prepended to the page when prepend() is called
*
* setCallbackParameters(callbackParameters)
* callbackParameters - an object for use in a callback function
*
* getCallbackParameters(): returns the object previous set by setCallbackParameters()
*
* Callback notes: callbackParameters is for use by the caller only. The parameters
* allow a caller to pass the proper context into its callback function.
* Callers must ensure that any changes to the callbackParameters object
* within a load() callback still permit a proper re-entry into the
* load() callback if an edit conflict is detected upon calling save().
*
* getStatusElement(): returns the Status element created by the constructor
*
* exists(): returns true if the page existed on the wiki when it was last loaded
*
* getCurrentID(): returns a string containing the current revision ID of the page
*
* lookupCreation(onSuccess): Retrieves the username and timestamp of page creation
* onSuccess - callback function which is called when the username and timestamp
* are found within the callback.
* The username can be retrieved using the getCreator() function;
* the timestamp can be retrieved using the getCreationTimestamp() function
*
* getCreator(): returns the user who created the page following lookupCreation()
*
* getCreationTimestamp(): returns an ISOString timestamp of page creation following lookupCreation()
*
* @memberof Morebits.wiki
* @class
* @param {string} pageName - The name of the page, prefixed by the namespace (if any).
* For the current page, use `mw.config.get('wgPageName')`.
* @param {string|Morebits.status} [status] - A string describing the action about to be undertaken,
* or a Morebits.status object
*/
Morebits.wiki.page = function(pageName, status) {
 
/**
if (!status) {
* Call sequence for common operations (optional final user callbacks not shown):
status = msg('opening-page', pageName, 'Opening page "' + pageName + '"');
*
* Edit current contents of a page (no edit conflict):
* .load(userTextEditCallback) -> ctx.loadApi.post() -> ctx.loadApi.post.success() ->
* ctx.fnLoadSuccess() -> userTextEditCallback() -> .save() ->
* ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()
*
* Edit current contents of a page (with edit conflict):
* .load(userTextEditCallback) -> ctx.loadApi.post() -> ctx.loadApi.post.success() ->
* ctx.fnLoadSuccess() -> userTextEditCallback() -> .save() ->
* ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveError() ->
* ctx.loadApi.post() -> ctx.loadApi.post.success() ->
* ctx.fnLoadSuccess() -> userTextEditCallback() -> .save() ->
* ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()
*
* Append to a page (similar for prepend):
* .append() -> ctx.loadApi.post() -> ctx.loadApi.post.success() ->
* ctx.fnLoadSuccess() -> ctx.fnAutoSave() -> .save() ->
* ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()
*
* Notes:
* 1. All functions following Morebits.wiki.api.post() are invoked asynchronously
* from the jQuery AJAX library.
* 2. The sequence for append/prepend could be slightly shortened, but it would require
* significant duplication of code for little benefit.
*/
 
/**
* @constructor
* @param {string} pageName The name of the page, prefixed by the namespace (if any)
* For the current page, use mw.config.get('wgPageName')
* @param {string} [currentAction] A string describing the action about to be undertaken (optional)
*/
Morebits.wiki.page = function(pageName, currentAction) {
 
if (!currentAction) {
currentAction = '"' + pageName + '" पृष्ठ खोला जा रहा';
}
 
/**
* Private context variables.
*
* This context is not visible to the outside, thus all the data here
* must be accessed via getter and setter functions.
*
* @private
*/
var ctx = {
Line 1,774 ⟶ 1,845:
pageExists: false,
editSummary: null,
changeTags: null,
testActions: null, // array if any valid actions
callbackParameters: null,
statusElement: status instanceof Morebits.status ? status : new Morebits.status(statuscurrentAction),
 
// - edit
Line 1,784 ⟶ 1,853:
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,793 ⟶ 1,860:
maxRetries: 2,
followRedirect: false,
followCrossNsRedirect: true,
watchlistOption: 'nochange',
watchlistExpiry: null,
creator: null,
timestamp: null,
Line 1,812 ⟶ 1,877:
protectMove: null,
protectCreate: null,
protectCascade: nullfalse,
 
// - creation lookup
Line 1,825 ⟶ 1,890:
loadTime: null,
lastEditTime: null,
pageID: null,
contentModel: null,
revertCurID: null,
revertUser: null,
watched: false,
fullyProtected: false,
suppressProtectWarning: false,
Line 1,841 ⟶ 1,903:
onSaveFailure: null,
onLookupCreationSuccess: null,
onLookupCreationFailure: null,
onMoveSuccess: null,
onMoveFailure: null,
Line 1,860 ⟶ 1,921:
moveApi: null,
moveProcessApi: null,
patrolApi: null,
patrolProcessApi: null,
triageApi: null,
triageProcessListApi: null,
triageProcessApi: null,
deleteApi: null,
deleteProcessApi: null,
Line 1,878 ⟶ 1,934:
 
/**
* Loads the text for the page.
* @param {Function} onSuccess - callback function which is called when the load has succeeded
*
* @param {Function} onSuccess[onFailure] - Callbackcallback function which is called when the load hasfails succeeded.(optional)
* @param {Function} [onFailure] - Callback function which is called when the load fails.
*/
this.load = function(onSuccess, onFailure) {
Line 1,895 ⟶ 1,950:
 
ctx.loadQuery = {
action: 'query',
prop: 'info|revisions',
inprop: 'watched',
Line 1,922 ⟶ 1,977:
}
if (Morebits.userIsSysop) {
ctx.loadQuery.inprop += '|protection';
}
 
ctx.loadApi = new Morebits.wiki.api(msg('retrieving-page',पृष्ठ 'Retrievingप्राप्त किया जा pageरहा...'), ctx.loadQuery, fnLoadSuccess, ctx.statusElement, ctx.onLoadFailure);
ctx.loadApi.setParent(this);
ctx.loadApi.post();
Line 1,931 ⟶ 1,986:
 
/**
* Saves the text for the page to Wikipedia.
* Must be preceded by successfully calling `load()`.
*
* Warning: Calling `save()` can result in additional calls to the previous load() callbacks
* previous `load()` callbacks to recover from edit conflicts! In this
* In this case, callers must make the same edit to the new pageText and reinvoke save().
* re-invoke `save()`. This behavior can be disabled with setMaxConflictRetries(0).
* @param {Function} [onSuccess] - callback function which is called when the save has
* `setMaxConflictRetries(0)`.
* succeeded (optional)
*
* @param {Function} [onSuccessonFailure] - Callbackcallback function which is called when the save has succeeded.fails
* (optional)
* @param {Function} [onFailure] - Callback function which is called when the save fails.
*/
this.save = function(onSuccess, onFailure) {
Line 1,947 ⟶ 2,002:
ctx.onSaveFailure = onFailure || emptyFunction;
 
// are we getting our editingedit token from mw.user.tokens?
var canUseMwUserToken = fnCanUseMwUserToken('edit');
 
Line 1,956 ⟶ 2,011:
}
if (!ctx.editSummary) {
ctx.statusElement.error('Internal error: edit summary not set before save!');
// new section mode allows (nay, encourages) using the
ctx.onSaveFailure(this);
// title as the edit summary, but the query needs
return;
// editSummary to be undefined or '', not null
if (ctx.editMode === 'new' && ctx.newSectionTitle) {
ctx.editSummary = '';
} else {
ctx.statusElement.error('Internal error: edit summary not set before save!');
ctx.onSaveFailure(this);
return;
}
}
 
// shouldn't happen if canUseMwUserToken === true
if (ctx.fullyProtected && !ctx.suppressProtectWarning &&
!confirm('आप एक पूर्ण सुरक्षित पृष्ठ पर संपादन करने वाले हैं "' + ctx.pageName +
!confirm(
(ctx.fullyProtected === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + ctx.fullyProtected + ')') +
'. \n\nसंपादन जारी रखने के लिए ओके करें, रद्द करने के लिए कैसिल करें।')) {
? msg('protected-indef-edit-warning', ctx.pageName,
ctx.statusElement.error('पूर्ण सुरक्षित पृष्ठ पर संपादन छोड़ दिया गया');
'You are about to make an edit to the fully protected page "' + ctx.pageName + '" (protected indefinitely). \n\nClick OK to proceed with the edit, or Cancel to skip this edit.'
)
: msg('protected-edit-warning', ctx.pageName, ctx.fullyProtected,
'You are about to make an edit to the fully protected page "' + ctx.pageName +
'" (protection expiring ' + new Morebits.date(ctx.fullyProtected).calendar('utc') + ' (UTC)). \n\nClick OK to proceed with the edit, or Cancel to skip this edit.'
)
)
) {
ctx.statusElement.error(msg('protected-aborted', 'Edit to fully protected page was aborted.'));
ctx.onSaveFailure(this);
return;
Line 1,993 ⟶ 2,033:
summary: ctx.editSummary,
token: canUseMwUserToken ? mw.user.tokens.get('csrfToken') : ctx.csrfToken,
watchlist: ctx.watchlistOption,
format: 'json'
};
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
 
if (typeof ctx.pageSection === 'number') {
Line 2,015 ⟶ 2,047:
}
 
// Set bot edit attribute. If this parameterparamter is present with any value, it is interpreted as true
if (ctx.botEdit) {
query.bot = true;
Line 2,022 ⟶ 2,054:
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 2,055 ⟶ 2,067:
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 2,072 ⟶ 2,084:
}
 
ctx.saveApi = new Morebits.wiki.api(msg('saving-page',पृष्ठ 'Savingसहेजा जा रहा pageहै...'), query, fnSaveSuccess, ctx.statusElement, fnSaveError);
ctx.saveApi.setParent(this);
ctx.saveApi.post();
Line 2,078 ⟶ 2,090:
 
/**
* Adds the text provided via `setAppendText()` to the end of the page.
* page. Does not require calling `load()` first, unless a watchlist.
* @param {Function} [onSuccess] - callback function which is called when the method has succeeded (optional)
* expiry is used.
* @param {Function} [onFailure] - callback function which is called when the method fails (optional)
*
* @param {Function} [onSuccess] - Callback function which is called when the method has succeeded.
* @param {Function} [onFailure] - Callback function which is called when the method fails.
*/
this.append = function(onSuccess, onFailure) {
Line 2,098 ⟶ 2,108:
 
/**
* Adds the text provided via `setPrependText()` to the start of the page.
* page. Does not require calling `load()` first, unless a watchlist.
* @param {Function} [onSuccess] - callback function which is called when the method has succeeded (optional)
* expiry is used.
* @param {Function} [onFailure] - callback function which is called when the method fails (optional)
*
* @param {Function} [onSuccess] - Callback function which is called when the method has succeeded.
* @param {Function} [onFailure] - Callback function which is called when the method fails.
*/
this.prepend = function(onSuccess, onFailure) {
Line 2,117 ⟶ 2,125:
};
 
/** @returns {string} string containing the name of the loaded page, including the namespace */
/**
* Creates a new section with the text provided by `setNewSectionText()`
* 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, unless a watchlist expiry
* is used.
*
* @param {Function} [onSuccess] - Callback function which is called when the method has succeeded.
* @param {Function} [onFailure] - Callback function which is called when the method fails.
*/
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} The name of the loaded page, including the namespace */
this.getPageName = function() {
return ctx.pageName;
};
 
/** @returns {string} Thestring containing the text of the page after a successful load() */
this.getPageText = function() {
return ctx.pageText;
};
 
/** @param {string} pageText - Updatedupdated page text that will be saved when `save()` is called */
this.setPageText = function(pageText) {
ctx.editMode = 'all';
Line 2,156 ⟶ 2,141:
};
 
/** @param {string} appendText - Texttext that will be appended to the page when `append()` is called */
this.setAppendText = function(appendText) {
ctx.editMode = 'append';
Line 2,162 ⟶ 2,147:
};
 
/** @param {string} prependText - Texttext 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 2,186 ⟶ 2,156:
 
// Edit-related setter methods:
/** @param {string} summary - text of the edit summary that will be used when save() is called */
/**
* Set the edit summary that will be used when `save()` is called.
* Unnecessary if editMode is 'new' and newSectionTitle is provided.
*
* @param {string} summary
*/
this.setEditSummary = function(summary) {
ctx.editSummary = summary;
Line 2,197 ⟶ 2,162:
 
/**
* @param {string} createOption - can take the following four values:
* Set any custom tag(s) to be applied to the API action.
* `recreate` - create the page if it does not exist, or edit it if it exists.
* A number of actions don't support it, most notably watch, review,
* `createonly` - create the page if it does not exist, but return an error if it
* and stabilize ({@link https://phabricator.wikimedia.org/T247721|T247721}), and
* already exists.
* pagetriageaction ({@link https://phabricator.wikimedia.org/T252980|T252980}).
* `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
* @param {string|string[]} tags - String or array of tag(s).
* between retrieving the edit token and saving the edit (default)
*/
this.setChangeTags = function(tags) {
ctx.changeTags = tags;
};
 
 
/**
* @param {string} [createOption=null] - Can take the following four values:
* - recreate: create the page if it does not exist, or edit it if it exists.
* - 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 loading the page and saving the edit (default).
*
*/
Line 2,223 ⟶ 2,175:
};
 
/** @param {boolean} minorEdit - Setset true to mark the edit as a minor edit. */
this.setMinorEdit = function(minorEdit) {
ctx.minorEdit = minorEdit;
};
 
/** @param {boolean} botEdit - Setset true to mark the edit as a bot edit */
this.setBotEdit = function(botEdit) {
ctx.botEdit = botEdit;
Line 2,234 ⟶ 2,186:
 
/**
* @param {number} pageSection - Integerinteger specifying the section number to load or save.
* If specified as `null`, the entire page will be retrieved.
*/
Line 2,242 ⟶ 2,194:
 
/**
* @param {number} maxConflictRetries - Numbernumber of retries for save errors involving an edit conflict or
* loss of edit token. Default: 2.
*/
this.setMaxConflictRetries = function(maxConflictRetries) {
Line 2,250 ⟶ 2,202:
 
/**
* @param {number} maxRetries - Numbernumber of retries for save errors not involving an edit conflict or
* loss of edit token. Default: 2.
*/
this.setMaxRetries = function(maxRetries) {
Line 2,258 ⟶ 2,210:
 
/**
* @param {boolean} watchlistOption
* Set whether and how to watch the page, including setting an expiry.
* 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)
* @param {boolean|string|Morebits.date|Date} [watchlistOption=false] -
* Basically a mix of MW API and Twinkley options available pre-expiry:
* - `true`|`'yes'`|`'watch'`: page will be added to the user's
* watchlist when the action is called. Defaults to an indefinite
* watch unless `watchlistExpiry` is provided.
* - `false`|`'no'`|`'nochange'`: watchlist status of the page (including expiry) will not be changed.
* - `'default'`|`'preferences'`: watchlist status of the page will be
* set based on the user's preference settings when the action is
* called. Defaults to an indefinite watch unless `watchlistExpiry` is
* provided.
* - `'unwatch'`: explicitly unwatch the page.
* - Any other `string` or `number`, or a `Morebits.date` or `Date`
* object: watch page until the specified time, deferring to
* `watchlistExpiry` if provided.
* @param {string|number|Morebits.date|Date} [watchlistExpiry=infinity] -
* A date-like string or number, or a date object. If a string or number,
* can be relative (2 weeks) or other similarly date-like (i.e. NOT "potato"):
* ISO 8601: 2038-01-09T03:14:07Z
* MediaWiki: 20380109031407
* UNIX: 2147483647
* SQL: 2038-01-09 03:14:07
* Can also be `infinity` or infinity-like (`infinite`, `indefinite`, and `never`).
* See {@link https://phabricator.wikimedia.org/source/mediawiki-libs-Timestamp/browse/master/src/ConvertibleTimestamp.php;4e53b859a9580c55958078f46dd4f3a44d0fcaa0$57-109?as=source&blame=off}
*/
this.setWatchlist = function(watchlistOption, watchlistExpiry) {
if (watchlistOption instanceof Morebits.date || watchlistOption instanceof Date) {
ctx.watchlistOption = watchlistOption.toISOString()'watch';
} else {
ctx.watchlistOption = 'nochange';
if (typeof watchlistExpiry === 'undefined') {
watchlistExpiry = 'infinity';
} else if (watchlistExpiry instanceof Morebits.date || watchlistExpiry instanceof Date) {
watchlistExpiry = watchlistExpiry.toISOString();
}
 
switch (watchlistOption) {
case 'nochange':
case 'no':
case false:
case undefined:
ctx.watchlistOption = 'nochange';
// The MW API allows for changing expiry with nochange (as "nochange" refers to the binary status),
// but by keeping this null it will default to any existing expiry, ensure there is actually "no change."
ctx.watchlistExpiry = null;
break;
case 'unwatch':
// expiry unimportant
ctx.watchlistOption = 'unwatch';
break;
case 'preferences':
case 'default':
ctx.watchlistOption = 'preferences';
// The API allows an expiry here, but there is as of yet (T265716)
// no expiry preference option, so it's a bit devoid of context.
ctx.watchlistExpiry = watchlistExpiry;
break;
case 'watch':
case 'yes':
case true:
ctx.watchlistOption = 'watch';
ctx.watchlistExpiry = watchlistExpiry;
break;
default: // Not really a "default" per se but catches "any other string"
ctx.watchlistOption = 'watch';
ctx.watchlistExpiry = watchlistOption;
break;
}
};
 
/**
* Set a watchlist expiry. setWatchlist can mostly handle this by
* itself, so this is here largely for completeness and compatibility
* with the full suite of options.
*
* @param {string|number|Morebits.date|Date} [watchlistExpiry=infinity] -
* A date-like string or number, or a date object. If a string or number,
* can be relative (2 weeks) or other similarly date-like (i.e. NOT "potato"):
* ISO 8601: 2038-01-09T03:14:07Z
* MediaWiki: 20380109031407
* UNIX: 2147483647
* SQL: 2038-01-09 03:14:07
* Can also be `infinity` or infinity-like (`infinite`, `indefinite`, and `never`).
* See {@link https://phabricator.wikimedia.org/source/mediawiki-libs-Timestamp/browse/master/src/ConvertibleTimestamp.php;4e53b859a9580c55958078f46dd4f3a44d0fcaa0$57-109?as=source&blame=off}
*/
this.setWatchlistExpiry = function(watchlistExpiry) {
if (typeof watchlistExpiry === 'undefined') {
watchlistExpiry = 'infinity';
} else if (watchlistExpiry instanceof Morebits.date || watchlistExpiry instanceof Date) {
watchlistExpiry = watchlistExpiry.toISOString();
}
ctx.watchlistExpiry = watchlistExpiry;
};
 
/**
* @param {boolean} watchlistOption
* @deprecated As of December 2020, use setWatchlist.
* True - page watchlist status will be set based on the user's
* @param {boolean} [watchlistOption=false] -
* preference settings when save() is called.
* - `True`: page watchlist status will be set based on the user's
* False - watchlist status of the page will not be changed (default)
* preference settings when `save()` is called.
* - `False`: watchlist status of the page will not be changed.
*
* Watchlist notes:
* 1. The MediaWiki API value of 'unwatch', which explicitly removes the page from the
* the page from the user's watchlist, is not used.
* 2. If both `setWatchlist()` and `setWatchlistFromPreferences()` are called,
* called, the last call takes priority.
* 3. Twinkle modules should use the appropriate preference to set the watchlist options.
* 4. Most Twinkle modules use `setWatchlist()`. `setWatchlistFromPreferences()`
* setWatchlistFromPreferences() is only needed for the few Twinkle watchlist preferences that
* that accept a string value of `'default`'.
*/
this.setWatchlistFromPreferences = function(watchlistOption) {
console.warn('NOTE: Morebits.wiki.page.setWatchlistFromPreferences was deprecated December 2020, please use setWatchlist'); // eslint-disable-line no-console
if (watchlistOption) {
ctx.watchlistOption = 'preferences';
Line 2,379 ⟶ 2,247:
 
/**
* @param {boolean} [followRedirect=false] -
* - ` true`: - a maximum of one redirect will be followed. In the event
* In the event of a redirect, a message is displayed to the user and the redirect
* the redirect target can be retrieved with getPageName().
* - ` false`: (default)- the requested pageName will be used without regard to any redirect (default).
* @param {boolean} [followCrossNsRedirect=true] - 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,394 ⟶ 2,259:
}
ctx.followRedirect = followRedirect;
ctx.followCrossNsRedirect = typeof followCrossNsRedirect !== 'undefined' ? followCrossNsRedirect : ctx.followCrossNsRedirect;
};
 
// lookup-creation setter function
/**
* @param {boolean} flag - Ifif set true, the author and timestamp of the first non-redirect
* 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
* 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
* redirects, the original creation is retrieved.
* as non-redirects.
* 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) {
Line 2,437 ⟶ 2,300:
 
// Protect-related setter functions
/**
* @param {string} level - The right required for the specific action
* e.g. autoconfirmed, sysop, templateeditor, extendedconfirmed
* (enWiki-only).
* @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,468 ⟶ 2,325:
};
 
/** @returns {string} Thestring containing the current revision ID of the page */
this.getCurrentID = function() {
return ctx.revertCurID;
};
 
/** @returns {string} Lastlast 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,486 ⟶ 2,338:
 
/**
* Define`callbackParameters` - an object for use in a callback function.
*
* `Callback notes: callbackParameters` is for use by the caller only. The parameters
* allow a caller to pass the proper context into its callback function.
* function. Callers must ensure that any changes to the callbackParameters object
* callbackParameters object within a `load()` callback still permit a proper re-entry into the
* proper re-entry into the `load()` callback if an edit conflict is detected upon calling save().
* detected upon calling `save()`.
*
* @param {object} callbackParameters
*/
this.setCallbackParameters = function(callbackParameters) {
Line 2,502 ⟶ 2,351:
 
/**
* @returns {object} - Thethe object previouslyprevious set by `setCallbackParameters()`.
*/
this.getCallbackParameters = function() {
Line 2,509 ⟶ 2,358:
 
/**
* @paramreturns {Morebits.status} statusElementStatus element created by the constructor
*/
this.setStatusElement = function(statusElement) {
ctx.statusElement = statusElement;
};
 
/**
* @returns {Morebits.status} Status element created by the constructor.
*/
this.getStatusElement = function() {
Line 2,522 ⟶ 2,364:
};
 
 
/**
* @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' };
};
 
/**
* @returns {boolean} Truetrue if the page existed on the wiki when it was last loaded.
*/
this.exists = function() {
Line 2,539 ⟶ 2,377:
 
/**
* @returns {string} PageISO ID8601 oftimestamp at which the page loaded.was 0last if the page doesn'tloaded
* exist.
*/
this.getPageID = function() {
return ctx.pageID;
};
 
/**
* @returns {string} - Content model of the page. Possible values
* include (but may not be limited to): `wikitext`, `javascript`,
* `css`, `json`, `Scribunto`, `sanitized-css`, `MassMessageListContent`.
* Also gettable via `mw.config.get('wgPageContentModel')`.
*/
this.getContentModel = function() {
return ctx.contentModel;
};
 
/**
* @returns {boolean|string} - Watched status of the page. Boolean
* unless it's being watched temporarily, in which case returns the
* expiry string.
*/
this.getWatched = function () {
return ctx.watched;
};
 
/**
* @returns {string} ISO 8601 timestamp at which the page was last loaded.
*/
this.getLoadTime = function() {
Line 2,573 ⟶ 2,384:
 
/**
* @returns {string} Thethe user who created the page following `lookupCreation()`.
*/
this.getCreator = function() {
Line 2,580 ⟶ 2,391:
 
/**
* @returns {string} Thethe ISOString timestamp of page creation following `lookupCreation()`.
*/
this.getCreationTimestamp = function() {
return ctx.timestamp;
};
 
/** @returns {boolean} whether or not you can edit the page */
this.canEdit = function() {
return !!ctx.testActions && ctx.testActions.indexOf('edit') !== -1;
};
 
/**
* Retrieves the username of the user who created the page as well as
* the timestamp of creation. The username can be retrieved using the
* @param {Function} onSuccess - callback function (required) which is
* `getCreator()` function; the timestamp can be retrieved using the
* called when the username and timestamp are found within the callback.
* `getCreationTimestamp()` function.
* The username can be retrieved using the getCreator() function;
* Prior to June 2019 known as `lookupCreator()`.
* the timestamp can be retrieved using the getCreationTimestamp() function
*
* @param {Function} onSuccess - Callback function to be called when
* the username and timestamp are found within the callback.
* @param {Function} [onFailure] - Callback function to be called when
* the lookup fails
*/
this.lookupCreation = function(onSuccess, onFailure) {
ctx.onLookupCreationSuccess = onSuccess;
ctx.onLookupCreationFailure = onFailure || emptyFunction;
if (!onSuccess) {
ctx.statusElement.error('Internal error: no onSuccess callback provided to lookupCreation()!');
ctx.onLookupCreationFailure(this);
return;
}
ctx.onLookupCreationSuccess = onSuccess;
 
var query = {
'action': 'query',
'prop': 'revisions',
'titles': ctx.pageName,
'rvlimit': 1,
'rvprop': 'user|timestamp',
'rvdir': 'newer',
format: 'json'
};
 
Line 2,636 ⟶ 2,435:
}
 
ctx.lookupCreationApi = new Morebits.wiki.api(msg('getting-creator',पृष्ठ 'Retrievingनिर्माता pageकी creationजानकारी informationप्राप्त की जा रही'), query, fnLookupCreationSuccess, ctx.statusElement, ctx.onLookupCreationFailure);
ctx.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
};
/**
* @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);
};
 
/**
* Revertsmarks athe page toas `revertOldID`patrolled, setif by `setOldID`.possible
*/
this.patrol = function() {
* @param {Function} [onSuccess] - Callback function to run on success.
// There's no patrol link on page, so we can't patrol
* @param {Function} [onFailure] - Callback function to run on failure.
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('पृष्ठ को जाँचा हुआ चिह्नित किया जा रहा');
 
var wikipedia_api = new Morebits.wiki.api('कार्य प्रगति पर है...', {
action: 'patrol',
rcid: rcid,
token: mw.user.tokens.get('patrolToken')
}, null, patrolstat);
 
// We don't really care about the response
wikipedia_api.post();
}
};
 
/**
* Reverts a page to revertOldID
* @param {Function} [onSuccess] - callback function to run on success (optional)
* @param {Function} [onFailure] - callback function to run on failure (optional)
*/
this.revert = function(onSuccess, onFailure) {
Line 2,662 ⟶ 2,496:
 
/**
* Moves a page to another title.
* @param {Function} [onSuccess] - callback function to run on success (optional)
*
* @param {Function} [onSuccessonFailure] - Callbackcallback function to run on success.failure (optional)
* @param {Function} [onFailure] - Callback function to run on failure.
*/
this.move = function(onSuccess, onFailure) {
Line 2,671 ⟶ 2,504:
ctx.onMoveFailure = onFailure || emptyFunction;
 
if (!fnPreflightChecks.call(this, 'move', ctx.onMoveFailure)editSummary) {
ctx.statusElement.error('Internal error: move reason not set before move (use setEditSummary function)!');
return; // abort
ctx.onMoveFailure(this);
return;
}
 
if (!ctx.moveDestination) {
ctx.statusElement.error('Internal error: destination page name was not set before move!');
Line 2,681 ⟶ 2,515:
}
 
var query = {
if (fnCanUseMwUserToken('move')) {
action: 'query',
fnProcessMove.call(this, this);
prop: 'info',
} else {
varintoken: query = fnNeedTokenInfoQuery('move');,
titles: ctx.pageName
 
};
ctx.moveApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
if (ctx.followRedirect) {
ctx.moveApi.setParent(this);
query.redirects = ''; // follow all redirects
ctx.moveApi.post();
}
if (Morebits.userIsSysop) {
};
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 {@link 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;
}
 
ctx.moveApi = new Morebits.wiki.api('स्थानान्तरण टोकन प्राप्त किया जा रहा...', query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
// If a link is present, don't need to check if it's patrolled
ctx.moveApi.setParent(this);
if ($('.patrollink').length) {
ctx.moveApi.post();
var patrolhref = $('.patrollink a').attr('href');
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,
format: 'json'
};
 
ctx.patrolApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), patrolQuery, fnProcessPatrol);
ctx.patrolApi.setParent(this);
ctx.patrolApi.post();
}
};
 
/**
* Marks the page as reviewed by the PageTriage extension.
*
* 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 {@link Morebits.wiki.api} is probably preferable.
*
* Will first check if the page is queued via
* {@link Morebits.wiki.page~fnProcessTriageList|fnProcessTriageList}.
*
* No error handling since we don't actually care about the errors.
*
* @see {@link https://www.mediawiki.org/wiki/Extension:PageTriage} Referred to as "review" on-wiki.
*/
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');
fnProcessTriageList(this, this);
} else {
var query = fnNeedTokenInfoQuery('triage');
 
ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList);
ctx.triageApi.setParent(this);
ctx.triageApi.post();
}
}
};
 
// |delete| is a reserved word in some flavours of JS
/**
* Deletes a page (for admins only).
* @param {Function} [onSuccess] - callback function to run on success (optional)
*
* @param {Function} [onSuccessonFailure] - Callbackcallback function to run on success.failure (optional)
* @param {Function} [onFailure] - Callback function to run on failure.
*/
this.deletePage = function(onSuccess, onFailure) {
Line 2,782 ⟶ 2,543:
ctx.onDeleteFailure = onFailure || emptyFunction;
 
// if a non-admin tries to do this, don't bother
if (!fnPreflightChecks.call(this, 'delete', ctx.onDeleteFailure)) {
if (!Morebits.userIsSysop) {
return; // abort
ctx.statusElement.error('पृष्ठ हटाया नहीं जा सकता: यह कार्य केवल प्रबंधक ही कर सकते हैं');
ctx.onDeleteFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error('Internal error: delete reason not set before delete (use setEditSummary function)!');
ctx.onDeleteFailure(this);
return;
}
 
Line 2,789 ⟶ 2,558:
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(msg('getting-token',हटाने 'retrievingहेतु टोकन प्राप्त किया जा tokenरहा...'), query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure);
ctx.deleteApi.setParent(this);
ctx.deleteApi.post();
Line 2,798 ⟶ 2,576:
 
/**
* Undeletes a page (for admins only).
* @param {Function} [onSuccess] - callback function to run on success (optional)
*
* @param {Function} [onSuccessonFailure] - Callbackcallback function to run on success.failure (optional)
* @param {Function} [onFailure] - Callback function to run on failure.
*/
this.undeletePage = function(onSuccess, onFailure) {
Line 2,807 ⟶ 2,584:
ctx.onUndeleteFailure = onFailure || emptyFunction;
 
// if a non-admin tries to do this, don't bother
if (!fnPreflightChecks.call(this, 'undelete', ctx.onUndeleteFailure)) {
if (!Morebits.userIsSysop) {
return; // abort
ctx.statusElement.error('पृष्ठ को अनडिलीट नहीं किया जा सकता: केवल प्रबंधक ही यह कार्य कर सकते हैं');
ctx.onUndeleteFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error('Internal error: undelete reason not set before undelete (use setEditSummary function)!');
ctx.onUndeleteFailure(this);
return;
}
 
Line 2,814 ⟶ 2,599:
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(msg('getting-token',अनडिलीट 'retrievingटोकन प्राप्त किया जा tokenरहा...'), query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure);
ctx.undeleteApi.setParent(this);
ctx.undeleteApi.post();
Line 2,823 ⟶ 2,614:
 
/**
* Protects a page (for admins only).
* @param {Function} [onSuccess] - callback function to run on success (optional)
*
* @param {Function} [onSuccessonFailure] - Callbackcallback function to run on success.failure (optional)
* @param {Function} [onFailure] - Callback function to run on failure.
*/
this.protect = function(onSuccess, onFailure) {
Line 2,832 ⟶ 2,622:
ctx.onProtectFailure = onFailure || emptyFunction;
 
// if a non-admin tries to do this, don't bother
if (!fnPreflightChecks.call(this, 'protect', ctx.onProtectFailure)) {
if (!Morebits.userIsSysop) {
return; // abort
ctx.statusElement.error('पृष्ठ सुरक्षित नहीं किया जा सकता: केवल प्रबंधक ही ऐसा कर सकते');
ctx.onProtectFailure(this);
return;
}
 
if (!ctx.protectEdit && !ctx.protectMove && !ctx.protectCreate) {
ctx.statusElement.error('Internal error: you must set edit and/or move and/or create protection before calling protect()!');
ctx.onProtectFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error('Internal error: protection reason not set before protect (use setEditSummary function)!');
ctx.onProtectFailure(this);
return;
}
 
// because of the way MW API interprets protection levels (absolute, not
// (absolute, not differential), we always need to request protection levels from the server
var query = {
// protection levels from the server
action: 'query',
var query = fnNeedTokenInfoQuery('protect');
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(msg('getting-token',सुरक्षित 'retrievingकरने हेतु टोकन प्राप्त किया जा tokenरहा...'), query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure);
ctx.protectApi.setParent(this);
ctx.protectApi.post();
Line 2,853 ⟶ 2,659:
 
/**
* Apply FlaggedRevs protection-style settings. Only works on wikis where
* theonly extensionworks iswhere installed (`$wgFlaggedRevsProtection = true` (i.e. where FlaggedRevs
* i.e. where FlaggedRevs settings appear on the wiki's "protect" tab).
* @param {function} [onSuccess]
*
* @param {function} [onFailure]
* @see {@link https://www.mediawiki.org/wiki/Extension:FlaggedRevs}
* Referred to as "pending changes" on-wiki.
*
* @param {Function} [onSuccess]
* @param {Function} [onFailure]
*/
this.stabilize = function(onSuccess, onFailure) {
Line 2,867 ⟶ 2,669:
ctx.onStabilizeFailure = onFailure || emptyFunction;
 
// if a non-admin tries to do this, don't bother
if (!fnPreflightChecks.call(this, 'FlaggedRevs', ctx.onStabilizeFailure)) {
if (!Morebits.userIsSysop) {
return; // abort
ctx.statusElement.error('Cannot apply FlaggedRevs settings: only admins can do that');
ctx.onStabilizeFailure(this);
return;
}
 
if (!ctx.flaggedRevs) {
ctx.statusElement.error('Internal error: you must set flaggedRevs before calling stabilize()!');
ctx.onStabilizeFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error('Internal error: reason not set before calling stabilize() (use setEditSummary function)!');
ctx.onStabilizeFailure(this);
return;
}
 
var query = {
if (fnCanUseMwUserToken('stabilize')) {
action: 'query',
fnProcessStabilize.call(this, this);
prop: 'info|flagged',
} else {
intoken: 'edit',
var query = fnNeedTokenInfoQuery('stabilize');
titles: ctx.pageName
};
if (ctx.followRedirect) {
query.redirects = ''; // follow all redirects
}
 
ctx.stabilizeApi = new Morebits.wiki.api(msg('getting-token',retrieving 'retrievingstabilize token...'), query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure);
ctx.stabilizeApi.setParent(this);
ctx.stabilizeApi.post();
}
};
 
Line 2,894 ⟶ 2,707:
 
/**
* Determines whether we can save an API call by using the csrfedit token sent with the page
* sent with the page HTML, or whether we need to ask the server for more info (e.g. protection expiry).
* more info (e.g. protection or watchlist expiry).
*
* Currently only used for `append`, `prepend`, `newSection`,and `move`,deletePage.
* `stabilize`, `deletePage`, and `undeletePage`. Not used 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) {
// API-based redirect resolution only works for action=query and
action = typeof action !== 'undefined' ? action : 'edit'; // IE doesn't support default parameters
// action=edit in append/prepend modes (and section=new, but we don't
 
// really support that)
// If a watchlist expiry is set, we must always load the page
if (ctx.followRedirect && (action !== 'edit' ||
// to avoid overwriting indefinite protection. Of course, not
(ctx.editMode !== 'append' && ctx.editMode !== 'prepend'))) {
// needed if setting indefinite watching!
if (ctx.watchlistExpiry && !Morebits.string.isInfinity(ctx.watchlistExpiry)) {
return false;
}
 
// API-based redirect resolution only works for action=query and
// action=edit in append/prepend/new modes
if (ctx.followRedirect) {
if (!ctx.followCrossNsRedirect) {
return false; // must load the page to check for cross namespace redirects
}
if (action !== 'edit' || (ctx.editMode === 'all' || ctx.editMode === 'revert')) {
return false;
}
}
 
// do we need to fetch the edit protection expiry?
if (Morebits.userIsSysop && !ctx.suppressProtectWarning) {
// poor man's normalisation
if (new mw.Title(Morebits.pageNameNorm).getPrefixedText() !== new mw.Title(ctx.pageName).getPrefixedText()) {
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,944 ⟶ 2,741:
};
 
// callback from loadSuccess() for append() and prepend() threads
/**
* When functions can't use
* {@link Morebits.wiki.page~fnCanUseMwUserToken|fnCanUseMwUserToken}
* or require checking protection or watched status, maintain the query
* in one place. Used for {@link Morebits.wiki.page#deletePage|delete},
* {@link Morebits.wiki.page#undeletePage|undelete},
* {@link* Morebits.wiki.page#protect|protect},
* {@link Morebits.wiki.page#stabilize|stabilize},
* and {@link Morebits.wiki.page#move|move}
* (basically, just not {@link Morebits.wiki.page#load|load}).
*
* @param {string} action - The action being undertaken, e.g. "edit" or
* "delete".
* @returns {object} Appropriate query.
*/
var fnNeedTokenInfoQuery = function(action) {
var query = {
action: 'query',
meta: 'tokens',
type: 'csrf',
titles: ctx.pageName,
prop: 'info',
inprop: 'watched',
format: 'json'
};
// Protection not checked for flagged-revs or non-sysop moves
if (action !== 'stabilize' && (action !== 'move' || Morebits.userIsSysop)) {
query.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,986 ⟶ 2,748:
// callback from loadApi.post()
var fnLoadSuccess = function() {
var responsexml = ctx.loadApi.getResponsegetXML().query;
 
if (!fnCheckPageName(responsexml, ctx.onLoadFailure)) {
return; // abort
}
 
ctx.pageExists = $(xml).find('page').attr('missing') !== '';
var page = response.pages[0], rev;
ctx.pageExists = !page.missing;
if (ctx.pageExists) {
ctx.pageText = $(xml).find('rev').text();
rev = page.revisions[0];
ctx.lastEditTime = rev.timestamp;
ctx.pageText = rev.content;
ctx.pageID = page.pageid;
} else {
ctx.pageText = ''; // allow for concatenation, etc.
ctx.pageID = 0; // nonexistent in response, matches wgArticleId
}
 
ctx.csrfToken = response.tokens.csrftoken;
// extract protection info, to alert admins when they are about to edit a protected page
if (Morebits.userIsSysop) {
var editprot = $(xml).find('pr[type="edit"]');
if (editprot.length > 0 && editprot.attr('level') === 'sysop') {
ctx.fullyProtected = editprot.attr('expiry');
} else {
ctx.fullyProtected = false;
}
}
 
ctx.csrfToken = $(xml).find('tokens').attr('csrftoken');
if (!ctx.csrfToken) {
ctx.statusElement.error(msg('token-fetch-fail',संपादन 'Failedटोकन toप्राप्त retrieveकरने editमें token.विफल'));
ctx.onLoadFailure(this);
return;
}
ctx.loadTime = ctx$(xml).loadApi.getResponsefind('api').attr('curtimestamp');
// XXX: starttimestamp is present because of intoken=edit parameter in the API call.
// When replacing that with meta=tokens (#615), add the curtimestamp parameter to the API call
// and change 'starttimestamp' here to 'curtimestamp'
if (!ctx.loadTime) {
ctx.statusElement.error('Failedआरंभ toटाइमस्टाम्प retrieveप्राप्त currentकरने timestamp.में विफल');
ctx.onLoadFailure(this);
return;
}
ctx.lastEditTime = $(xml).find('rev').attr('timestamp');
 
ctx.contentModelrevertCurID = $(xml).find('page').contentmodelattr('lastrevid');
ctx.watched = page.watchlistexpiry || page.watched;
 
// extract protection info, to alert admins when they are about to edit a protected page
// Includes cascading protection
if (Morebits.userIsSysop) {
var editProt = page.protection.filter(function(pr) {
return pr.type === 'edit' && pr.level === 'sysop';
}).pop();
if (editProt) {
ctx.fullyProtected = editProt.expiry;
} else {
ctx.fullyProtected = false;
}
}
 
ctx.revertCurID = page.lastrevid;
 
var testactions = page.actions;
ctx.testActions = []; // was null
Object.keys(testactions).forEach(function(action) {
if (testactions[action]) {
ctx.testActions.push(action);
}
});
 
if (ctx.editMode === 'revert') {
ctx.revertCurID = $(xml).find('rev && rev').attr('revid');
if (!ctx.revertCurID) {
ctx.statusElement.error('Failedवर्तमान toअवतरण retrieveआइडी currentप्राप्त revisionकरने ID.में विफल');
ctx.onLoadFailure(this);
return;
}
ctx.revertUser = $(xml).find('rev && rev').attr('user');
if (!ctx.revertUser) {
if ($(xml).find('rev && rev').attr('userhidden') === '') { // username was RevDel'd or oversighted
ctx.revertUser = '<username hidden>';
} else {
Line 3,060 ⟶ 2,807:
}
// set revert edit summary
ctx.editSummary = '[[Help:Revert|Reverted]] to revision ' + ctx.revertOldIDrevertUser + ' byके अवतरण' + ctx.revertUserrevertOldID + 'पर [[सहायता:प्रत्यावर्तन|वापस किया]] गया: ' + ctx.editSummary;
}
 
Line 3,070 ⟶ 2,817:
 
// helper function to parse the page name returned from the API
var fnCheckPageName = function(responsexml, onFailure) {
if (!onFailure) {
onFailure = emptyFunction;
}
 
// check for invalid titles
var page = response.pages && response.pages[0];
if ($(xml).find('page').attr('invalid') === '') {
ctx.statusElement.error('The page title is invalid: ' + ctx.pageName);
// check for invalid titles
onFailure(this);
if (page.invalid) {
return false; // abort
ctx.statusElement.error(msg('invalid-title', ctx.pageName, 'The page title is invalid: ' + ctx.pageName));
}
onFailure(this);
return false; // abort
}
 
// retrieve actual title of the page after normalization and redirects
var resolvedName =if ($(xml).find('page').attr('title;')) {
var resolvedName = $(xml).find('page').attr('title');
 
if// only notify user for (response.redirects), not {normalization
if ($(xml).find('redirects').length > 0) {
// check for cross-namespace redirect:
Morebits.status.info('Info', 'Redirected from ' + ctx.pageName + ' to ' + resolvedName);
var origNs = new mw.Title(ctx.pageName).namespace;
var newNs = new mw.Title(resolvedName).namespace;
if (origNs !== newNs && !ctx.followCrossNsRedirect) {
ctx.statusElement.error(msg('cross-redirect-abort', ctx.pageName, resolvedName, ctx.pageName + ' is a cross-namespace redirect to ' + resolvedName + ', aborted'));
onFailure(this);
return false;
}
 
// only notify user for redirects, not normalization
new Morebits.status('Note', msg('redirected', ctx.pageName, resolvedName, '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
ctx.statusElement.error(msg('redirect-resolution-fail', ctx.pageName, 'Could not resolve redirects for: ' + ctx.pageName));
onFailure(this);
 
Line 3,115 ⟶ 2,850:
};
 
// helper function to get a new token on encountering token errors
/**
// in save, deletePage, and undeletePage
* Determine whether we should provide a watchlist expiry. Will not
// Being a synchronous ajax call, this blocks the event loop,
* do so if the page is currently permanently watched, or the current
// and hence should be used sparingly.
* expiry is *after* the new, provided expiry. Only handles strings
var fnGetToken = function() {
* recognized by {@link Morebits.date} or relative timeframes with
var token;
* unit it can process. Relies on the fact that fnCanUseMwUserToken
var tokenApi = new Morebits.wiki.api('टोकन प्राप्त किया जा रहा', {
* requires page loading if a watchlistexpiry is provided, so we are
action: 'query',
* ensured of knowing the watch status by the use of this.
meta: 'tokens'
*
}, function(apiobj) {
* @returns {boolean}
token = $(apiobj.responseXML).find('tokens').attr('csrftoken');
*/
var }, fnApplyWatchlistExpiry =null, function() {
this.getStatusElement().error('टोकन प्राप्त करने में विफल');
if (ctx.watchlistExpiry) {
});
if (!ctx.watched || Morebits.string.isInfinity(ctx.watchlistExpiry)) {
tokenApi.post({async: false});
return true;
return token;
} else if (typeof ctx.watched === 'string') {
var newExpiry;
// Attempt to determine if the new expiry is a
// relative (e.g. `1 month`) or absolute datetime
var rel = ctx.watchlistExpiry.split(' ');
try {
newExpiry = new Morebits.date().add(rel[0], rel[1]);
} catch (e) {
newExpiry = new Morebits.date(ctx.watchlistExpiry);
}
 
// If the date is valid, only use it if it extends the current expiry
if (newExpiry.isValid()) {
if (newExpiry.isAfter(new Morebits.date(ctx.watched))) {
return true;
}
} else {
// If it's still not valid, hope it's a valid MW expiry format that
// Morebits.date doesn't recognize, so just default to using it.
// This will also include minor typos.
return true;
}
}
}
return false;
};
 
// callback from saveApi.post()
var fnSaveSuccess = function() {
ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes
var responsexml = ctx.saveApi.getResponsegetXML();
 
// see if the API thinks we were successful
if (response$(xml).find('edit').attr('result') === 'Success') {
 
// real success
Line 3,170 ⟶ 2,881:
link.setAttribute('href', mw.util.getUrl(ctx.pageName));
link.appendChild(document.createTextNode(ctx.pageName));
ctx.statusElement.info(['completedकार्य पूर्ण हुआ (', link, ')']);
if (ctx.onSaveSuccess) {
ctx.onSaveSuccess(this); // invoke callback
Line 3,179 ⟶ 2,890:
// errors here are only generated by extensions which hook APIEditBeforeSave within MediaWiki,
// which as of 1.34.0-wmf.23 (Sept 2019) should only encompass captcha messages
if (response.edit$(xml).find('captcha').length > 0) {
ctx.statusElement.error('Could not save the page because the wiki server wanted you to fill out a CAPTCHA.');
} else {
ctx.statusElement.error(msg('api-error-unknown', 'Unknown error received from API while saving page'));
}
 
Line 3,204 ⟶ 2,915:
};
 
var purgeApi = new Morebits.wiki.api(msg('editconflict-purging', 'Edit conflict detected, purging server cache'), purgeQuery, function()null, {ctx.statusElement);
purgeApi.post({ async: false }); // just wait for it, result is for debugging
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
 
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.statusElement.info(msg('editconflict-retrying', 'Edit conflict detected, reapplying edit'));
 
if (fnCanUseMwUserToken('edit')) {
ctx.statusElement.info('Edit conflict detected, reapplying edit');
ctx.saveApi.post(); // necessarily append, prepend, or newSection, so this should work as desired
if (fnCanUseMwUserToken('edit')) {
} else {
ctx.loadApisaveApi.post(); // reloadnecessarily theappend pageor andprepend, reapplyso thethis editshould work as desired
} else {
ctx.loadApi.post(); // reload the page and reapply the edit
}, ctx.statusElement);
}
purgeApi.post();
 
// check for loss of edit token
} else if ((errorCode === 'badtoken' || errorCode === 'notoken') && ctx.retries++ < ctx.maxRetries) {
 
ctx.statusElement.info('Edit token is invalid, retrying');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.saveApi.query.token = fnGetToken.call(this);
ctx.saveApi.post();
 
// 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(msg('save-failed-retrying', 2, '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 connectivity
sleep(2000).then(function() {
ctx.saveApi.post(); // give it another go!
});
 
// hard error, give up
} else {
 
// non-admin attempting to edit a protected page - this gives a friendlier message than the default
switch (errorCode) {
if (errorCode === 'protectedpage') {
 
ctx.statusElement.error('Failed to save edit: Page is protected');
case 'protectedpage':
// check for absuefilter hits: disallowed or warning
// non-admin attempting to edit a protected page - this gives a friendlier message than the default
} else if (errorCode.indexOf('abusefilter') === 0) {
ctx.statusElement.error('Failed to save edit: Page is protected');
var desc = $(ctx.saveApi.getXML()).find('abusefilter').attr('description');
break;
if (errorCode === 'abusefilter-disallowed') {
 
ctx.statusElement.error('संपादन फिल्टर द्वारा रोका गया: "' + desc + '".');
case 'abusefilter-disallowed':
} else if (errorCode === 'abusefilter-warning') {
ctx.statusElement.error('The edit was disallowed by the edit filter: "' + ctx.saveApi.getResponse().error.abusefilter.description + '".');
ctx.statusElement.error([ 'संपादन फिल्टर द्वारा जारी चेतावनी: "', desc, '"।यदि आप फिर भी संपादन करना चाहते हैं, कृपया दुबारा प्रयत्न करें। यह चेतावनी दुबारा नहीं दिखाई जायेगी।' ]);
break;
 
case 'abusefilter-warning':
ctx.statusElement.error([ 'A warning was returned by the edit filter: "', ctx.saveApi.getResponse().error.abusefilter.description, '". If you wish to proceed with the edit, please carry it out again. This warning will not appear a second time.' ]);
// We should provide the user with a way to automatically retry the action if they so choose -
// I can't see how to do this without creating a UI dependency on Morebits.wiki.page though -- TTO
} else { // shouldn't happen but...
break;
ctx.statusElement.error('संपादन को फिल्टर द्वारा रोका गया, अनुमति नहीं है।');
 
}
case 'spamblacklist':
// check for blacklist hits
// If multiple items are blacklisted, we only return the first
var} spamelse =if ctx.saveApi.getResponse().error.errorCode === 'spamblacklist.matches[0];') {
// .find('matches') returns an array in case multiple items are blacklisted, we only return the first
ctx.statusElement.error('Could not save the page because the URL ' + spam + ' is on the spam blacklist');
var spam = $(ctx.saveApi.getXML()).find('spamblacklist').find('matches').children()[0].textContent;
break;
ctx.statusElement.error('पृष्ठ सहेजा नहीं जा सका क्योंकि यूआरएल ' + spam + ' स्पैम रोकने हेतु स्थापित काली सूची में आता है।');
 
default:} else {
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
}
}
};
 
var isTextRedirect = function(text) {
if (!text) { // no text - content empty or inaccessible (revdelled or suppressed)
return false;
}
return Morebits.l10n.redirectTagAliases.some(function(tag) {
return new RegExp('^\\s*' + tag + '\\W', 'i').test(text);
});
};
 
var fnLookupCreationSuccess = function() {
var responsexml = ctx.lookupCreationApi.getResponsegetXML().query;
 
if (!fnCheckPageName(response, ctx.onLookupCreationFailurexml)) {
return; // abort
}
 
if (!ctx.lookupNonRedirectCreator || !/^\s*#redirect/i.test($(xml).find('rev').text())) {
var rev = response.pages[0].revisions && response.pages[0].revisions[0];
if (!rev) {
ctx.statusElement.error('Could not find any revisions of ' + ctx.pageName);
ctx.onLookupCreationFailure(this);
return;
}
 
ctx.creator = $(xml).find('rev').attr('user');
if (!ctx.lookupNonRedirectCreator || !isTextRedirect(rev.content)) {
 
ctx.creator = rev.user;
if (!ctx.creator) {
ctx.statusElement.error('Couldपृष्ठ notनिर्माता findका nameनाम ofनहीं page creatorमिला');
ctx.onLookupCreationFailure(this);
return;
}
ctx.timestamp = $(xml).find('rev').attr('timestamp');
if (!ctx.timestamp) {
ctx.statusElement.error('Couldपृष्ठ notनिर्माण findका timestampटाइमस्टाम्प ofनहीं page creationमिला');
ctx.onLookupCreationFailure(this);
return;
}
 
ctx.statusElement.info('retrieved page creation information');
ctx.onLookupCreationSuccess(this);
 
Line 3,310 ⟶ 3,001:
ctx.lookupCreationApi.query.titles = ctx.pageName; // update pageName if redirect resolution took place in earlier query
 
ctx.lookupCreationApi = new Morebits.wiki.api('Retrieving page creation information', ctx.lookupCreationApi.query, fnLookupNonRedirectCreator, ctx.statusElement, ctx.onLookupCreationFailure);
ctx.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
Line 3,318 ⟶ 3,009:
 
var fnLookupNonRedirectCreator = function() {
var responsexml = ctx.lookupCreationApi.getResponsegetXML().query;
var revs = response.pages[0].revisions;
 
$(xml).find('rev').each(function(_, rev) {
for (var i = 0; i < revs.length; i++) {
if (!/^\s*#redirect/i.test(rev.textContent)) { // inaccessible revisions also check out
 
ctx.creator = rev.getAttribute('user');
if (!isTextRedirect(revs[i].content)) {
ctx.creatortimestamp = revs[i]rev.usergetAttribute('timestamp');
return false; // break
ctx.timestamp = revs[i].timestamp;
break;
}
});
 
if (!ctx.creator) {
// fallback to give first revision author if no non-redirect version in the first 50
ctx.creator = revs$(xml).find('rev')[0].getAttribute('user');
ctx.timestamp = revs$(xml).find('rev')[0].getAttribute('timestamp');
if (!ctx.creator) {
ctx.statusElement.error('Could not find name of page creator');
ctx.onLookupCreationFailure(this);
return;
}
Line 3,343 ⟶ 3,031:
if (!ctx.timestamp) {
ctx.statusElement.error('Could not find timestamp of page creation');
ctx.onLookupCreationFailure(this);
return;
}
 
ctx.statusElement.info('retrieved page creation information');
ctx.onLookupCreationSuccess(this);
 
};
 
var fnProcessMove = function() {
/**
var xml = ctx.moveApi.getXML();
* Common checks for action methods. Used for move, undelete, delete,
* protect, stabilize.
*
* @param {string} action - The action being checked.
* @param {string} onFailure - Failure callback.
* @returns {boolean}
*/
var fnPreflightChecks = function(action, onFailure) {
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsSysop && action !== 'move') {
ctx.statusElement.error('Cannot ' + action + 'page : only admins can do that');
onFailure(this);
return false;
}
 
if ($(xml).find('page').attr('missing') === '') {
if (!ctx.editSummary) {
ctx.statusElement.error('InternalCannot error:move 'the +page, actionbecause +it 'no reasonlonger not set (use setEditSummary function)!exists');
onFailurectx.onMoveFailure(this);
return false;
}
return true; // all OK
};
 
/**
* Common checks for fnProcess functions (`fnProcessDelete`, `fnProcessMove`, etc.
* Used for move, undelete, delete, protect, stabilize.
*
* @param {string} action - The action being checked.
* @param {string} onFailure - Failure callback.
* @param {string} response - The response document from the API call.
* @returns {boolean}
*/
var fnProcessChecks = function(action, onFailure, response) {
var missing = response.pages[0].missing;
 
// No undelete as an existing page could have deleted revisions
var actionMissing = missing && ['delete', 'stabilize', 'move'].indexOf(action) !== -1;
var protectMissing = action === 'protect' && missing && (ctx.protectEdit || ctx.protectMove);
var saltMissing = action === 'protect' && !missing && ctx.protectCreate;
 
if (actionMissing || protectMissing || saltMissing) {
ctx.statusElement.error('Cannot ' + action + ' the page because it ' + (missing ? 'no longer' : 'already') + ' exists');
onFailure(this);
return false;
}
 
// Delete, undelete, move
// extract protection info
if (Morebits.userIsSysop) {
var editprot;
var editprot = $(xml).find('pr[type="edit"]');
if (action === 'undelete') {
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
editprot = response.pages[0].protection.filter(function(pr) {
!confirm('You are about to move the fully protected page "' + ctx.pageName +
return pr.type === 'create' && pr.level === 'sysop';
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + editprot.attr('expiry') + ')') +
}).pop();
'. \n\nClick OK to proceed with the move, or Cancel to skip this move.')) {
} else if (action === 'delete' || action === 'move') {
ctx.statusElement.error('Move of fully protected page was aborted.');
editprot = response.pages[0].protection.filter(function(pr) {
ctx.onMoveFailure(this);
return pr.type === 'edit' && pr.level === 'sysop';
}).pop() return;
}
if (editprot && !ctx.suppressProtectWarning &&
!confirm('You are about to ' + action + ' the fully protected page "' + ctx.pageName +
(editprot.expiry === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + new Morebits.date(editprot.expiry).calendar('utc') + ' (UTC))') +
'. \n\nClick OK to proceed with ' + action + ', or Cancel to skip.')) {
ctx.statusElement.error('Aborted ' + action + ' on fully protected page.');
onFailure(this);
return false;
}
 
var moveToken = $(xml).find('page').attr('movetoken');
if (!response.tokens.csrftoken) {
if (!moveToken) {
ctx.statusElement.error('Failed to retrieve token.');
ctx.statusElement.error('Failed to retrieve move token.');
onFailure(this);
ctx.onMoveFailure(this);
return false;
return;
}
return true; // all OK
};
 
var fnProcessMove = function() {
var pageTitle, token;
 
if (fnCanUseMwUserToken('move')) {
token = mw.user.tokens.get('csrfToken');
pageTitle = ctx.pageName;
} else {
var response = ctx.moveApi.getResponse().query;
 
if (!fnProcessChecks('move', ctx.onMoveFailure, response)) {
return; // abort
}
 
token = response.tokens.csrftoken;
var page = response.pages[0];
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
 
var query = {
'action': 'move',
'from': pageTitle$(xml).find('page').attr('title'),
'to': ctx.moveDestination,
'token': tokenmoveToken,
'reason': ctx.editSummary,
watchlist: ctx.watchlistOption,
format: 'json'
};
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
if (ctx.moveTalkPage) {
query.movetalk = 'true';
Line 3,471 ⟶ 3,082:
if (ctx.moveSuppressRedirect) {
query.noredirect = 'true';
}
if (ctx.watchlistOption === 'watch') {
query.watch = 'true';
}
 
ctx.moveProcessApi = new Morebits.wiki.api(msg('moving-page', 'moving page...'), query, ctx.onMoveSuccess, ctx.statusElement, ctx.onMoveFailure);
ctx.moveProcessApi.setParent(this);
ctx.moveProcessApi.post();
};
 
var fnProcessPatrolfnProcessDelete = function() {
var querypageTitle, = {token;
action: 'patrol',
format: 'json'
};
 
if (fnCanUseMwUserToken('delete')) {
// Didn't need to load the page
token = mw.user.tokens.get('csrfToken');
if (ctx.rcid) {
query.rcidpageTitle = ctx.rcidpageName;
query.token = mw.user.tokens.get('patrolToken');
} else {
var responsexml = ctx.patrolApideleteApi.getResponsegetXML().query;
 
if ($(xml).find('page').attr('missing') === '') {
// Don't patrol if not unpatrolled
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
if (!response.recentchanges[0].unpatrolled) {
ctx.onDeleteFailure(this);
return;
}
 
// extract protection info
var lastrevid = response.pages[0].lastrevid;
var editprot = $(xml).find('pr[type="edit"]');
if (!lastrevid) {
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 ' + editprot.attr('expiry') + ')') +
'. \n\nClick OK to proceed with the deletion, or Cancel to skip this deletion.')) {
ctx.statusElement.error('Deletion of fully protected page was aborted.');
ctx.onDeleteFailure(this);
return;
}
query.revid = lastrevid;
 
var token = response$(xml).tokensfind('page').csrftokenattr('deletetoken');
if (!token) {
ctx.statusElement.error('Failed to retrieve delete token.');
ctx.onDeleteFailure(this);
return;
}
query.token = token;
}
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
var patrolStat pageTitle = new Morebits$(xml).statusfind('Marking page as patrolled').attr('title');
 
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat);
ctx.patrolProcessApi.setParent(this);
ctx.patrolProcessApi.post();
};
 
// Ensure that the page is curatable
var fnProcessTriageList = function() {
if (ctx.pageID) {
ctx.csrfToken = mw.user.tokens.get('csrfToken');
} else {
var response = ctx.triageApi.getResponse().query;
 
ctx.pageID = response.pages[0].pageid;
if (!ctx.pageID) {
return;
}
 
ctx.csrfToken = response.tokens.csrftoken;
if (!ctx.csrfToken) {
return;
}
}
 
var query = {
'action': 'pagetriagelistdelete',
page_id'title': ctx.pageIDpageTitle,
'token': token,
format: 'json'
'reason': ctx.editSummary
};
if (ctx.watchlistOption === 'watch') {
 
query.watch = 'true';
ctx.triageProcessListApi = new Morebits.wiki.api('checking curation status...', query, fnProcessTriage);
ctx.triageProcessListApi.setParent(this);
ctx.triageProcessListApi.post();
};
 
// callback from triageProcessListApi.post()
var fnProcessTriage = function() {
var responseList = ctx.triageProcessListApi.getResponse().pagetriagelist;
// Exit if not in the queue
if (!responseList || responseList.result !== 'success') {
return;
}
var page = responseList.pages && responseList.pages[0];
// Do nothing if page already triaged/patrolled
if (!page || !parseInt(page.patrol_status, 10)) {
var query = {
action: 'pagetriageaction',
pageid: ctx.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: ctx.csrfToken,
format: 'json'
};
var triageStat = new Morebits.status('Marking page as curated');
ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, null, triageStat);
ctx.triageProcessApi.setParent(this);
ctx.triageProcessApi.post();
}
};
 
var fnProcessDelete = function() {
var pageTitle, token;
 
if (fnCanUseMwUserToken('delete')) {
token = mw.user.tokens.get('csrfToken');
pageTitle = ctx.pageName;
} else {
var response = ctx.deleteApi.getResponse().query;
 
if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) {
return; // abort
}
 
token = response.tokens.csrftoken;
var page = response.pages[0];
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
 
var query = {
action: 'delete',
title: pageTitle,
token: token,
reason: ctx.editSummary,
watchlist: ctx.watchlistOption,
format: 'json'
};
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
 
ctx.deleteProcessApi = new Morebits.wiki.api('deletingपृष्ठ pageहटाया जा रहा...', query, ctx.onDeleteSuccess, ctx.statusElement, fnProcessDeleteError);
ctx.deleteProcessApi.setParent(this);
ctx.deleteProcessApi.post();
Line 3,625 ⟶ 3,153:
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.deleteProcessApi.post(); // give it another go!
} else if ((errorCode === 'badtoken' || errorCode === 'notoken') && ctx.retries++ < ctx.maxRetries) {
 
ctx.statusElement.info('Invalid token, retrying');
--Morebits.wiki.numberOfActionsLeft;
ctx.deleteProcessApi.query.token = fnGetToken.call(this);
ctx.deleteProcessApi.post();
} else if (errorCode === 'missingtitle') {
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
Line 3,643 ⟶ 3,175:
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');
pageTitle = ctx.pageName;
} else {
var responsexml = ctx.undeleteApi.getResponsegetXML().query;
 
if ($(xml).find('page').attr('missing') !== '') {
if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) {
ctx.statusElement.error('Cannot undelete the page, because it already exists');
return; // abort
ctx.onUndeleteFailure(this);
return;
}
 
// extract protection info
token = response.tokens.csrftoken;
var pageeditprot = response$(xml).pagesfind('pr[0type="create"]');
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
pageTitle = page.title;
!confirm('You are about to undelete the fully create protected page "' + ctx.pageName +
ctx.watched = page.watchlistexpiry || page.watched;
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + editprot.attr('expiry') + ')') +
'. \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.');
ctx.onUndeleteFailure(this);
return;
}
 
// KLUDGE:
token = mw.user.tokens.get('csrfToken');
pageTitle = ctx.pageName;
}
 
var query = {
'action': 'undelete',
'title': pageTitle,
'token': token,
'reason': ctx.editSummary,
watchlist: ctx.watchlistOption,
format: 'json'
};
if (ctx.changeTagswatchlistOption === 'watch') {
query.tagswatch = ctx.changeTags'true';
}
 
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
 
Line 3,686 ⟶ 3,231:
 
// check for "Database query error"
if (errorCode === 'internal_api_error_DBQueryError' && ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
if (ctx.retries++ < ctx.maxRetries) {
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.statusElement.info('Database query error, retrying');
ctx.undeleteProcessApi.post(); // give it another go!
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
} else if ((errorCode === 'badtoken' || errorCode === 'notoken') && ctx.retries++ < ctx.maxRetries) {
ctx.undeleteProcessApi.post(); // give it another go!
ctx.statusElement.info('Invalid token, retrying');
} else {
--Morebits.wiki.numberOfActionsLeft;
ctx.statusElement.error('Repeated database query error, please try again');
ctx.undeleteProcessApi.query.token = fnGetToken.call(this);
if (ctx.onUndeleteFailure) {
ctx.undeleteProcessApi.post();
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback
 
}
}
} else if (errorCode === 'cantundelete') {
ctx.statusElement.error('Cannot undelete the page, either because there are no revisions to undelete or because it has already been undeleted');
Line 3,712 ⟶ 3,256:
 
var fnProcessProtect = function() {
var responsexml = ctx.protectApi.getResponsegetXML().query;
 
var missing = $(xml).find('page').attr('missing') === '';
if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) {
if ((ctx.protectEdit || ctx.protectMove) && missing) {
return; // abort
ctx.statusElement.error('Cannot protect the page, because it no longer exists');
ctx.onProtectFailure(this);
return;
}
if (ctx.protectCreate && !missing) {
ctx.statusElement.error('Cannot create protect the page, because it already exists');
ctx.onProtectFailure(this);
return;
}
 
// TODO cascading protection not possible on edit<sysop
var token = response.tokens.csrftoken;
var page = response.pages[0];
var pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
 
var protectToken = $(xml).find('page').attr('protecttoken');
// Fetch existing protection levels
if (!protectToken) {
var prs = response.pages[0].protection;
ctx.statusElement.error('Failed to retrieve protect token.');
var editprot, moveprot, createprot;
ctx.onProtectFailure(this);
prs.forEach(function(pr) {
return;
// Filter out protection from cascading
if (pr.type === 'edit' && !pr.source) {
editprot = pr;
} else if (pr.type === 'move') {
moveprot = pr;
} else if (pr.type === 'create') {
createprot = pr;
}
});
 
 
// Fall back to current levels if not explicitly set
if (!ctx.protectEdit && editprot) {
ctx.protectEdit = { level: editprot.level, expiry: editprot.expiry };
}
if (!ctx.protectMove && moveprot) {
ctx.protectMove = { level: moveprot.level, expiry: moveprot.expiry };
}
if (!ctx.protectCreate && createprot) {
ctx.protectCreate = { level: createprot.level, expiry: createprot.expiry };
}
 
// Defaultfetch to pre-existing cascading protection if unchanged (similar to above)levels
var prs = $(xml).find('pr');
if (ctx.protectCascade === null) {
ctx.protectCascadevar editprot = !!prs.filter(function(pr'[type="edit"]') {;
var moveprot = prs.filter('[type="move"]');
return pr.cascade;
var createprot = prs.filter('[type="create"]');
}).length;
}
// Warn if cascading protection being applied with an invalid protection level,
// which for edit protection will cause cascading to be silently stripped
if (ctx.protectCascade) {
// On move protection, this is technically stricter than the MW API,
// but seems reasonable to avoid dumb values and misleading log entries (T265626)
if (((!ctx.protectEdit || ctx.protectEdit.level !== 'sysop') ||
(!ctx.protectMove || ctx.protectMove.level !== 'sysop')) &&
!confirm('You have cascading protection enabled on "' + ctx.pageName +
'" but have not selected uniform sysop-level protection.\n\n' +
'Click OK to adjust and proceed with sysop-level cascading protection, or Cancel to skip this action.')) {
ctx.statusElement.error('Cascading protection was aborted.');
ctx.onProtectFailure(this);
return;
}
 
var protections = [], expirys = [];
ctx.protectEdit.level = 'sysop';
ctx.protectMove.level = 'sysop';
}
 
// Buildset edit protection levels and expirys (expiries?) for querylevel
var protections = [], expirys = [];
if (ctx.protectEdit) {
protections.push('edit=' + ctx.protectEdit.level);
expirys.push(ctx.protectEdit.expiry);
} else if (editprot.length) {
protections.push('edit=' + editprot.attr('level'));
expirys.push(editprot.attr('expiry').replace('infinity', 'indefinite'));
}
 
Line 3,784 ⟶ 3,299:
protections.push('move=' + ctx.protectMove.level);
expirys.push(ctx.protectMove.expiry);
} else if (moveprot.length) {
protections.push('move=' + moveprot.attr('level'));
expirys.push(moveprot.attr('expiry').replace('infinity', 'indefinite'));
}
 
Line 3,789 ⟶ 3,307:
protections.push('create=' + ctx.protectCreate.level);
expirys.push(ctx.protectCreate.expiry);
} else if (createprot.length) {
protections.push('create=' + createprot.attr('level'));
expirys.push(createprot.attr('expiry').replace('infinity', 'indefinite'));
}
 
var query = {
action: 'protect',
title: pageTitle$(xml).find('page').attr('title'),
token: tokenprotectToken,
protections: protections.join('|'),
expiry: expirys.join('|'),
reason: ctx.editSummary,
watchlist: ctx.watchlistOption,
format: 'json'
};
// Only shows up in logs, not page history [[phab:T259983]]
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
 
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
if (ctx.protectCascade) {
query.cascade = 'true';
}
if (ctx.watchlistOption === 'watch') {
query.watch = 'true';
}
 
Line 3,819 ⟶ 3,333:
 
var fnProcessStabilize = function() {
var xml = ctx.stabilizeApi.getXML();
var pageTitle, token;
 
var missing = $(xml).find('page').attr('missing') === '';
if (fnCanUseMwUserToken('stabilize')) {
if (missing) {
token = mw.user.tokens.get('csrfToken');
ctx.statusElement.error('Cannot protect the page, because it no longer exists');
pageTitle = ctx.pageName;
ctx.onStabilizeFailure(this);
} else {
return;
var response = ctx.stabilizeApi.getResponse().query;
}
 
var stabilizeToken = $(xml).find('tokens').attr('csrftoken');
// 'stabilize' as a verb not necessarily well understood
if (!stabilizeToken) {
if (!fnProcessChecks('stabilize', ctx.onStabilizeFailure, response)) {
ctx.statusElement.error('Failed to retrieve stabilize token.');
return; // abort
ctx.onStabilizeFailure(this);
}
return;
 
token = response.tokens.csrftoken;
var page = response.pages[0];
pageTitle = page.title;
// Doesn't support watchlist expiry [[phab:T263336]]
// ctx.watched = page.watchlistexpiry || page.watched;
}
 
var query = {
action: 'stabilize',
title: pageTitle$(xml).find('page').attr('title'),
token: tokenstabilizeToken,
protectlevel: ctx.flaggedRevs.level,
expiry: ctx.flaggedRevs.expiry,
reason: ctx.editSummary
// tags: ctx.changeTags, // flaggedrevs tag support: [[phab:T247721]]
reason: ctx.editSummary,
watchlist: ctx.watchlistOption,
format: 'json'
};
if (ctx.watchlistOption === 'watch') {
 
query.watch = 'true';
/* Doesn't support watchlist expiry [[phab:T263336]]
if (fnApplyWatchlistExpiry()) {
query.watchlistexpiry = ctx.watchlistExpiry;
}
*/
 
ctx.stabilizeProcessApi = new Morebits.wiki.api('configuring stabilization settings...', query, ctx.onStabilizeSuccess, ctx.statusElement, ctx.onStabilizeFailure);
Line 3,861 ⟶ 3,365:
ctx.stabilizeProcessApi.post();
};
 
var sleep = function(milliseconds) {
var deferred = $.Deferred();
setTimeout(deferred.resolve, milliseconds);
return deferred;
};
 
}; // end Morebits.wiki.page
 
Line 3,878 ⟶ 3,375:
 
 
 
/* **************** Morebits.wiki.preview **************** */
/**
* **************** Morebits.wiki.preview ****************
* Use the API to parse a fragment of wikitext and render it as HTML.
* Uses the API to parse a fragment of wikitext and render it as HTML.
*
* The suggested implementation pattern (in {@link Morebits.simpleWindow} and+ Morebits.quickForm situations) is to
* construct a Morebits.wiki.preview object after rendering a Morebits.quickForm, and bind the object
* {@link Morebits.quickForm} situations) is to construct a
* to an arbitrary property of the form (e.g. |previewer|). For an example, see
* `Morebits.wiki.preview` object after rendering a `Morebits.quickForm`, and
* twinklewarn.js.
* bind the object to an arbitrary property of the form (e.g. |previewer|).
*/
* For an example, see twinklewarn.js.
 
*
/**
* @memberof Morebits.wiki
* @classconstructor
* @param {HTMLElement} previewbox - Thethe element that will contain the rendered HTML,
* usually a <div> element.
*/
Morebits.wiki.preview = function(previewbox) {
Line 3,900 ⟶ 3,398:
* Displays the preview box, and begins an asynchronous attempt
* to render the specified wikitext.
* @param {string} wikitext - wikitext to render; most things should work, including subst: and ~~~~
*
* @param {string} wikitext[pageTitle] - Wikitextoptional toparameter render;for mostthe thingspage this should workbe rendered as being on, includingif omitted it is taken as `subst:`the andcurrent `~~~~`.page
* @param {string} [pageTitle] - Optional parameter for the page this should be rendered as being on, if omitted it is taken as the current page.
* @param {string} [sectionTitle] - If provided, render the text as a new section using this as the title.
* @returns {jQuery.promise}
*/
this.beginRender = function(wikitext, pageTitle, sectionTitle) {
$(previewbox).show();
 
Line 3,918 ⟶ 3,413:
pst: 'true', // PST = pre-save transform; this makes substitution work properly
text: wikitext,
title: pageTitle || mw.config.get('wgPageName'),
disablelimitreport: true,
format: 'json'
};
var renderApi = new Morebits.wiki.api('लोड किया जा रहा...', query, fnRenderSuccess, new Morebits.status('Preview'));
if (sectionTitle) {
renderApi.post();
query.section = 'new';
query.sectiontitle = sectionTitle;
}
var renderApi = new Morebits.wiki.api('loading...', query, fnRenderSuccess, new Morebits.status('Preview'));
return renderApi.post();
};
 
var fnRenderSuccess = function(apiobj) {
var htmlxml = apiobj.getResponsegetXML().parse.text;
var html = $(xml).find('text').text();
if (!html) {
apiobj.statelem.error('failed to retrieve preview, or template was blanked');
Line 3,947 ⟶ 3,437:
 
 
/* **************** Morebits.wikitext **************** */
 
/**
* **************** Morebits.wikitext ****************
* Wikitext manipulation.
* Wikitext manipulation
*
* @namespace Morebits.wikitext
* @memberof Morebits
*/
 
Morebits.wikitext = {};
 
Morebits.wikitext.template = {
/**
parse: function(text, start) {
* Get the value of every parameter found in the wikitext of a given template.
var count = -1;
*
var level = -1;
* @memberof Morebits.wikitext
var equals = -1;
* @param {string} text - Wikitext containing a template.
var current = '';
* @param {number} [start=0] - Index noting where in the text the template begins.
var result = {
* @returns {object} `{name: templateName, parameters: {key: value}}`.
name: '',
*/
parameters: {}
Morebits.wikitext.parseTemplate = function(text, start) {
};
start = start || 0;
var key, value;
 
for (var i = start; i < text.length; ++i) {
var level = []; // Track of how deep we are ({{, {{{, or [[)
var test3 = text.substr(i, 3);
var count = -1; // Number of parameters found
if (test3 === '{{{') {
var unnamed = 0; // Keep track of what number an unnamed parameter should receive
current += '{{{';
var equals = -1; // After finding "=" before a parameter, the index; otherwise, -1
var current i += ''2;
++level;
var result = {
continue;
name: '',
}
parameters: {}
if (test3 === '}}}') {
};
current += '}}}';
var key, value;
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;
 
if (level <= 0) {
/**
if (count === -1) {
* Function to handle finding parameter values.
result.name = current.substring(2).trim();
*
++count;
* @param {boolean} [final=false] - Whether this is the final
} else {
* parameter and we need to remove the trailing `}}`.
if (equals !== -1) {
*/
key = current.substring(0, equals).trim();
function findParam(final) {
value = current.substring(equals).trim();
// Nothing found yet, this must be the template name
result.parameters[key] = value;
if (count === -1) {
equals = -1;
result.name = current.substring(2).trim();
++count; } else {
result.parameters[count] = current;
} else {
++count;
// In a parameter
}
if (equals !== -1) {
}
// We found an equals, so save the parameter as key: value
break;
key = current.substring(0, equals).trim();
value = final ? current.substring(equals + 1, current.length - 2).trim() : current.substring(equals + 1).trim();
result.parameters[key] = value;
equals = -1;
} else {
// No equals, so it must be unnamed; no trim since whitespace allowed
var param = final ? current.substring(equals + 1, current.length - 2) : current;
if (param) {
result.parameters[++unnamed] = param;
++count;
}
continue;
}
}
}
 
for if (var text.charAt(i) === start;'|' i&& level <= text.length; ++i0) {
if (count === -1) {
var test3 = text.substr(i, 3);
result.name = current.substring(2).trim();
if (test3 === '{{{' || (test3 === '}}}' && level[level.length - 1] === 3)) {
current += test3+count;
i } +=else 2;{
if (test3equals =!== '{{{'-1) {
key = current.substring(0, equals).trim();
level.push(3);
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 {
levelcurrent += text.popcharAt(i);
}
continue;
}
var test2 = text.substr(i, 2);
// Entering a template (or link)
if (test2 === '{{' || test2 === '[[') {
current += test2;
++i;
if (test2 === '{{') {
level.push(2);
} else {
level.push('wl');
}
continue;
}
// Either leaving a link or template/parser function
if ((test2 === '}}' && level[level.length - 1] === 2) ||
(test2 === ']]' && level[level.length - 1] === 'wl')) {
current += test2;
++i;
level.pop();
 
return result;
// Find the final parameter if this really is the end
if (test2 === '}}' && level.length === 0) {
findParam(true);
break;
}
continue;
}
 
if (text.charAt(i) === '|' && level.length === 1) {
// Another pipe found, toplevel, so parameter coming up!
findParam();
current = '';
} else if (equals === -1 && text.charAt(i) === '=' && level.length === 1) {
// Equals found, toplevel
equals = current.length;
current += text.charAt(i);
} else {
// Just advance the position
current += text.charAt(i);
}
}
 
return result;
};
 
/**
* @constructor
* Adjust and manipulate the wikitext of a page.
* @param {string} text
*
* @class
* @memberof Morebits.wikitext
* @param {string} text - Wikitext to be manipulated.
*/
Morebits.wikitext.page = function mediawikiPage(text) {
Line 4,081 ⟶ 3,550:
/**
* 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);
// Remove a leading colon, to be handled later
var link_re_string = '[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExp.escape(link_target.substr(1), true);
if (link_target.indexOf(':') === 0) {
link_target = link_target.slice(1);
}
var link_re_string = '', ns = '', title = link_target;
 
var idx = link_target.indexOf(':');
if (idx > 0) {
ns = link_target.slice(0, idx);
title = link_target.slice(idx + 1);
 
link_re_string = Morebits.namespaceRegex(mw.config.get('wgNamespaceIds')[ns.toLowerCase().replace(/ /g, '_')]) + ':';
}
link_re_string += Morebits.pageNameRegex(title);
 
// Allow for an optional leading colon, e.g. [[:User:Test]]
// Files and Categories become links with a leading colon, e.g. [[:File:Test.png]]
// Otherwise, allow for an optional leading colon, e.g. [[:User:Test]]
var colon = new RegExp(Morebits.namespaceRegex([6, 14])).test(ns) ? ':' : ':?';
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;
},
 
/**
* Comments out images from page text;. ifIf used in a gallery, deletes the whole line.
* If used as a template argument (not necessarily with `File:` prefix), the template parameter is commented out.
* @param {string} image - Image name without File: prefix
*
* @param {string} imagereason - ImageReason nameto withoutbe `File:`included prefix.in comment, alongside the commented-out image
* @param {string} [reason] - Reason to be included in comment, alongside the commented-out image.
* @returns {Morebits.wikitext.page}
*/
commentOutImage: function(image, reason) {
Line 4,124 ⟶ 3,577:
 
reason = reason ? reason + ': ' : '';
var image_re_stringfirst_char = Morebitsimage.pageNameRegexsubstr(image0, 1);
var image_re_string = '[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExp.escape(image.substr(1), true);
 
// Check for normal image links, i.e. [[File:Foobar.png|...]]
// Will eat the whole link
var links_re = new RegExp('\\[\\[' + Morebits.namespaceRegex(6?:[Ii]mage|[Ff]ile) + ':\\s*' + image_re_string + '\\s*[\\|(?:\\]\\])]');
var allLinks = Morebits.array.uniq(Morebits.string.splitWeightedByKeys(unbinder.content, '[[', ']]'));
for (var i = 0; i < allLinks.length; ++i) {
if (links_re.test(allLinks[i])) {
var replacement = '<!-- ' + reason + allLinks[i] + ' -->';
unbinder.content = unbinder.content.replace(allLinks[i], replacement, 'g');
}
}
Line 4,142 ⟶ 3,596:
// eventually preceded with some space, and must include File: prefix
// Will eat the whole line.
var gallery_image_re = new RegExp('(^\\s*' + Morebits.namespaceRegex(6?:[Ii]mage|[Ff]ile) + ':\\s*' + image_re_string + '\\s*(?:\\|.*?$|$))', 'mg');
unbinder.content = unbinder.content.replace(gallery_image_re, '<!-- ' + reason + '$1 -->');
 
Line 4,148 ⟶ 3,602:
unbinder.unbind('<!--', '-->');
 
// Check free image usages, for example as template arguments, might have the File: prefix excluded, but must be precededpreceeded by an |
// Will only eat the image name and the precedingpreceeding bar and an eventual named parameter
var free_image_re = new RegExp('(\\|\\s*(?:[\\w\\s]+\\=)?\\s*(?:' + Morebits.namespaceRegex(6?:[Ii]mage|[Ff]ile) + ':\\s*)?' + image_re_string + ')', 'mg');
unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->');
// Rebind the content now, we are done!
this.text = unbinder.rebind();
return this;
},
 
/**
* Converts usesfirst usage of [[File:`image`]] to [[File:`image`|`data`]].
* @param {string} image - Image name without File: prefix
*
* @param {string} image - Image name without File: prefix.data
* @param {string} data - The display options.
* @returns {Morebits.wikitext.page}
*/
addToImageComment: function(image, data) {
var image_re_stringfirst_char = Morebitsimage.pageNameRegexsubstr(image0, 1);
var first_char_regex = RegExp.escape(first_char, true);
var links_re = new RegExp('\\[\\[' + Morebits.namespaceRegex(6) + ':\\s*' + image_re_string + '\\s*[\\|(?:\\]\\])]');
if (first_char.toUpperCase() !== first_char.toLowerCase()) {
var allLinks = Morebits.string.splitWeightedByKeys(this.text, '[[', ']]');
first_char_regex = '[' + RegExp.escape(first_char.toUpperCase(), true) + RegExp.escape(first_char.toLowerCase(), true) + ']';
}
var image_re_string = '(?:[Ii]mage|[Ff]ile):\\s*' + first_char_regex + RegExp.escape(image.substr(1), true);
var links_re = new RegExp('\\[\\[' + image_re_string);
var allLinks = Morebits.array.uniq(Morebits.string.splitWeightedByKeys(this.text, '[[', ']]'));
for (var i = 0; i < allLinks.length; ++i) {
if (links_re.test(allLinks[i])) {
Line 4,173 ⟶ 3,629:
// just put it at the end?
replacement = replacement.replace(/\]\]$/, '|' + data + ']]');
this.text = this.text.replace(allLinks[i], replacement, 'g');
}
}
Line 4,179 ⟶ 3,635:
var newtext = '$1|$2 ' + data;
this.text = this.text.replace(gallery_re, newtext);
return this;
},
 
/**
* Remove allRemoves transclusions of a template from page text.
*
* @param {string} template - Page name whose transclusions are to be removed,
* include namespace prefix only if not in template namespace.
* @returns {Morebits.wikitext.page}
*/
removeTemplate: function(template) {
var template_re_stringfirst_char = Morebitstemplate.pageNameRegexsubstr(template0, 1);
var template_re_string = '(?:[Tt]emplate:)?\\s*[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExp.escape(template.substr(1), true);
var links_re = new RegExp('\\{\\{(?:' + Morebits.namespaceRegex(10) + ':)?\\s*' + template_re_string + '\\s*[\\|(?:\\}\\})]');
var links_re = new RegExp('\\{\\{' + template_re_string);
var allTemplates = Morebits.string.splitWeightedByKeys(this.text, '{{', '}}', [ '{{{', '}}}' ]);
var allTemplates = Morebits.array.uniq(Morebits.string.splitWeightedByKeys(this.text, '{{', '}}', [ '{{{', '}}}' ]));
for (var i = 0; i < allTemplates.length; ++i) {
if (links_re.test(allTemplates[i])) {
this.text = this.text.replace(allTemplates[i], '', 'g');
}
}
return this;
},
 
/** @returns {string} */
/**
* Smartly insert a tag atop page text but after specified templates,
* 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. `''` to provide no flags;
* other falsey values will default to `i`.
* @param {string|string[]} [preRegex] - Optional regex string or array to match
* before any template matches (i.e. before `{{`), such as html comments.
* @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('|');
}
 
if (typeof flags !== 'string') {
flags = 'i';
}
 
if (!preRegex || !preRegex.length) {
preRegex = '';
} else if (Array.isArray(preRegex)) {
preRegex = preRegex.join('|');
}
 
 
// Regex is extra complicated to allow for templates with
// parameters and to handle whitespace properly
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;
},
 
/**
* Get the manipulated wikitext.
*
* @returns {string}
*/
getText: function() {
return this.text;
Line 4,279 ⟶ 3,660:
};
 
 
/* *********** Morebits.userspaceLogger ************ */
/**
* **************** Morebits.status ****************
* Handles logging actions to a userspace log.
* Used in CSD, PROD, and XFD.
*
* @memberof Morebits
* @class
* @param {string} logPageName - Title of the subpage of the current user's log.
*/
Morebits.userspaceLogger = function(logPageName) {
if (!logPageName) {
throw new Error('no log page name specified');
}
/**
* The text to prefix the log with upon creation, defaults to empty.
*
* @type {string}
*/
this.initialText = '';
/**
* The header level to use for months, defaults to 3 (`===`).
*
* @type {number}
*/
this.headerLevel = 3;
this.changeTags = '';
 
/**
* Log the entry.
*
* @param {string} logText - Doesn't include leading `#` or `*`.
* @param {string} summaryText - Edit summary.
* @returns {JQuery.Promise}
*/
this.log = function(logText, summaryText) {
var def = $.Deferred();
if (!logText) {
return def.reject();
}
var page = new Morebits.wiki.page('User:' + mw.config.get('wgUserName') + '/' + logPageName,
'Adding entry to userspace log'); // make this '... to ' + logPageName ?
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
var date = new Morebits.date(pageobj.getLoadTime());
if (!date.monthHeaderRegex().exec(text)) {
text += '\n\n' + date.monthHeader(this.headerLevel);
}
 
pageobj.setPageText(text + '\n' + logText);
pageobj.setEditSummary(summaryText);
pageobj.setChangeTags(this.changeTags);
pageobj.setCreateOption('recreate');
pageobj.save(def.resolve, def.reject);
}.bind(this));
return def;
};
};
 
 
/* **************** Morebits.status **************** */
/**
* @constructor
* Create and show status messages of varying urgency.
* {@link Morebits.status.init|Morebits.status.init()} must be called before any status object is created, otherwise
* 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 `:`
* @memberof Morebits
* @param {String} [type=status] - This parameter determines the font color of the status line,
* @class
* this can be 'status' (blue), 'info' (green), 'warn' (red), or 'error' (bold red)
* @param {string} text - Text before the the colon `:`.
* The default is 'status'
* @param {string} stat - Text after the colon `:`.
* @param {string} [type=status] - Determine the font color of the status
* line, allowable values are: `status` (blue), `info` (green), `warn` (red),
* or `error` (bold red).
*/
 
Morebits.status = function Status(text, stat, type) {
this.textRaw = text;
this.text = Morebitsthis.createHtmlcodify(text);
this.type = type || 'status';
this.generate();
Line 4,368 ⟶ 3,686:
 
/**
* Specify an area for status message elements to be added to.
* @param {HTMLElement} root - usually a div element
*
* @memberof Morebits.status
* @param {HTMLElement} root - Usually a div element.
* @throws If `root` is not an `HTMLElement`.
*/
Morebits.status.init = function(root) {
Line 4,387 ⟶ 3,702:
Morebits.status.root = null;
 
/** @param {Function} handler - function to execute on error */
/**
* @memberof Morebits.status
* @param {Function} handler - Function to execute on error.
* @throws When `handler` is not a function.
*/
Morebits.status.onError = function(handler) {
if (typeof handler === 'function') {
Line 4,402 ⟶ 3,713:
Morebits.status.prototype = {
stat: null,
statRaw: null,
text: null,
textRaw: null,
Line 4,410 ⟶ 3,720:
linked: false,
 
/** Add the status element node to the DOM. */
link: function() {
if (!this.linked && Morebits.status.root) {
Line 4,418 ⟶ 3,728:
},
 
/** Remove the status element node from the DOM. */
unlink: function() {
if (this.linked) {
Line 4,427 ⟶ 3,737:
 
/**
* UpdateCreate a document fragment with the status. text
* @param {(string|Element|Array)} obj
*
* @returns {DocumentFragment}
* @param {string} status - Part of status message after colon.
*/
* @param {string} type - 'status' (blue), 'info' (green), 'warn'
codify: function(obj) {
* (red), or 'error' (bold red).
if (!Array.isArray(obj)) {
obj = [ obj ];
}
var result;
result = document.createDocumentFragment();
for (var i = 0; i < obj.length; ++i) {
if (typeof obj[i] === 'string') {
result.appendChild(document.createTextNode(obj[i]));
} else if (obj[i] instanceof Element) {
result.appendChild(obj[i]);
} // Else cosmic radiation made something shit
}
return result;
 
},
 
/**
* Update the status
* @param {String} status - Part of status message after colon `:`
* @param {String} type - 'status' (blue), 'info' (green), 'warn' (red), or 'error' (bold red)
*/
update: function(status, type) {
this.statRawstat = this.codify(status);
this.stat = Morebits.createHtml(status);
if (type) {
this.type = type;
Line 4,448 ⟶ 3,777:
 
// also log error messages in the browser console
console.error(this.textRaw + ': ' + this.statRawstatus); // eslint-disable-line no-console
}
}
Line 4,454 ⟶ 3,783:
},
 
/** Produce the html for first part of the status message. */
generate: function() {
this.node = document.createElement('div');
Line 4,463 ⟶ 3,792:
},
 
/** Complete the html, for the second part of the status message. */
render: function() {
this.node.className = 'morebits_status_tw_status_' + this.type;
while (this.target.hasChildNodes()) {
this.target.removeChild(this.target.firstChild);
Line 4,485 ⟶ 3,814:
}
};
 
/**
* @memberof Morebits.status
* @param {string} text - Before colon
* @param {string} status - After colon
* @returns {Morebits.status} - `status`-type (blue)
*/
Morebits.status.status = function(text, status) {
return new Morebits.status(text, status);
};
/**
* @memberof Morebits.status
* @param {string} text - Before colon
* @param {string} status - After colon
* @returns {Morebits.status} - `info`-type (green)
*/
Morebits.status.info = function(text, status) {
return new Morebits.status(text, status, 'info');
};
 
/**
* @memberof Morebits.status
* @param {string} text - Before colon
* @param {string} status - After colon
* @returns {Morebits.status} - `warn`-type (red)
*/
Morebits.status.warn = function(text, status) {
return new Morebits.status(text, status, 'warn');
};
 
/**
* @memberof Morebits.status
* @param {string} text - Before colon
* @param {string} status - After colon
* @returns {Morebits.status} - `error`-type (bold red)
*/
Morebits.status.error = function(text, status) {
return new Morebits.status(text, status, 'error');
Line 4,525 ⟶ 3,830:
* For the action complete message at the end, create a status line without
* a colon separator.
* @param {String} text
*
* @memberof Morebits.status
* @param {string} text
*/
Morebits.status.actionCompleted = function(text) {
var node = document.createElement('div');
node.appendChild(document.createElement('bspan')).appendChild(document.createTextNode(text));
node.className = 'morebits_status_info morebits_action_completetw_status_info';
if (Morebits.status.root) {
Morebits.status.root.appendChild(node);
Line 4,539 ⟶ 3,842:
 
/**
* Display the user's rationale, comments, etc. Backback to them after a failure,
* so that they may re-use it.
*
* @memberof Morebits.status
* @param {string} comments
* @param {string} message
Line 4,561 ⟶ 3,862:
 
/**
* **************** Morebits.htmlNode() ****************
* Simple helper function to create a simple node.
* Simple helper function to create a simple node
*
* @param {string} type - Typetype of HTML element.
* @param {string} contenttext - Texttext content.
* @param {string} [color] - Fontfont color.
* @returns {HTMLElement}
*/
Line 4,580 ⟶ 3,881:
 
/**
* **************** Morebits.checkboxShiftClickSupport() ****************
* Add shift-click support for checkboxes. The wikibits version
* shift-click-support for checkboxes
* (`window.addCheckboxClickHandlers`) has some restrictions, and doesn't work
* wikibits version (window.addCheckboxClickHandlers) has some restrictions, and
* with checkboxes inside a sortable table, so let's build our own.
* doesn't work with checkboxes inside a sortable table, so let's build our own.
*
* @param jQuerySelector
* @param jQueryContext
*/
Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) {
Line 4,638 ⟶ 3,937:
 
 
/** **************** Morebits.batchOperation **************** */
/**
* Iterates over a group of pages (or arbitrary objects) and executes a worker function
* for each.
*
* Constructor: Morebits.batchOperation(currentAction)
* `setPageList(pageList)`: Sets the list of pages to work on. It should be an
* array of page names strings.
*
* setPageList(wikitext): Sets the list of pages to work on.
* `setOption(optionName, optionValue)`: Sets a known option:
* It should be an array of page names (strings).
* - `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.
*
* setOption(optionName, optionValue): Sets a known option:
* `run(worker, postFinish)`: Runs the callback `worker` for each page in the
* - chunkSize (integer): the size of chunks to break the array into (default 50).
* list. The callback must call `workerSuccess` when succeeding, or
* Setting this to a small value (<5) can cause problems.
* `workerFailure` when failing. If using {@link Morebits.wiki.api} or
* - preserveIndividualStatusLines (boolean): keep each page's status element visible
* {@link Morebits.wiki.page}, this is easily done by passing these two
* when worker is complete? See note below
* functions as parameters to the methods on those objects: for instance,
* `page.save(batchOp.workerSuccess, batchOp.workerFailure)`. Make sure the
* methods are called directly if special success/failure cases arise. If you
* omit to call these methods, the batch operation will stall after the first
* 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.
*
* run(worker, postFinish): Runs the callback `worker` for each page in the list.
* If using `preserveIndividualStatusLines`, you should try to ensure that the
* The callback must call workerSuccess when succeeding, or workerFailure
* `workerSuccess` callback has access to the page title. This is no problem for
* when failing. If using Morebits.wiki.api or Morebits.wiki.page, this is easily
* {@link Morebits.wiki.page} objects. But when using the API, please set the
* done by passing these two functions as parameters to the methods on those
* |pageName| property on the {@link Morebits.wiki.api} object.
* objects, for instance, page.save(batchOp.workerSuccess, batchOp.workerFailure).
* Make sure the methods are called directly if special success/failure cases arise.
* If you omit to call these methods, the batch operation will stall after the first
* 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
* workerSuccess callback has access to the page title. This is no problem for
* Morebits.wiki.page objects. But when using the API, please set the
* |pageName| property on the Morebits.wiki.api object.
*
* There are sample batchOperation implementations using Morebits.wiki.page in
* twinklebatchdelete.js, twinklebatchundelete.js, and twinklebatchprotect.js.
*/
 
* @memberof Morebits
/**
* @class
* @constructor
* @param {string} [currentAction]
*/
Line 4,686 ⟶ 3,986:
 
// internal counters, etc.
statusElement: new Morebits.status(currentAction || msg('batch-starting', 'Performing batch operation')),
worker: null, // function that executes for each item in pageList
postFinish: null, // function that executes when the whole batch has been processed
Line 4,703 ⟶ 4,003:
 
/**
* Sets the list of pages to work on.
* @param {Array} pageList Array of objects over which you wish to execute the worker function
*
* @param {Array} pageList - Array of objects over which you wish to execute the worker function
* This is usually the list of page names (strings).
*/
Line 4,713 ⟶ 4,012:
 
/**
* Sets a known option.:
* - chunkSize (integer):
*
* The size of chunks to break the array into (default 50).
* @param {string} optionName - Name of the option:
* Setting this to a small value (<5) can cause problems.
* - chunkSize (integer): The size of chunks to break the array into
* - preserveIndividualStatusLines (boolean):
* (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?
* element visible when worker is complete?
* @param {number|boolean} optionValue - Value to which the option is
* to be set. Should be an integer for chunkSize and a boolean for
* preserveIndividualStatusLines.
*/
this.setOption = function(optionName, optionValue) {
Line 4,731 ⟶ 4,026:
* Runs the first callback for each page in the list.
* The callback must call workerSuccess when succeeding, or workerFailure when failing.
* Runs the optional second callback when the whole batch has been processed. (optional)
*
* @param {Function} worker
* @param {Function} [postFinish]
Line 4,753 ⟶ 4,047:
var total = ctx.pageList.length;
if (!total) {
ctx.statusElement.info(msg('batch-no-pages', 'no pages specified'));
ctx.running = false;
if (ctx.postFinish) {
Line 4,771 ⟶ 4,065:
 
/**
* To be called by worker before it terminates successfully.succesfully
* @param {(Morebits.wiki.page|Morebits.wiki.api|string)} arg
*
* @param {(Morebits.wiki.page|Morebits.wiki.api|string)} arg -
* This should be the `Morebits.wiki.page` or `Morebits.wiki.api` object used by worker
* (for the adjustment of status lines emitted by them).
* If no Morebits.wiki.* object is used (e.geg. 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) {
Line 4,788 ⟶ 4,088:
// we know the page title - display a relevant message
var pageName = arg.getPageName ? arg.getPageName() : arg.pageName || arg.query.title;
statelem.info(msg('batch-done-page', pageName, ['completed ([[', + createPageLink(pageName +), ']])')]);
} else {
// we don't know the page title - just display a generic message
statelem.info(msg('done', 'done'));
}
} else {
Line 4,799 ⟶ 4,099:
 
} else if (typeof arg === 'string' && ctx.options.preserveIndividualStatusLines) {
new Morebits.status(arg, msg(['batch-done-page (', createPageLink(arg), 'completed ([[' + arg + )']])'));
}
 
Line 4,832 ⟶ 4,132:
// update overall status line
var total = ctx.pageList.length;
if (ctx.countFinished <=== total) {
var progressstatusString = Math.round'Done (100' *+ ctx.countFinished /countFinishedSuccess total);+
'/' + ctx.countFinished + ' actions completed successfully)';
ctx.statusElement.status(msg('percent', progress, progress + '%'));
 
// 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 = msg('batch-progress', ctx.countFinishedSuccess, ctx.countFinished, 'Done (' + ctx.countFinishedSuccess +
'/' + ctx.countFinished + ' actions completed successfully)');
if (ctx.countFinishedSuccess < ctx.countFinished) {
ctx.statusElement.warn(statusString);
Line 4,855 ⟶ 4,145:
Morebits.wiki.removeCheckpoint();
ctx.running = false;
return;
} else {
}
// 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;
}
};
};
 
ctx.statusElement.status(parseInt(100 * ctx.countFinished / total, 10) + '%');
/**
* Given a set of asynchronous functions to run along with their dependencies,
* run them in an efficient sequence 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.
*
* @memberof Morebits
* @class
*/
Morebits.taskManager = function(context) {
this.taskDependencyMap = new Map();
this.failureCallbackMap = new Map();
this.deferreds = new Map();
this.allDeferreds = []; // Hack: IE doesn't support Map.prototype.values
this.context = context || window;
 
// 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
* Register a task along with its dependencies (tasks which should have finished
if (ctx.countFinished >= (ctx.countStarted - Math.max(ctx.options.chunkSize / 10, 2)) &&
* execution before we can begin this one). Each task is a function that must return
Math.floor(ctx.countFinished / ctx.options.chunkSize) > ctx.currentChunkIndex) {
* a promise. The function will get the values resolved by the dependency functions
fnStartNewChunk();
* as arguments.
* }
* @param {Function} func - A task.
* @param {Function[]} deps - Its dependencies.
* @param {Function} [onFailure] - a failure callback that's run if the task or any one
* of its dependencies fail.
*/
this.add = function(func, deps, onFailure) {
this.taskDependencyMap.set(func, deps);
this.failureCallbackMap.set(func, onFailure || function() {});
var deferred = $.Deferred();
this.deferreds.set(func, deferred);
this.allDeferreds.push(deferred);
};
};
 
/**
* Run all the tasks. Multiple tasks may be run at once.
*
* @returns {jQuery.Promise} - Resolved if all tasks succeed, rejected otherwise.
*/
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(self.context, dependencyPromisesArray).then(function() {
var result = task.apply(self.context, arguments);
if (result === undefined) { // maybe the function threw, or it didn't return anything
mw.log.error('Morebits.taskManager: task returned undefined');
self.deferreds.get(task).reject.apply(self.context, arguments);
self.failureCallbackMap.get(task).apply(self.context, []);
}
result.then(function() {
self.deferreds.get(task).resolve.apply(self.context, arguments);
}, function() { // task failed
self.deferreds.get(task).reject.apply(self.context, arguments);
self.failureCallbackMap.get(task).apply(self.context, arguments);
});
}, function() { // one or more of the dependencies failed
self.failureCallbackMap.get(task).apply(self.context, arguments);
});
});
return $.when.apply(null, this.allDeferreds); // resolved when everything is done!
};
 
};
 
/**
* **************** Morebits.simpleWindow ****************
* A simple draggable window, now a wrapper for jQuery UI's dialog feature.
* A simple draggable window
*
* now a wrapper for jQuery UI's dialog feature
* @memberof Morebits
* @requires {jquery.ui.dialog}
* @class
*/
* @requires jquery.ui.dialog
 
/**
* @constructor
* @param {number} width
* @param {number} height - The maximum allowable height for the content area.
*/
Morebits.simpleWindow = function SimpleWindow(width, height) {
Line 4,972 ⟶ 4,209:
}
},
resizeStopresizeEnd: function() {
this.scrollbox = null;
},
Line 4,984 ⟶ 4,221:
 
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 5,009 ⟶ 4,251:
/**
* Focuses the dialog. This might work, or on the contrary, it might not.
*
* @returns {Morebits.simpleWindow}
*/
Line 5,020 ⟶ 4,261:
* Closes the dialog. If this is set as an event handler, it will stop the event
* from doing anything more.
*
* @param {event} [event]
* @returns {Morebits.simpleWindow}
*/
Line 5,035 ⟶ 4,274:
* Shows the dialog. Calling display() on a dialog that has previously been closed
* might work, but it is not guaranteed.
*
* @returns {Morebits.simpleWindow}
*/
Line 5,059 ⟶ 4,297:
/**
* Sets the dialog title.
*
* @param {string} title
* @returns {Morebits.simpleWindow}
Line 5,071 ⟶ 4,308:
* Sets the script name, appearing as a prefix to the title to help users determine which
* user script is producing which dialog. For instance, Twinkle modules set this to "Twinkle".
*
* @param {string} name
* @returns {Morebits.simpleWindow}
Line 5,082 ⟶ 4,318:
/**
* Sets the dialog width.
*
* @param {number} width
* @returns {Morebits.simpleWindow}
Line 5,094 ⟶ 4,329:
* Sets the dialog's maximum height. The dialog will auto-size to fit its contents,
* but the content area will grow no larger than the height given here.
*
* @param {number} height
* @returns {Morebits.simpleWindow}
Line 5,117 ⟶ 4,351:
/**
* Sets the content of the dialog to the given element node, usually from rendering
* a {@link Morebits.quickForm}.
* Re-enumerates the footer buttons, but leaves the footer links as they are.
* Be sure to call this at least once before the dialog is displayed...
*
* @param {HTMLElement} content
* @returns {Morebits.simpleWindow}
Line 5,132 ⟶ 4,365:
/**
* Adds the given element node to the dialog content.
*
* @param {HTMLElement} content
* @returns {Morebits.simpleWindow}
Line 5,144 ⟶ 4,376:
value.style.display = 'none';
var button = document.createElement('button');
button.textContent = value.hasAttribute('value') ? value.getAttribute('value') : value.textContent ? value.textContent : msg('submit', 'Submit Query');
button.className = value.className || 'submitButtonProxy';
// here is an instance of cheap coding, probably a memory-usage hit in using a closure here
Line 5,162 ⟶ 4,394:
 
/**
* Removes all contents from the dialog, barring any footer links.
*
* @returns {Morebits.simpleWindow}
*/
Line 5,182 ⟶ 4,413:
* For example, Twinkle's CSD module adds a link to the CSD policy page,
* as well as a link to Twinkle's documentation.
* @param {string} text Link's text content
*
* @param {string} textwikiPage - DisplayLink text.target
* @param {stringboolean} wikiPage[prep=false] -Set Linktrue target.to prepend rather than append
* @param {boolean} [prep=false] - Set true to prepend rather than append.
* @returns {Morebits.simpleWindow}
*/
Line 5,192 ⟶ 4,422:
if (this.hasFooterLinks) {
var bullet = document.createElement('span');
bullet.textContent = msg('bullet-separator', ' \u2022 '); // U+2022 BULLET
if (prep) {
$footerlinks.prepend(bullet);
Line 5,214 ⟶ 4,444:
 
/**
* SetsSet whether the window should be modal or not. Modal dialogs create
* anIf overlayset belowto thetrue, dialogother butitems aboveon otherthe page elementswill be disabled, i.e., cannot Thisbe
* interacted with. Modal dialogs create an overlay below the dialog but above
* must be used (if necessary) before calling display().
* other page elements.
*
* This must be used (if necessary) before calling display()
* @param {boolean} [modal=false] - If set to true, other items on the
* Default: false
* page will be disabled, i.e., cannot be interacted with.
* @param {boolean} modal
* @returns {Morebits.simpleWindow}
*/
Line 5,229 ⟶ 4,460:
 
/**
* Enables or disables all footer buttons on all {@link Morebits.simpleWindow}ssimpleWindows in the current page.
* This should be called with `false` when the button(s) become irrelevant (e.g. just before
* {@link Morebits.status.init} is called).
* This is not an instance method so that consumers don't have to keep a reference to the
* original `Morebits.simpleWindow` object sitting around somewhere. Anyway, most of the time
* there will only be one `Morebits.simpleWindow` open, so this shouldn't matter.
*
* @memberof Morebits.simpleWindow
* @param {boolean} enabled
*/
Line 5,242 ⟶ 4,471:
$('.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 5,249 ⟶ 4,482:
/**
* If this script is being executed outside a ResourceLoader context, we add some
* global assignments for legacy scripts, hopefully these can be removed down the line.
*
* IMPORTANT NOTE: