24use Wikimedia\ScopedCallback;
53 if (
$user->isBot() ) {
54 $this->
dieUsage(
'This interface is not supported for bots',
'botsnotsupported' );
57 $cache = ObjectCache::getLocalClusterInstance();
62 ->isSupportedFormat(
$params[
'contentformat'] )
64 $this->
dieUsage(
'Unsupported content model/format',
'badmodelformat' );
69 if ( strlen(
$params[
'stashedtexthash'] ) ) {
71 $textHash =
$params[
'stashedtexthash'];
72 $textKey =
$cache->makeKey(
'stashedit',
'text', $textHash );
73 $text =
$cache->get( $textKey );
74 if ( !is_string( $text ) ) {
75 $this->
dieUsage(
'No stashed text found with the given hash',
'missingtext' );
77 } elseif (
$params[
'text'] !==
null ) {
79 $text = rtrim( str_replace(
"\r\n",
"\n",
$params[
'text'] ) );
80 $textHash = sha1( $text );
83 'The text or stashedtexthash parameter must be given',
'missingtextparam' );
90 if (
$page->exists() ) {
94 $this->
dieUsage(
"No revision ID {$params['baserevid']}",
'missingrev' );
96 $currentRev =
$page->getRevision();
98 $this->
dieUsage(
"No current revision of page ID {$page->getId()}",
'missingrev' );
101 $editContent =
$page->replaceSectionAtRev(
107 if ( !$editContent ) {
108 $this->
dieUsage(
'Could not merge updated section.',
'replacefailed' );
110 if ( $currentRev->getId() == $baseRev->getId() ) {
115 $baseContent = $baseRev->getContent();
116 $currentContent = $currentRev->getContent();
117 if ( !$baseContent || !$currentContent ) {
118 $this->
dieUsage(
"Missing content for page ID {$page->getId()}",
'missingrev' );
135 ignore_user_abort(
true );
137 if (
$user->pingLimiter(
'stashedit' ) ) {
141 $textKey =
$cache->makeKey(
'stashedit',
'text', $textHash );
142 $cache->set( $textKey, $text, self::MAX_CACHE_TTL );
145 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
146 $stats->increment(
"editstash.cache_stores.$status" );
153 'texthash' => $textHash
167 $cache = ObjectCache::getLocalClusterInstance();
168 $logger = LoggerFactory::getInstance(
'StashEdit' );
175 if ( !$dbw->lock( $key, __METHOD__, 1 ) ) {
180 $unlocker =
new ScopedCallback(
function ()
use ( $dbw, $key ) {
181 $dbw->unlock( $key, __METHOD__ );
187 $editInfo =
$cache->get( $key );
189 $alreadyCached =
true;
191 $format =
$content->getDefaultFormat();
193 $alreadyCached =
false;
196 if ( $editInfo && $editInfo->output ) {
198 Hooks::run(
'ParserOutputStashForEdit',
201 if ( $alreadyCached ) {
202 $logger->debug(
"Already cached parser output for key '$key' ('$title')." );
207 $editInfo->pstContent,
209 $editInfo->timestamp,
214 $ok =
$cache->set( $key, $stashInfo, $ttl );
216 $logger->debug(
"Cached parser output for key '$key' ('$title')." );
219 $logger->error(
"Failed to cache parser output for key '$key' ('$title')." );
223 $logger->info(
"Uncacheable parser output for key '$key' ('$title') [$code]." );
249 if (
$user->isBot() ) {
253 $cache = ObjectCache::getLocalClusterInstance();
254 $logger = LoggerFactory::getInstance(
'StashEdit' );
255 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
258 $editInfo =
$cache->get( $key );
259 if ( !is_object( $editInfo ) ) {
260 $start = microtime(
true );
265 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
266 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
267 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
268 $editInfo =
$cache->get( $key );
269 $dbw->unlock( $key, __METHOD__ );
272 $timeMs = 1000 * max( 0, microtime(
true ) - $start );
273 $stats->timing(
'editstash.lock_wait_time', $timeMs );
276 if ( !is_object( $editInfo ) || !$editInfo->output ) {
277 $stats->increment(
'editstash.cache_misses.no_stash' );
278 $logger->debug(
"Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
283 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
285 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
286 $logger->debug(
"Timestamp-based cache hit for key '$key' (age: $age sec)." );
287 } elseif ( isset( $editInfo->edits ) && $editInfo->edits ===
$user->getEditCount() ) {
289 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
290 $logger->debug(
"Edit count based cache hit for key '$key' (age: $age sec)." );
291 } elseif (
$user->isAnon()
292 && self::lastEditTime(
$user ) < $editInfo->output->getCacheTime()
295 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
296 $logger->debug(
"Edit check based cache hit for key '$key' (age: $age sec)." );
303 $stats->increment(
'editstash.cache_misses.proven_stale' );
304 $logger->info(
"Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
305 } elseif ( $editInfo->output->getFlag(
'vary-revision' ) ) {
308 $logger->info(
"Cache for key '$key' ('$title') has vary_revision." );
309 } elseif ( $editInfo->output->getFlag(
'vary-revision-id' ) ) {
311 $logger->info(
"Cache for key '$key' ('$title') has vary_revision_id." );
325 [
'rc_user_text' =>
$user->getName() ],
339 return sha1( implode(
"\n", [
359 return ObjectCache::getLocalClusterInstance()->makeKey(
361 md5(
$title->getPrefixedDBkey() ),
365 md5(
$user->getId() .
"\n" .
$user->getName() )
386 $ttl = min(
$parserOutput->getCacheExpiry() - $since, self::MAX_CACHE_TTL );
388 return [
null, 0,
'no_ttl' ];
393 'pstContent' => $pstContent,
396 'edits' =>
$user->getEditCount()
399 return [ $stashInfo, $ttl,
'ok' ];
418 'stashedtexthash' => [
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
This abstract class implements many basic API functions, and is the base of all API classes.
const PARAM_REQUIRED
(boolean) Is the parameter required?
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
getResult()
Get the result object.
getModuleName()
Get the name of the module being executed by this instance.
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
dieUsage( $description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Prepare an edit in shared cache so that it can be reused on edit.
const PRESUME_FRESH_TTL_SEC
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
static getStashKey(Title $title, $contentHash, User $user)
Get the temporary prepared edit stash key for a user.
static parseAndStash(WikiPage $page, Content $content, User $user, $summary)
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
static lastEditTime(User $user)
isInternal()
Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party...
static getContentHash(Content $content)
Get hash of the content, factoring in model/format.
needsToken()
Returns the token type this module requires in order to execute.
static buildStashValue(Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user)
Build a value to store in memcached based on the PST content and parser output.
isWriteMode()
Indicates whether this module requires write mode.
static checkCache(Title $title, Content $content, User $user)
Check that a prepared edit is in cache and still up-to-date.
mustBePosted()
Indicates whether this module must be called with a POST request.
static getAllContentFormats()
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
static getContentModels()
getUser()
Get the User object.
static newFromPageId( $pageId, $revId=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given page ID.
Represents a title within MediaWiki.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Class representing a MediaWiki article and history.
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context $parserOutput
see documentation in includes Linker php for Linker::makeImageLink & $time
namespace and then decline to actually register it file or subcat img or subcat $title
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Base interface for content objects.
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)