"मीडियाविकि:Gadget-morebits.js": अवतरणों में अंतर
Content deleted Content added
update टैग: Reverted |
reverted back टैग: Manual revert |
||
पंक्ति 1,707:
};
/**
* **************** Morebits.wiki.page ****************
* 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
* before the first call to
*
* Each of the callback functions takes one parameter, which is a
पंक्ति 1,722:
*
*
* HIGHLIGHTS:
*
* Constructor: Morebits.wiki.page(pageName, currentAction)
* pageName - the name of the page, prefixed by the namespace (if any)
* (for the current page, use mw.config.get('wgPageName'))
* currentAction - a string describing the action about to be undertaken (optional)
*
* onSuccess and onFailure are callback functions called when the operation is a success or failure
* if enclosed in [brackets], it indicates that it is optional
*
* load(onSuccess, [onFailure]): Loads the text for the page
*
* getPageText(): returns a string containing the text of the page after a successful load()
*
* 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()
*
*/
/**
* Call sequence for common operations (optional final user callbacks not shown):
*
* 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.
*/
var ctx = {
Line 1,774 ⟶ 1,845:
pageExists: false,
editSummary: null,
callbackParameters: null,
statusElement
// - 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
createOption: null,
minorEdit: false,
Line 1,793 ⟶ 1,860:
maxRetries: 2,
followRedirect: false,
watchlistOption: 'nochange',
creator: null,
timestamp: null,
Line 1,812 ⟶ 1,877:
protectMove: null,
protectCreate: null,
protectCascade:
// - creation lookup
Line 1,825 ⟶ 1,890:
loadTime: null,
lastEditTime: null,
revertCurID: null,
revertUser: null,
fullyProtected: false,
suppressProtectWarning: false,
Line 1,841 ⟶ 1,903:
onSaveFailure: null,
onLookupCreationSuccess: null,
onMoveSuccess: null,
onMoveFailure: null,
Line 1,860 ⟶ 1,921:
moveApi: null,
moveProcessApi: 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}
*/
this.load = function(onSuccess, onFailure) {
Line 1,895 ⟶ 1,950:
ctx.loadQuery = {
prop: 'info|revisions',
inprop: 'watched',
Line 1,922 ⟶ 1,977:
}
if (Morebits.userIsSysop) {
ctx.loadQuery.inprop
}
ctx.loadApi = new Morebits.wiki.api
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
*
* Warning: Calling
*
* In this case, callers must make the same edit to the new pageText and reinvoke save().
*
* @param {Function} [onSuccess] - callback function which is called when the save has
* succeeded (optional)
* @param {Function} [
* (optional)
*/
this.save = function(onSuccess, onFailure) {
Line 1,947 ⟶ 2,002:
ctx.onSaveFailure = onFailure || emptyFunction;
// are we getting our
var canUseMwUserToken = fnCanUseMwUserToken('edit');
Line 1,956 ⟶ 2,011:
}
if (!ctx.editSummary) {
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 +
'. \n\nसंपादन जारी रखने के लिए ओके करें, रद्द करने के लिए कैसिल करें।')) {
ctx.statusElement.error('पूर्ण सुरक्षित पृष्ठ पर संपादन छोड़ दिया गया');
ctx.onSaveFailure(this);
return;
Line 1,993 ⟶ 2,033:
summary: ctx.editSummary,
token: canUseMwUserToken ? mw.user.tokens.get('csrfToken') : ctx.csrfToken,
watchlist: ctx.watchlistOption
};
if (typeof ctx.pageSection === 'number') {
Line 2,015 ⟶ 2,047:
}
// Set bot edit attribute. If this
if (ctx.botEdit) {
query.bot = true;
Line 2,022 ⟶ 2,054:
switch (ctx.editMode) {
case 'append':
query.appendtext = ctx.appendText; // use mode to append to current page contents
break;
case 'prepend':
query.prependtext = ctx.prependText; // use mode to prepend to current page contents
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:
query.text = ctx.pageText; // replace entire contents of the page
if (ctx.lastEditTime) {
Line 2,072 ⟶ 2,084:
}
ctx.saveApi = new Morebits.wiki.api
ctx.saveApi.setParent(this);
ctx.saveApi.post();
Line 2,078 ⟶ 2,090:
/**
* Adds the text provided via
*
* @param {Function} [onSuccess] - callback function which is called when the method has succeeded (optional)
* @param {Function} [onFailure] - callback function which is called when the method fails (optional)
*/
this.append = function(onSuccess, onFailure) {
Line 2,098 ⟶ 2,108:
/**
* Adds the text provided via
*
* @param {Function} [onSuccess] - callback function which is called when the method has succeeded (optional)
* @param {Function} [onFailure] - callback function which is called when the method fails (optional)
*/
this.prepend = function(onSuccess, onFailure) {
Line 2,117 ⟶ 2,125:
};
/** @returns {string} string containing the name of the loaded page, including the namespace */
this.getPageName = function() {
return ctx.pageName;
};
/** @returns {string}
this.getPageText = function() {
return ctx.pageText;
};
/** @param {string} pageText -
this.setPageText = function(pageText) {
ctx.editMode = 'all';
Line 2,156 ⟶ 2,141:
};
/** @param {string} appendText -
this.setAppendText = function(appendText) {
ctx.editMode = 'append';
Line 2,162 ⟶ 2,147:
};
/** @param {string} prependText -
this.setPrependText = function(prependText) {
ctx.editMode = 'prepend';
ctx.prependText = prependText;
};
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 */
this.setEditSummary = function(summary) {
ctx.editSummary = summary;
Line 2,197 ⟶ 2,162:
/**
* @param {string} createOption - 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 retrieving the edit token and saving the edit (default)
*
*/
Line 2,223 ⟶ 2,175:
};
/** @param {boolean} minorEdit -
this.setMinorEdit = function(minorEdit) {
ctx.minorEdit = minorEdit;
};
/** @param {boolean} botEdit -
this.setBotEdit = function(botEdit) {
ctx.botEdit = botEdit;
Line 2,234 ⟶ 2,186:
/**
* @param {number} pageSection -
* If specified as `null`, the entire page will be retrieved.
*/
Line 2,242 ⟶ 2,194:
/**
* @param {number} maxConflictRetries -
* loss of edit token. Default: 2
*/
this.setMaxConflictRetries = function(maxConflictRetries) {
Line 2,250 ⟶ 2,202:
/**
* @param {number} maxRetries -
* loss of edit token. Default: 2
*/
this.setMaxRetries = function(maxRetries) {
Line 2,258 ⟶ 2,210:
/**
* @param {boolean} watchlistOption
* True - page will be added to the user's watchlist when save() is called
* False - watchlist status of the page will not be changed (default)
*/
this.setWatchlist = function(watchlistOption
if (watchlistOption
ctx.watchlistOption =
} else {
ctx.watchlistOption = 'nochange';
}
};
/**
* @param {boolean} watchlistOption
* True - page watchlist status will be set based on the user's
* preference settings when save() is called.
* False - watchlist status of the page will not be changed (default)
*
* Watchlist notes:
* 1. The MediaWiki API value of 'unwatch', which explicitly removes the page from the
*
* 2. If both
*
* 3. Twinkle modules should use the appropriate preference to set the watchlist options.
* 4. Most Twinkle modules use
* setWatchlistFromPreferences() is only needed for the few Twinkle watchlist preferences
* that accept a string value of
*/
this.setWatchlistFromPreferences = function(watchlistOption) {
if (watchlistOption) {
ctx.watchlistOption = 'preferences';
Line 2,379 ⟶ 2,247:
/**
* @param {boolean}
*
* In the event of a redirect, a message is displayed to the user and
* the redirect target can be retrieved with getPageName().
*
*/
this.setFollowRedirect = function(followRedirect
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;
};
// lookup-creation setter function
/**
* @param {boolean} flag -
*
*
* Warning:
* 1. If there are no revisions among the first 50 that are non-redirects, or if there are
*
* 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
this.setEditProtection = function(level, expiry) {
ctx.protectEdit = { level: level, expiry: expiry
};
this.setMoveProtection = function(level, expiry) {
ctx.protectMove = { level: level, expiry: expiry
};
this.setCreateProtection = function(level, expiry) {
ctx.protectCreate = { level: level, expiry: expiry
};
Line 2,468 ⟶ 2,325:
};
/** @returns {string}
this.getCurrentID = function() {
return ctx.revertCurID;
};
/** @returns {string}
this.getRevisionUser = function() {
return ctx.revertUser;
};
Line 2,486 ⟶ 2,338:
/**
*
*
*
* allow a caller to pass the proper context into its callback function.
*
*
*
*/
this.setCallbackParameters = function(callbackParameters) {
Line 2,502 ⟶ 2,351:
/**
* @returns
*/
this.getCallbackParameters = function() {
Line 2,509 ⟶ 2,358:
/**
* @
*/
this.getStatusElement = function() {
Line 2,522 ⟶ 2,364:
};
this.setFlaggedRevs = function(level, expiry) {
ctx.flaggedRevs = { level: level, expiry: expiry
};
/**
* @returns {boolean}
*/
this.exists = function() {
Line 2,539 ⟶ 2,377:
/**
* @returns {string}
*/
this.getLoadTime = function() {
Line 2,573 ⟶ 2,384:
/**
* @returns {string}
*/
this.getCreator = function() {
Line 2,580 ⟶ 2,391:
/**
* @returns {string}
*/
this.getCreationTimestamp = function() {
return ctx.timestamp;
};
/**
* Retrieves the username of the user who created the page as well as
* the timestamp of creation
* @param {Function} onSuccess - callback function (required) 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
*/
this.lookupCreation = function(onSuccess
if (!onSuccess) {
ctx.statusElement.error('Internal error: no onSuccess callback provided to lookupCreation()!');
return;
}
ctx.onLookupCreationSuccess = onSuccess;
var query = {
'action': 'query',
'prop': 'revisions',
'titles': ctx.pageName,
'rvlimit': 1,
'rvprop': 'user|timestamp',
'rvdir': 'newer'
};
Line 2,636 ⟶ 2,435:
}
ctx.lookupCreationApi = new Morebits.wiki.api
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);
};
/**
*
*/
this.patrol = function() {
// There's no patrol link on page, so we can't patrol
if (!$('.patrollink').length) {
return;
}
// Extract the rcid token from the "Mark page as patrolled" link on page
var patrolhref = $('.patrollink a').attr('href'),
rcid = mw.util.getParamValue('rcid', patrolhref);
if (rcid) {
var patrolstat = new Morebits.status('पृष्ठ को जाँचा हुआ चिह्नित किया जा रहा');
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} [
*/
this.move = function(onSuccess, onFailure) {
Line 2,671 ⟶ 2,504:
ctx.onMoveFailure = onFailure || emptyFunction;
if (!
ctx.statusElement.error('Internal error: move reason not set before move (use setEditSummary function)!');
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 = {
action: 'query',
prop: 'info',
titles: ctx.pageName
};
if (ctx.followRedirect) {
query.redirects = ''; // follow all redirects
}
if (Morebits.userIsSysop) {
query.inprop = 'protection';
}
ctx.moveApi = new Morebits.wiki.api('स्थानान्तरण टोकन प्राप्त किया जा रहा...', query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
ctx.moveApi.setParent(this);
ctx.moveApi.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} [
*/
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 (!Morebits.userIsSysop) {
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 =
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
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} [
*/
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 (!Morebits.userIsSysop) {
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 =
action: 'query',
prop: 'info',
inprop: 'protection',
intoken: 'undelete',
titles: ctx.pageName
};
ctx.undeleteApi = new Morebits.wiki.api
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} [
*/
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 (!Morebits.userIsSysop) {
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
//
var query = {
action: 'query',
prop: 'info',
inprop: 'protection',
intoken: 'protect',
titles: ctx.pageName,
watchlist: ctx.watchlistOption
};
if (ctx.followRedirect) {
query.redirects = ''; // follow all redirects
}
ctx.protectApi = new Morebits.wiki.api
ctx.protectApi.setParent(this);
ctx.protectApi.post();
Line 2,853 ⟶ 2,659:
/**
* Apply FlaggedRevs protection-style settings
*
*
* @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 (!Morebits.userIsSysop) {
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 = {
action: 'query',
prop: 'info|flagged',
intoken: 'edit',
titles: ctx.pageName
};
if (ctx.followRedirect) {
query.redirects = ''; // follow all redirects
}
};
Line 2,894 ⟶ 2,707:
/**
* Determines whether we can save an API call by using the
*
*
* Currently only used for
*
* @param {string}
* @returns {boolean}
*/
var fnCanUseMwUserToken = function(action) {
// API-based redirect resolution only works for action=query and
// action=edit in append/prepend modes (and section=new, but we don't
// really support that)
if (ctx.followRedirect && (action !== 'edit' ||
(ctx.editMode !== 'append' && ctx.editMode !== 'prepend'))) {
return false;
}
// do we need to fetch the edit protection expiry?
if (Morebits.userIsSysop && !ctx.suppressProtectWarning) {
// poor man's normalisation
if (Morebits.string.toUpperCaseFirstChar(mw.config.get('wgPageName')).replace(/ /g, '_').trim() !==
Morebits.string.toUpperCaseFirstChar(ctx.pageName).replace(/ /g, '_').trim()) {
return false;
}
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
var fnAutoSave = function(pageobj) {
pageobj.save(ctx.onSaveSuccess, ctx.onSaveFailure);
Line 2,986 ⟶ 2,748:
// callback from loadApi.post()
var fnLoadSuccess = function() {
var
if (!fnCheckPageName(
return; // abort
}
ctx.pageExists = $(xml).find('page').attr('missing') !== '';
if (ctx.pageExists) {
ctx.pageText = $(xml).find('rev').text();
} else {
ctx.pageText = ''; // allow for concatenation, etc.
}
// 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
ctx.onLoadFailure(this);
return;
}
ctx.loadTime =
// 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('
ctx.onLoadFailure(this);
return;
}
ctx.lastEditTime = $(xml).find('rev').attr('timestamp');
ctx.
if (ctx.editMode === 'revert') {
ctx.revertCurID = $(xml).find('rev
if (!ctx.revertCurID) {
ctx.statusElement.error('
ctx.onLoadFailure(this);
return;
}
ctx.revertUser = $(xml).find('rev
if (!ctx.revertUser) {
if ($(xml).find('rev
ctx.revertUser = '<username hidden>';
} else {
Line 3,060 ⟶ 2,807:
}
// set revert edit summary
ctx.editSummary =
}
Line 3,070 ⟶ 2,817:
// helper function to parse the page name returned from the API
var fnCheckPageName = function(
if (!onFailure) {
onFailure = emptyFunction;
}
// check for invalid titles
if ($(xml).find('page').attr('invalid') === '') {
ctx.statusElement.error('The page title is invalid: ' + ctx.pageName);
onFailure(this);
return false; // abort
}
var resolvedName = $(xml).find('page').attr('title');
if ($(xml).find('redirects').length > 0) {
Morebits.status.info('Info', 'Redirected from ' + ctx.pageName + ' to ' + resolvedName);
}
ctx.pageName = resolvedName; // always update in case of normalization
} else {
// could be a circular redirect or other problem
ctx.statusElement.error
onFailure(this);
Line 3,115 ⟶ 2,850:
};
// helper function to get a new token on encountering token errors
// in save, deletePage, and undeletePage
// Being a synchronous ajax call, this blocks the event loop,
// and hence should be used sparingly.
var fnGetToken = function() {
var token;
var tokenApi = new Morebits.wiki.api('टोकन प्राप्त किया जा रहा', {
action: 'query',
meta: 'tokens'
}, function(apiobj) {
token = $(apiobj.responseXML).find('tokens').attr('csrftoken');
this.getStatusElement().error('टोकन प्राप्त करने में विफल');
});
tokenApi.post({async: false});
return token;
};
// callback from saveApi.post()
var fnSaveSuccess = function() {
ctx.editMode = 'all'; // cancel append/prepend
var
// see if the API thinks we were successful
if (
// real success
Line 3,170 ⟶ 2,881:
link.setAttribute('href', mw.util.getUrl(ctx.pageName));
link.appendChild(document.createTextNode(ctx.pageName));
ctx.statusElement.info(['
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 (
ctx.statusElement.error('Could not save the page because the wiki server wanted you to fill out a CAPTCHA.');
} else {
ctx.statusElement.error
}
Line 3,204 ⟶ 2,915:
};
var purgeApi = new Morebits.wiki.api
purgeApi.post({ async: false }); // just wait for it, result is for debugging
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.statusElement.info('Edit conflict detected, reapplying edit');
if (fnCanUseMwUserToken('edit')) {
ctx.loadApi.post(); // reload the page and reapply the edit
}
// 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
// the error might be transient, so try again
ctx.statusElement.info
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
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
if (errorCode === 'protectedpage') {
ctx.statusElement.error('Failed to save edit: Page is protected');
// check for absuefilter hits: disallowed or warning
} else if (errorCode.indexOf('abusefilter') === 0) {
var desc = $(ctx.saveApi.getXML()).find('abusefilter').attr('description');
if (errorCode === 'abusefilter-disallowed') {
ctx.statusElement.error('संपादन फिल्टर द्वारा रोका गया: "' + desc + '".');
} else if (errorCode === 'abusefilter-warning') {
ctx.statusElement.error([ 'संपादन फिल्टर द्वारा जारी चेतावनी: "', desc, '"।यदि आप फिर भी संपादन करना चाहते हैं, कृपया दुबारा प्रयत्न करें। यह चेतावनी दुबारा नहीं दिखाई जायेगी।' ]);
// 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...
ctx.statusElement.error('संपादन को फिल्टर द्वारा रोका गया, अनुमति नहीं है।');
}
// check for blacklist hits
// .find('matches') returns an array in case multiple items are blacklisted, we only return the first
var spam = $(ctx.saveApi.getXML()).find('spamblacklist').find('matches').children()[0].textContent;
ctx.statusElement.error('पृष्ठ सहेजा नहीं जा सका क्योंकि यूआरएल ' + spam + ' स्पैम रोकने हेतु स्थापित काली सूची में आता है।');
}
ctx.editMode = 'all'; // cancel append/prepend/revert modes
if (ctx.onSaveFailure) {
ctx.onSaveFailure(this); // invoke callback
}
}
};
var fnLookupCreationSuccess = function() {
var
if (!fnCheckPageName(
return; // abort
}
if (!ctx.lookupNonRedirectCreator || !/^\s*#redirect/i.test($(xml).find('rev').text())) {
ctx.creator = $(xml).find('rev').attr('user');
if (!ctx.creator) {
ctx.statusElement.error('
return;
}
ctx.timestamp = $(xml).find('rev').attr('timestamp');
if (!ctx.timestamp) {
ctx.statusElement.error('
return;
}
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.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
Line 3,318 ⟶ 3,009:
var fnLookupNonRedirectCreator = function() {
var
$(xml).find('rev').each(function(_, rev) {
if (!/^\s*#redirect/i.test(rev.textContent)) { // inaccessible revisions also check out
ctx.creator = rev.getAttribute('user');
ctx.
return false; // break
}
});
if (!ctx.creator) {
// fallback to give first revision author if no non-redirect version in the first 50
ctx.creator =
ctx.timestamp =
if (!ctx.creator) {
ctx.statusElement.error('Could not find name of page creator');
return;
}
Line 3,343 ⟶ 3,031:
if (!ctx.timestamp) {
ctx.statusElement.error('Could not find timestamp of page creation');
return;
}
ctx.onLookupCreationSuccess(this);
};
var fnProcessMove = function() {
var xml = ctx.moveApi.getXML();
if ($(xml).find('page').attr('missing') === '') {
ctx.statusElement.error('
return
}
// extract protection info
if (Morebits.userIsSysop) {
var editprot = $(xml).find('pr[type="edit"]');
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
!confirm('You are about to move the fully protected page "' + ctx.pageName +
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + editprot.attr('expiry') + ')') +
'. \n\nClick OK to proceed with the move, or Cancel to skip this move.')) {
ctx.statusElement.error('Move of fully protected page was aborted.');
ctx.onMoveFailure(this);
}
}
var moveToken = $(xml).find('page').attr('movetoken');
if (!moveToken) {
ctx.statusElement.error('Failed to retrieve move token.');
ctx.onMoveFailure(this);
return;
}
var query = {
'action': 'move',
'from':
'to': ctx.moveDestination,
'token':
'reason': ctx.editSummary
};
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
ctx.moveProcessApi.setParent(this);
ctx.moveProcessApi.post();
};
var
var
if (fnCanUseMwUserToken('delete')) {
token = mw.user.tokens.get('csrfToken');
} else {
var
if ($(xml).find('page').attr('missing') === '') {
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
ctx.onDeleteFailure(this);
return;
}
// extract protection info
var editprot = $(xml).find('pr[type="edit"]');
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;
}
if (!token) {
ctx.statusElement.error('Failed to retrieve delete token.');
ctx.onDeleteFailure(this);
return;
}
}
var query = {
'action': '
'token': token,
'reason': ctx.editSummary
};
if (ctx.watchlistOption === 'watch') {
query.watch = 'true';
}
ctx.deleteProcessApi = new Morebits.wiki.api('
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
if ($(xml).find('page').attr('missing') !== '') {
ctx.statusElement.error('Cannot undelete the page, because it already exists');
ctx.onUndeleteFailure(this);
return;
}
// extract protection info
var
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
!confirm('You are about to undelete the fully create protected page "' + ctx.pageName +
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + 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
};
if (ctx.
query.
}
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');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.undeleteProcessApi.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.undeleteProcessApi.query.token = fnGetToken.call(this);
ctx.undeleteProcessApi.post();
} 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
var missing = $(xml).find('page').attr('missing') === '';
if ((ctx.protectEdit || ctx.protectMove) && missing) {
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 protectToken = $(xml).find('page').attr('protecttoken');
if (!protectToken) {
ctx.statusElement.error('Failed to retrieve protect token.');
ctx.onProtectFailure(this);
return;
}
//
var prs = $(xml).find('pr');
var moveprot = prs.filter('[type="move"]');
var createprot = prs.filter('[type="create"]');
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:
token:
protections: protections.join('|'),
expiry: expirys.join('|'),
reason: ctx.editSummary
};
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 missing = $(xml).find('page').attr('missing') === '';
if (missing) {
ctx.statusElement.error('Cannot protect the page, because it no longer exists');
ctx.onStabilizeFailure(this);
return;
}
var stabilizeToken = $(xml).find('tokens').attr('csrftoken');
if (!stabilizeToken) {
ctx.statusElement.error('Failed to retrieve stabilize token.');
ctx.onStabilizeFailure(this);
return;
}
var query = {
action: 'stabilize',
title:
token:
protectlevel: ctx.flaggedRevs.level,
expiry: ctx.flaggedRevs.expiry,
reason: ctx.editSummary
};
if (ctx.watchlistOption === 'watch') {
query.watch = 'true';
}
ctx.stabilizeProcessApi = new Morebits.wiki.api('configuring stabilization settings...', query, ctx.onStabilizeSuccess, ctx.statusElement, ctx.onStabilizeFailure);
Line 3,861 ⟶ 3,365:
ctx.stabilizeProcessApi.post();
};
}; // end Morebits.wiki.page
Line 3,878 ⟶ 3,375:
/**
* **************** Morebits.wiki.preview ****************
* Uses the API to parse a fragment of wikitext and render it as HTML.
*
* The suggested implementation pattern (in
* construct a Morebits.wiki.preview object after rendering a Morebits.quickForm, and bind the object
* to an arbitrary property of the form (e.g. |previewer|). For an example, see
* twinklewarn.js.
*/
/**
* @
* @param {HTMLElement} previewbox -
* 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}
*/
this.beginRender = function(wikitext, pageTitle
$(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')
};
var renderApi = new Morebits.wiki.api('लोड किया जा रहा...', query, fnRenderSuccess, new Morebits.status('Preview'));
renderApi.post();
};
var fnRenderSuccess = function(apiobj) {
var
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 ****************
* Wikitext manipulation
*/
Morebits.wikitext = {};
Morebits.wikitext.template = {
parse: function(text, start) {
var count = -1;
var level = -1;
var equals = -1;
var current = '';
var result = {
name: '',
parameters: {}
};
var key, value;
for (var i = start; i < text.length; ++i) {
var test3 = text.substr(i, 3);
if (test3 === '{{{') {
current += '{{{';
++level;
continue;
}
if (test3 === '}}}') {
current += '}}}';
i += 2;
--level;
continue;
}
var test2 = text.substr(i, 2);
if (test2 === '{{' || test2 === '[[') {
current += test2;
++i;
++level;
continue;
}
if (test2 === ']]') {
current += ']]';
++i;
--level;
continue;
}
if (test2 === '}}') {
current += test2;
++i;
--level;
if (level <= 0) {
if (count === -1) {
result.name = current.substring(2).trim();
++count;
} else {
if (equals !== -1) {
key = current.substring(0, equals).trim();
value = current.substring(equals).trim();
result.parameters[key] = value;
equals = -1;
result.parameters[count] = current;
++count;
}
}
break;
}
continue;
}
if (count === -1) {
result.name = current.substring(2).trim();
if (
key = current.substring(0, equals).trim();
value = current.substring(equals + 1).trim();
result.parameters[key] = value;
equals = -1;
} else {
result.parameters[count] = current;
++count;
}
}
current = '';
} else if (equals === -1 && text.charAt(i) === '=' && level <= 0) {
equals = current.length;
current += text.charAt(i);
} else {
}
}
return result;
}
};
/**
* @constructor
* @param {string} text
*/
Morebits.wikitext.page = function mediawikiPage(text) {
Line 4,081 ⟶ 3,550:
/**
* Removes links to `link_target` from the page text.
* @param {string} link_target
*/
removeLink: function(link_target) {
var first_char = link_target.substr(0, 1);
var link_re_string = '[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExp.escape(link_target.substr(1), true);
// Files and Categories become links with a leading colon, e.g. [[:File:Test.png]]
// Otherwise, allow for an optional leading colon, e.g. [[:User:Test]]
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');
},
/**
* Comments out images from page text
* If used as a template argument (not necessarily with
* @param {string} image - Image name without File: prefix
* @param {string}
*/
commentOutImage: function(image, reason) {
Line 4,124 ⟶ 3,577:
reason = reason ? reason + ': ' : '';
var
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('\\[\\[
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*
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
// Will only eat the image name and the
var free_image_re = new RegExp('(\\|\\s*(?:[\\w\\s]+\\=)?\\s*(?:
unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->');
// Rebind the content now, we are done!
this.text = unbinder.rebind();
},
/**
* Converts
* @param {string} image - Image name without File: prefix
* @param {string}
*/
addToImageComment: function(image, data) {
var
var first_char_regex = RegExp.escape(first_char, true);
if (first_char.toUpperCase() !== first_char.toLowerCase()) {
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);
},
/**
*
* @param {string} template - Page name whose transclusions are to be removed,
* include namespace prefix only if not in template namespace
*/
removeTemplate: function(template) {
var
var template_re_string = '(?:[Tt]emplate:)?\\s*[' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExp.escape(template.substr(1), true);
var links_re = new RegExp('\\{\\{' + template_re_string);
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');
}
}
},
/** @returns {string} */
getText: function() {
return this.text;
Line 4,279 ⟶ 3,660:
};
/**
* **************** Morebits.status ****************
*/
/**
* @constructor
*
*
* @param {String} text - Text before the the colon `:`
* @param {String} stat - Text after the colon `:`
* @param {String} [type=status] - This parameter determines the font color of the status line,
* this can be 'status' (blue), 'info' (green), 'warn' (red), or 'error' (bold red)
* The default is 'status'
*/
Morebits.status = function Status(text, stat, type) {
this.textRaw = text;
this.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
*/
Morebits.status.init = function(root) {
Line 4,387 ⟶ 3,702:
Morebits.status.root = null;
/** @param {Function} handler - function to execute on error */
Morebits.status.onError = function(handler) {
if (typeof handler === 'function') {
Line 4,402 ⟶ 3,713:
Morebits.status.prototype = {
stat: 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:
/**
*
* @param {(string|Element|Array)} obj
* @returns {DocumentFragment}
*/
codify: function(obj) {
if (!Array.isArray(obj)) {
obj = [ obj ];
}
var result;
result = document.createDocumentFragment();
for (var i = 0; i < obj.length; ++i) {
if (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.
if (type) {
this.type = type;
Line 4,448 ⟶ 3,777:
// also log error messages in the browser console
console.error(this.textRaw + ': ' +
}
}
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 = '
while (this.target.hasChildNodes()) {
this.target.removeChild(this.target.firstChild);
Line 4,485 ⟶ 3,814:
}
};
Morebits.status.info = function(text, status) {
return new Morebits.status(text, status, 'info');
};
Morebits.status.warn = function(text, status) {
return new Morebits.status(text, status, 'warn');
};
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
*/
Morebits.status.actionCompleted = function(text) {
var node = document.createElement('div');
node.appendChild(document.createElement('
node.className = '
if (Morebits.status.root) {
Morebits.status.root.appendChild(node);
Line 4,539 ⟶ 3,842:
/**
* Display the user's rationale, comments, etc.
* so that they may re-use it
* @param {string} comments
* @param {string} message
Line 4,561 ⟶ 3,862:
/**
* **************** Morebits.htmlNode() ****************
* Simple helper function to create a simple node
* @param {string} type -
* @param {string}
* @param {string} [color] -
* @returns {HTMLElement}
*/
Line 4,580 ⟶ 3,881:
/**
* **************** Morebits.checkboxShiftClickSupport() ****************
* shift-click-support for checkboxes
* wikibits version (window.addCheckboxClickHandlers) has some restrictions, and
* doesn't work with checkboxes inside a sortable table, so let's build our own.
*/
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(wikitext): Sets the list of pages to work on.
* It should be an array of page names (strings).
*
* setOption(optionName, optionValue): Sets a known option:
* - chunkSize (integer): the size of chunks to break the array into (default 50).
* Setting this to a small value (<5) can cause problems.
* - preserveIndividualStatusLines (boolean): keep each page's status element visible
* when worker is complete? See note below
*
* run(worker, postFinish): Runs the callback `worker` for each page in the list.
* The callback must call workerSuccess when succeeding, or workerFailure
* when failing. If using Morebits.wiki.api or Morebits.wiki.page, this is easily
* done by passing these two 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.
*
* 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.
*/
/**
* @constructor
* @param {string} [currentAction]
*/
Line 4,686 ⟶ 3,986:
// internal counters, etc.
statusElement: new Morebits.status(currentAction ||
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
* 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).
* Setting this to a small value (<5) can cause problems.
* - preserveIndividualStatusLines (boolean):
*
*/
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
* @param {Function} worker
* @param {Function} [postFinish]
Line 4,753 ⟶ 4,047:
var total = ctx.pageList.length;
if (!total) {
ctx.statusElement.info
ctx.running = false;
if (ctx.postFinish) {
Line 4,771 ⟶ 4,065:
/**
* To be called by worker before it terminates
* @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 (
* `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(
} else {
// we don't know the page title - just display a generic message
statelem.info
}
} else {
Line 4,799 ⟶ 4,099:
} else if (typeof arg === 'string' && ctx.options.preserveIndividualStatusLines) {
new Morebits.status(arg,
}
Line 4,832 ⟶ 4,132:
// update overall status line
var total = ctx.pageList.length;
if (ctx.countFinished
var
'/' + 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;
}
// 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) + '%');
// 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();
};
};
/**
* **************** Morebits.simpleWindow ****************
* A simple draggable window
* now a wrapper for jQuery UI's dialog feature
* @requires {jquery.ui.dialog}
*/
/**
* @constructor
* @param {number} width
* @param {number} height
*/
Morebits.simpleWindow = function SimpleWindow(width, height) {
Line 4,972 ⟶ 4,209:
}
},
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.
* @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
* 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 :
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}
* @param {
* @returns {Morebits.simpleWindow}
*/
Line 5,192 ⟶ 4,422:
if (this.hasFooterLinks) {
var bullet = document.createElement('span');
bullet.textContent =
if (prep) {
$footerlinks.prepend(bullet);
Line 5,214 ⟶ 4,444:
/**
*
*
* interacted with. Modal dialogs create an overlay below the dialog but above
* other page elements.
* This must be used (if necessary) before calling display()
* Default: false
* @param {boolean} modal
* @returns {Morebits.simpleWindow}
*/
Line 5,229 ⟶ 4,460:
/**
* Enables or disables all footer buttons on all
* This should be called with `false` when the button(s) become irrelevant (e.g. just before
*
* This is not an instance method so that consumers don't have to keep a reference to the
* original
* there will only be one
* @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:
|