Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / api / ApiStashEdit.php
blob37ee3e76232b4d654cb163b81beea6be996c56ae
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
19 * @author Aaron Schulz
22 use MediaWiki\Logger\LoggerFactory;
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\ScopedCallback;
26 /**
27 * Prepare an edit in shared cache so that it can be reused on edit
29 * This endpoint can be called via AJAX as the user focuses on the edit
30 * summary box. By the time of submission, the parse may have already
31 * finished, and can be immediately used on page save. Certain parser
32 * functions like {{REVISIONID}} or {{CURRENTTIME}} may cause the cache
33 * to not be used on edit. Template and files used are check for changes
34 * since the output was generated. The cache TTL is also kept low for sanity.
36 * @ingroup API
37 * @since 1.25
39 class ApiStashEdit extends ApiBase {
40 const ERROR_NONE = 'stashed';
41 const ERROR_PARSE = 'error_parse';
42 const ERROR_CACHE = 'error_cache';
43 const ERROR_UNCACHEABLE = 'uncacheable';
44 const ERROR_BUSY = 'busy';
46 const PRESUME_FRESH_TTL_SEC = 30;
47 const MAX_CACHE_TTL = 300; // 5 minutes
49 public function execute() {
50 $user = $this->getUser();
51 $params = $this->extractRequestParams();
53 if ( $user->isBot() ) { // sanity
54 $this->dieWithError( 'apierror-botsnotsupported' );
57 $cache = ObjectCache::getLocalClusterInstance();
58 $page = $this->getTitleOrPageId( $params );
59 $title = $page->getTitle();
61 if ( !ContentHandler::getForModelID( $params['contentmodel'] )
62 ->isSupportedFormat( $params['contentformat'] )
63 ) {
64 $this->dieWithError(
65 [ 'apierror-badformat-generic', $params['contentformat'], $params['contentmodel'] ],
66 'badmodelformat'
70 $this->requireAtLeastOneParameter( $params, 'stashedtexthash', 'text' );
72 $text = null;
73 $textHash = null;
74 if ( strlen( $params['stashedtexthash'] ) ) {
75 // Load from cache since the client indicates the text is the same as last stash
76 $textHash = $params['stashedtexthash'];
77 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
78 $text = $cache->get( $textKey );
79 if ( !is_string( $text ) ) {
80 $this->dieWithError( 'apierror-stashedit-missingtext', 'missingtext' );
82 } elseif ( $params['text'] !== null ) {
83 // Trim and fix newlines so the key SHA1's match (see WebRequest::getText())
84 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
85 $textHash = sha1( $text );
86 } else {
87 $this->dieWithError( [
88 'apierror-missingparam-at-least-one-of',
89 Message::listParam( [ '<var>stashedtexthash</var>', '<var>text</var>' ] ),
91 ], 'missingparam' );
94 $textContent = ContentHandler::makeContent(
95 $text, $title, $params['contentmodel'], $params['contentformat'] );
97 $page = WikiPage::factory( $title );
98 if ( $page->exists() ) {
99 // Page exists: get the merged content with the proposed change
100 $baseRev = Revision::newFromPageId( $page->getId(), $params['baserevid'] );
101 if ( !$baseRev ) {
102 $this->dieWithError( [ 'apierror-nosuchrevid', $params['baserevid'] ] );
104 $currentRev = $page->getRevision();
105 if ( !$currentRev ) {
106 $this->dieWithError( [ 'apierror-missingrev-pageid', $page->getId() ], 'missingrev' );
108 // Merge in the new version of the section to get the proposed version
109 $editContent = $page->replaceSectionAtRev(
110 $params['section'],
111 $textContent,
112 $params['sectiontitle'],
113 $baseRev->getId()
115 if ( !$editContent ) {
116 $this->dieWithError( 'apierror-sectionreplacefailed', 'replacefailed' );
118 if ( $currentRev->getId() == $baseRev->getId() ) {
119 // Base revision was still the latest; nothing to merge
120 $content = $editContent;
121 } else {
122 // Merge the edit into the current version
123 $baseContent = $baseRev->getContent();
124 $currentContent = $currentRev->getContent();
125 if ( !$baseContent || !$currentContent ) {
126 $this->dieWithError( [ 'apierror-missingcontent-pageid', $page->getId() ], 'missingrev' );
128 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
129 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
131 } else {
132 // New pages: use the user-provided content model
133 $content = $textContent;
136 if ( !$content ) { // merge3() failed
137 $this->getResult()->addValue( null,
138 $this->getModuleName(), [ 'status' => 'editconflict' ] );
139 return;
142 // The user will abort the AJAX request by pressing "save", so ignore that
143 ignore_user_abort( true );
145 if ( $user->pingLimiter( 'stashedit' ) ) {
146 $status = 'ratelimited';
147 } else {
148 $status = self::parseAndStash( $page, $content, $user, $params['summary'] );
149 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
150 $cache->set( $textKey, $text, self::MAX_CACHE_TTL );
153 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
154 $stats->increment( "editstash.cache_stores.$status" );
156 $this->getResult()->addValue(
157 null,
158 $this->getModuleName(),
160 'status' => $status,
161 'texthash' => $textHash
167 * @param WikiPage $page
168 * @param Content $content Edit content
169 * @param User $user
170 * @param string $summary Edit summary
171 * @return string ApiStashEdit::ERROR_* constant
172 * @since 1.25
174 public static function parseAndStash( WikiPage $page, Content $content, User $user, $summary ) {
175 $cache = ObjectCache::getLocalClusterInstance();
176 $logger = LoggerFactory::getInstance( 'StashEdit' );
178 $title = $page->getTitle();
179 $key = self::getStashKey( $title, self::getContentHash( $content ), $user );
181 // Use the master DB for fast blocking locks
182 $dbw = wfGetDB( DB_MASTER );
183 if ( !$dbw->lock( $key, __METHOD__, 1 ) ) {
184 // De-duplicate requests on the same key
185 return self::ERROR_BUSY;
187 /** @noinspection PhpUnusedLocalVariableInspection */
188 $unlocker = new ScopedCallback( function () use ( $dbw, $key ) {
189 $dbw->unlock( $key, __METHOD__ );
190 } );
192 $cutoffTime = time() - self::PRESUME_FRESH_TTL_SEC;
194 // Reuse any freshly build matching edit stash cache
195 $editInfo = $cache->get( $key );
196 if ( $editInfo && wfTimestamp( TS_UNIX, $editInfo->timestamp ) >= $cutoffTime ) {
197 $alreadyCached = true;
198 } else {
199 $format = $content->getDefaultFormat();
200 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
201 $alreadyCached = false;
204 if ( $editInfo && $editInfo->output ) {
205 // Let extensions add ParserOutput metadata or warm other caches
206 Hooks::run( 'ParserOutputStashForEdit',
207 [ $page, $content, $editInfo->output, $summary, $user ] );
209 if ( $alreadyCached ) {
210 $logger->debug( "Already cached parser output for key '$key' ('$title')." );
211 return self::ERROR_NONE;
214 list( $stashInfo, $ttl, $code ) = self::buildStashValue(
215 $editInfo->pstContent,
216 $editInfo->output,
217 $editInfo->timestamp,
218 $user
221 if ( $stashInfo ) {
222 $ok = $cache->set( $key, $stashInfo, $ttl );
223 if ( $ok ) {
224 $logger->debug( "Cached parser output for key '$key' ('$title')." );
225 return self::ERROR_NONE;
226 } else {
227 $logger->error( "Failed to cache parser output for key '$key' ('$title')." );
228 return self::ERROR_CACHE;
230 } else {
231 $logger->info( "Uncacheable parser output for key '$key' ('$title') [$code]." );
232 return self::ERROR_UNCACHEABLE;
236 return self::ERROR_PARSE;
240 * Check that a prepared edit is in cache and still up-to-date
242 * This method blocks if the prepared edit is already being rendered,
243 * waiting until rendering finishes before doing final validity checks.
245 * The cache is rejected if template or file changes are detected.
246 * Note that foreign template or file transclusions are not checked.
248 * The result is a map (pstContent,output,timestamp) with fields
249 * extracted directly from WikiPage::prepareContentForEdit().
251 * @param Title $title
252 * @param Content $content
253 * @param User $user User to get parser options from
254 * @return stdClass|bool Returns false on cache miss
256 public static function checkCache( Title $title, Content $content, User $user ) {
257 if ( $user->isBot() ) {
258 return false; // bots never stash - don't pollute stats
261 $cache = ObjectCache::getLocalClusterInstance();
262 $logger = LoggerFactory::getInstance( 'StashEdit' );
263 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
265 $key = self::getStashKey( $title, self::getContentHash( $content ), $user );
266 $editInfo = $cache->get( $key );
267 if ( !is_object( $editInfo ) ) {
268 $start = microtime( true );
269 // We ignore user aborts and keep parsing. Block on any prior parsing
270 // so as to use its results and make use of the time spent parsing.
271 // Skip this logic if there no master connection in case this method
272 // is called on an HTTP GET request for some reason.
273 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
274 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
275 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
276 $editInfo = $cache->get( $key );
277 $dbw->unlock( $key, __METHOD__ );
280 $timeMs = 1000 * max( 0, microtime( true ) - $start );
281 $stats->timing( 'editstash.lock_wait_time', $timeMs );
284 if ( !is_object( $editInfo ) || !$editInfo->output ) {
285 $stats->increment( 'editstash.cache_misses.no_stash' );
286 $logger->debug( "Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
287 return false;
290 $age = time() - wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
291 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
292 // Assume nothing changed in this time
293 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
294 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
295 } elseif ( isset( $editInfo->edits ) && $editInfo->edits === $user->getEditCount() ) {
296 // Logged-in user made no local upload/template edits in the meantime
297 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
298 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
299 } elseif ( $user->isAnon()
300 && self::lastEditTime( $user ) < $editInfo->output->getCacheTime()
302 // Logged-out user made no local upload/template edits in the meantime
303 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
304 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
305 } else {
306 // User may have changed included content
307 $editInfo = false;
310 if ( !$editInfo ) {
311 $stats->increment( 'editstash.cache_misses.proven_stale' );
312 $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
313 } elseif ( $editInfo->output->getFlag( 'vary-revision' ) ) {
314 // This can be used for the initial parse, e.g. for filters or doEditContent(),
315 // but a second parse will be triggered in doEditUpdates(). This is not optimal.
316 $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
317 } elseif ( $editInfo->output->getFlag( 'vary-revision-id' ) ) {
318 // Similar to the above if we didn't guess the ID correctly.
319 $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
322 return $editInfo;
326 * @param User $user
327 * @return string|null TS_MW timestamp or null
329 private static function lastEditTime( User $user ) {
330 $time = wfGetDB( DB_REPLICA )->selectField(
331 'recentchanges',
332 'MAX(rc_timestamp)',
333 [ 'rc_user_text' => $user->getName() ],
334 __METHOD__
337 return wfTimestampOrNull( TS_MW, $time );
341 * Get hash of the content, factoring in model/format
343 * @param Content $content
344 * @return string
346 private static function getContentHash( Content $content ) {
347 return sha1( implode( "\n", [
348 $content->getModel(),
349 $content->getDefaultFormat(),
350 $content->serialize( $content->getDefaultFormat() )
351 ] ) );
355 * Get the temporary prepared edit stash key for a user
357 * This key can be used for caching prepared edits provided:
358 * - a) The $user was used for PST options
359 * - b) The parser output was made from the PST using cannonical matching options
361 * @param Title $title
362 * @param string $contentHash Result of getContentHash()
363 * @param User $user User to get parser options from
364 * @return string
366 private static function getStashKey( Title $title, $contentHash, User $user ) {
367 return ObjectCache::getLocalClusterInstance()->makeKey(
368 'prepared-edit',
369 md5( $title->getPrefixedDBkey() ),
370 // Account for the edit model/text
371 $contentHash,
372 // Account for user name related variables like signatures
373 md5( $user->getId() . "\n" . $user->getName() )
378 * Build a value to store in memcached based on the PST content and parser output
380 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
382 * @param Content $pstContent Pre-Save transformed content
383 * @param ParserOutput $parserOutput
384 * @param string $timestamp TS_MW
385 * @param User $user
386 * @return array (stash info array, TTL in seconds, info code) or (null, 0, info code)
388 private static function buildStashValue(
389 Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user
391 // If an item is renewed, mind the cache TTL determined by config and parser functions.
392 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
393 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
394 $ttl = min( $parserOutput->getCacheExpiry() - $since, self::MAX_CACHE_TTL );
395 if ( $ttl <= 0 ) {
396 return [ null, 0, 'no_ttl' ];
399 // Only store what is actually needed
400 $stashInfo = (object)[
401 'pstContent' => $pstContent,
402 'output' => $parserOutput,
403 'timestamp' => $timestamp,
404 'edits' => $user->getEditCount()
407 return [ $stashInfo, $ttl, 'ok' ];
410 public function getAllowedParams() {
411 return [
412 'title' => [
413 ApiBase::PARAM_TYPE => 'string',
414 ApiBase::PARAM_REQUIRED => true
416 'section' => [
417 ApiBase::PARAM_TYPE => 'string',
419 'sectiontitle' => [
420 ApiBase::PARAM_TYPE => 'string'
422 'text' => [
423 ApiBase::PARAM_TYPE => 'text',
424 ApiBase::PARAM_DFLT => null
426 'stashedtexthash' => [
427 ApiBase::PARAM_TYPE => 'string',
428 ApiBase::PARAM_DFLT => null
430 'summary' => [
431 ApiBase::PARAM_TYPE => 'string',
433 'contentmodel' => [
434 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
435 ApiBase::PARAM_REQUIRED => true
437 'contentformat' => [
438 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
439 ApiBase::PARAM_REQUIRED => true
441 'baserevid' => [
442 ApiBase::PARAM_TYPE => 'integer',
443 ApiBase::PARAM_REQUIRED => true
448 public function needsToken() {
449 return 'csrf';
452 public function mustBePosted() {
453 return true;
456 public function isWriteMode() {
457 return true;
460 public function isInternal() {
461 return true;