MediaWiki  master
ApiStashEdit.php
Go to the documentation of this file.
1 <?php
23 
37 class ApiStashEdit extends ApiBase {
38  const ERROR_NONE = 'stashed';
39  const ERROR_PARSE = 'error_parse';
40  const ERROR_CACHE = 'error_cache';
41  const ERROR_UNCACHEABLE = 'uncacheable';
42 
44  const MAX_CACHE_TTL = 300; // 5 minutes
45 
46  public function execute() {
47  $user = $this->getUser();
48  $params = $this->extractRequestParams();
49 
50  if ( $user->isBot() ) { // sanity
51  $this->dieUsage( 'This interface is not supported for bots', 'botsnotsupported' );
52  }
53 
54  $page = $this->getTitleOrPageId( $params );
55  $title = $page->getTitle();
56 
57  if ( !ContentHandler::getForModelID( $params['contentmodel'] )
58  ->isSupportedFormat( $params['contentformat'] )
59  ) {
60  $this->dieUsage( 'Unsupported content model/format', 'badmodelformat' );
61  }
62 
63  // Trim and fix newlines so the key SHA1's match (see RequestContext::getText())
64  $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
65  $textContent = ContentHandler::makeContent(
66  $text, $title, $params['contentmodel'], $params['contentformat'] );
67 
69  if ( $page->exists() ) {
70  // Page exists: get the merged content with the proposed change
71  $baseRev = Revision::newFromPageId( $page->getId(), $params['baserevid'] );
72  if ( !$baseRev ) {
73  $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
74  }
75  $currentRev = $page->getRevision();
76  if ( !$currentRev ) {
77  $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
78  }
79  // Merge in the new version of the section to get the proposed version
80  $editContent = $page->replaceSectionAtRev(
81  $params['section'],
82  $textContent,
83  $params['sectiontitle'],
84  $baseRev->getId()
85  );
86  if ( !$editContent ) {
87  $this->dieUsage( 'Could not merge updated section.', 'replacefailed' );
88  }
89  if ( $currentRev->getId() == $baseRev->getId() ) {
90  // Base revision was still the latest; nothing to merge
91  $content = $editContent;
92  } else {
93  // Merge the edit into the current version
94  $baseContent = $baseRev->getContent();
95  $currentContent = $currentRev->getContent();
96  if ( !$baseContent || !$currentContent ) {
97  $this->dieUsage( "Missing content for page ID {$page->getId()}", 'missingrev' );
98  }
99  $handler = ContentHandler::getForModelID( $baseContent->getModel() );
100  $content = $handler->merge3( $baseContent, $editContent, $currentContent );
101  }
102  } else {
103  // New pages: use the user-provided content model
104  $content = $textContent;
105  }
106 
107  if ( !$content ) { // merge3() failed
108  $this->getResult()->addValue( null,
109  $this->getModuleName(), [ 'status' => 'editconflict' ] );
110  return;
111  }
112 
113  // The user will abort the AJAX request by pressing "save", so ignore that
114  ignore_user_abort( true );
115 
116  // Use the master DB for fast blocking locks
117  $dbw = wfGetDB( DB_MASTER );
118 
119  // Get a key based on the source text, format, and user preferences
120  $key = self::getStashKey( $title, $content, $user );
121  // De-duplicate requests on the same key
122  if ( $user->pingLimiter( 'stashedit' ) ) {
123  $status = 'ratelimited';
124  } elseif ( $dbw->lock( $key, __METHOD__, 1 ) ) {
125  $status = self::parseAndStash( $page, $content, $user, $params['summary'] );
126  $dbw->unlock( $key, __METHOD__ );
127  } else {
128  $status = 'busy';
129  }
130 
131  $this->getStats()->increment( "editstash.cache_stores.$status" );
132 
133  $this->getResult()->addValue( null, $this->getModuleName(), [ 'status' => $status ] );
134  }
135 
146  $logger = LoggerFactory::getInstance( 'StashEdit' );
147 
148  $format = $content->getDefaultFormat();
149  $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
150  $title = $page->getTitle();
151 
152  if ( $editInfo && $editInfo->output ) {
153  $key = self::getStashKey( $title, $content, $user );
154 
155  // Let extensions add ParserOutput metadata or warm other caches
156  Hooks::run( 'ParserOutputStashForEdit',
157  [ $page, $content, $editInfo->output, $summary, $user ] );
158 
159  list( $stashInfo, $ttl, $code ) = self::buildStashValue(
160  $editInfo->pstContent,
161  $editInfo->output,
162  $editInfo->timestamp,
163  $user
164  );
165 
166  if ( $stashInfo ) {
167  $ok = $cache->set( $key, $stashInfo, $ttl );
168  if ( $ok ) {
169  $logger->debug( "Cached parser output for key '$key' ('$title')." );
170  return self::ERROR_NONE;
171  } else {
172  $logger->error( "Failed to cache parser output for key '$key' ('$title')." );
173  return self::ERROR_CACHE;
174  }
175  } else {
176  $logger->info( "Uncacheable parser output for key '$key' ('$title') [$code]." );
177  return self::ERROR_UNCACHEABLE;
178  }
179  }
180 
181  return self::ERROR_PARSE;
182  }
183 
201  public static function checkCache( Title $title, Content $content, User $user ) {
202  if ( $user->isBot() ) {
203  return false; // bots never stash - don't pollute stats
204  }
205 
207  $logger = LoggerFactory::getInstance( 'StashEdit' );
208  $stats = RequestContext::getMain()->getStats();
209 
210  $key = self::getStashKey( $title, $content, $user );
211  $editInfo = $cache->get( $key );
212  if ( !is_object( $editInfo ) ) {
213  $start = microtime( true );
214  // We ignore user aborts and keep parsing. Block on any prior parsing
215  // so as to use its results and make use of the time spent parsing.
216  // Skip this logic if there no master connection in case this method
217  // is called on an HTTP GET request for some reason.
218  $lb = wfGetLB();
219  $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
220  if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
221  $editInfo = $cache->get( $key );
222  $dbw->unlock( $key, __METHOD__ );
223  }
224 
225  $timeMs = 1000 * max( 0, microtime( true ) - $start );
226  $stats->timing( 'editstash.lock_wait_time', $timeMs );
227  }
228 
229  if ( !is_object( $editInfo ) || !$editInfo->output ) {
230  $stats->increment( 'editstash.cache_misses.no_stash' );
231  $logger->debug( "Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
232  return false;
233  }
234 
235  $age = time() - wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
236  if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
237  // Assume nothing changed in this time
238  $stats->increment( 'editstash.cache_hits.presumed_fresh' );
239  $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
240  } elseif ( isset( $editInfo->edits ) && $editInfo->edits === $user->getEditCount() ) {
241  // Logged-in user made no local upload/template edits in the meantime
242  $stats->increment( 'editstash.cache_hits.presumed_fresh' );
243  $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
244  } elseif ( $user->isAnon()
245  && self::lastEditTime( $user ) < $editInfo->output->getCacheTime()
246  ) {
247  // Logged-out user made no local upload/template edits in the meantime
248  $stats->increment( 'editstash.cache_hits.presumed_fresh' );
249  $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
250  } else {
251  // User may have changed included content
252  $editInfo = false;
253  }
254 
255  if ( !$editInfo ) {
256  $stats->increment( 'editstash.cache_misses.proven_stale' );
257  $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
258  } elseif ( $editInfo->output->getFlag( 'vary-revision' ) ) {
259  // This can be used for the initial parse, e.g. for filters or doEditContent(),
260  // but a second parse will be triggered in doEditUpdates(). This is not optimal.
261  $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
262  } elseif ( $editInfo->output->getFlag( 'vary-revision-id' ) ) {
263  // Similar to the above if we didn't guess the ID correctly.
264  $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
265  }
266 
267  return $editInfo;
268  }
269 
274  private static function lastEditTime( User $user ) {
275  $time = wfGetDB( DB_SLAVE )->selectField(
276  'recentchanges',
277  'MAX(rc_timestamp)',
278  [ 'rc_user_text' => $user->getName() ],
279  __METHOD__
280  );
281 
282  return wfTimestampOrNull( TS_MW, $time );
283  }
284 
297  private static function getStashKey( Title $title, Content $content, User $user ) {
298  $hash = sha1( implode( ':', [
299  // Account for the edit model/text
300  $content->getModel(),
301  $content->getDefaultFormat(),
302  sha1( $content->serialize( $content->getDefaultFormat() ) ),
303  // Account for user name related variables like signatures
304  $user->getId(),
305  md5( $user->getName() )
306  ] ) );
307 
308  return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
309  }
310 
322  private static function buildStashValue(
324  ) {
325  // If an item is renewed, mind the cache TTL determined by config and parser functions.
326  // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
327  $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
328  $ttl = min( $parserOutput->getCacheExpiry() - $since, self::MAX_CACHE_TTL );
329  if ( $ttl <= 0 ) {
330  return [ null, 0, 'no_ttl' ];
331  }
332 
333  // Only store what is actually needed
334  $stashInfo = (object)[
335  'pstContent' => $pstContent,
336  'output' => $parserOutput,
337  'timestamp' => $timestamp,
338  'edits' => $user->getEditCount()
339  ];
340 
341  return [ $stashInfo, $ttl, 'ok' ];
342  }
343 
344  public function getAllowedParams() {
345  return [
346  'title' => [
347  ApiBase::PARAM_TYPE => 'string',
349  ],
350  'section' => [
351  ApiBase::PARAM_TYPE => 'string',
352  ],
353  'sectiontitle' => [
354  ApiBase::PARAM_TYPE => 'string'
355  ],
356  'text' => [
357  ApiBase::PARAM_TYPE => 'text',
359  ],
360  'summary' => [
361  ApiBase::PARAM_TYPE => 'string',
362  ],
363  'contentmodel' => [
364  ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
366  ],
367  'contentformat' => [
368  ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
370  ],
371  'baserevid' => [
372  ApiBase::PARAM_TYPE => 'integer',
374  ]
375  ];
376  }
377 
378  public function needsToken() {
379  return 'csrf';
380  }
381 
382  public function mustBePosted() {
383  return true;
384  }
385 
386  public function isWriteMode() {
387  return true;
388  }
389 
390  public function isInternal() {
391  return true;
392  }
393 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:101
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
getStats()
Get the Stats object.
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
Definition: deferred.txt:11
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
getResult()
Get the result object.
Definition: ApiBase.php:577
serialize($format=null)
Convenience method for serializing this Content object.
Prepare an edit in shared cache so that it can be reused on edit.
static checkCache(Title $title, Content $content, User $user)
Check that a prepared edit is in cache and still up-to-date.
static parseAndStash(WikiPage $page, Content $content, User $user, $summary)
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:112
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:678
static getLocalClusterInstance()
Get the main cluster-local cache object.
Represents a title within MediaWiki.
Definition: Title.php:36
static newFromPageId($pageId, $revId=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given page ID...
Definition: Revision.php:148
const MAX_CACHE_TTL
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
Definition: globals.txt:25
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2139
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1629
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
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
Definition: hooks.txt:1816
getTitleOrPageId($params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition: ApiBase.php:800
getCacheExpiry()
Returns the number of seconds after which this object should expire.
Definition: CacheTime.php:110
wfGetLB($wiki=false)
Get a load balancer object.
static getMain()
Static methods.
const ERROR_NONE
isAnon()
Get whether the user is anonymous.
Definition: User.php:3521
if($limit) $timestamp
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
Definition: hooks.txt:1020
$summary
Base interface for content objects.
Definition: Content.php:34
$cache
Definition: mcc.php:33
$params
getTitle()
Get the title object of the article.
Definition: WikiPage.php:213
const DB_SLAVE
Definition: Defines.php:46
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:312
const ERROR_PARSE
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:457
const ERROR_CACHE
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
isBot()
Definition: User.php:3529
static lastEditTime(User $user)
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
Definition: hooks.txt:776
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
Definition: hooks.txt:242
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Class representing a MediaWiki article and history.
Definition: WikiPage.php:31
prepareContentForEdit(Content $content, $revision=null, User $user=null, $serialFormat=null, $useCache=true)
Prepare content which is about to be saved.
Definition: WikiPage.php:2025
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
Definition: injection.txt:35
getId()
Get the user's ID.
Definition: User.php:2114
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
Definition: hooks.txt:1020
const ERROR_UNCACHEABLE
getEditCount()
Get the user's edit count.
Definition: User.php:3403
static buildStashValue(Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user)
Build a value to store in memcached based on the PST content and parser output.
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...
Definition: ApiBase.php:1481
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
Definition: hooks.txt:1020
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
wfMemcKey()
Make a cache key for the local wiki.
const DB_MASTER
Definition: Defines.php:47
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
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
Definition: hooks.txt:776
getModel()
Returns the ID of the content model used by this Content object.
wfTimestampOrNull($outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
getUser()
Get the User object.
getDefaultFormat()
Convenience method that returns the default serialization format for the content model that this Cont...
const PRESUME_FRESH_TTL_SEC
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
Definition: hooks.txt:2376
getPrefixedDBkey()
Get the prefixed database key form.
Definition: Title.php:1418
static getStashKey(Title $title, Content $content, User $user)
Get the temporary prepared edit stash key for a user.