Localisation updates from https://translatewiki.net.
[lhc/web/wiklou.git] / includes / api / ApiStashEdit.php
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\MediaWikiServices;
23 use Wikimedia\ScopedCallback;
24
25 /**
26 * Prepare an edit in shared cache so that it can be reused on edit
27 *
28 * This endpoint can be called via AJAX as the user focuses on the edit
29 * summary box. By the time of submission, the parse may have already
30 * finished, and can be immediately used on page save. Certain parser
31 * functions like {{REVISIONID}} or {{CURRENTTIME}} may cause the cache
32 * to not be used on edit. Template and files used are check for changes
33 * since the output was generated. The cache TTL is also kept low for sanity.
34 *
35 * @ingroup API
36 * @since 1.25
37 */
38 class ApiStashEdit extends ApiBase {
39 const ERROR_NONE = 'stashed';
40 const ERROR_PARSE = 'error_parse';
41 const ERROR_CACHE = 'error_cache';
42 const ERROR_UNCACHEABLE = 'uncacheable';
43 const ERROR_BUSY = 'busy';
44
45 const PRESUME_FRESH_TTL_SEC = 30;
46 const MAX_CACHE_TTL = 300; // 5 minutes
47 const MAX_SIGNATURE_TTL = 60;
48
49 public function execute() {
50 $user = $this->getUser();
51 $params = $this->extractRequestParams();
52
53 if ( $user->isBot() ) { // sanity
54 $this->dieWithError( 'apierror-botsnotsupported' );
55 }
56
57 $cache = ObjectCache::getLocalClusterInstance();
58 $page = $this->getTitleOrPageId( $params );
59 $title = $page->getTitle();
60
61 if ( !ContentHandler::getForModelID( $params['contentmodel'] )
62 ->isSupportedFormat( $params['contentformat'] )
63 ) {
64 $this->dieWithError(
65 [ 'apierror-badformat-generic', $params['contentformat'], $params['contentmodel'] ],
66 'badmodelformat'
67 );
68 }
69
70 $this->requireOnlyOneParameter( $params, 'stashedtexthash', 'text' );
71
72 $text = null;
73 $textHash = null;
74 if ( $params['stashedtexthash'] !== null ) {
75 // Load from cache since the client indicates the text is the same as last stash
76 $textHash = $params['stashedtexthash'];
77 if ( !preg_match( '/^[0-9a-f]{40}$/', $textHash ) ) {
78 $this->dieWithError( 'apierror-stashedit-missingtext', 'missingtext' );
79 }
80 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
81 $text = $cache->get( $textKey );
82 if ( !is_string( $text ) ) {
83 $this->dieWithError( 'apierror-stashedit-missingtext', 'missingtext' );
84 }
85 } else {
86 // 'text' was passed. Trim and fix newlines so the key SHA1's
87 // match (see WebRequest::getText())
88 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
89 $textHash = sha1( $text );
90 }
91
92 $textContent = ContentHandler::makeContent(
93 $text, $title, $params['contentmodel'], $params['contentformat'] );
94
95 $page = WikiPage::factory( $title );
96 if ( $page->exists() ) {
97 // Page exists: get the merged content with the proposed change
98 $baseRev = Revision::newFromPageId( $page->getId(), $params['baserevid'] );
99 if ( !$baseRev ) {
100 $this->dieWithError( [ 'apierror-nosuchrevid', $params['baserevid'] ] );
101 }
102 $currentRev = $page->getRevision();
103 if ( !$currentRev ) {
104 $this->dieWithError( [ 'apierror-missingrev-pageid', $page->getId() ], 'missingrev' );
105 }
106 // Merge in the new version of the section to get the proposed version
107 $editContent = $page->replaceSectionAtRev(
108 $params['section'],
109 $textContent,
110 $params['sectiontitle'],
111 $baseRev->getId()
112 );
113 if ( !$editContent ) {
114 $this->dieWithError( 'apierror-sectionreplacefailed', 'replacefailed' );
115 }
116 if ( $currentRev->getId() == $baseRev->getId() ) {
117 // Base revision was still the latest; nothing to merge
118 $content = $editContent;
119 } else {
120 // Merge the edit into the current version
121 $baseContent = $baseRev->getContent();
122 $currentContent = $currentRev->getContent();
123 if ( !$baseContent || !$currentContent ) {
124 $this->dieWithError( [ 'apierror-missingcontent-pageid', $page->getId() ], 'missingrev' );
125 }
126 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
127 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
128 }
129 } else {
130 // New pages: use the user-provided content model
131 $content = $textContent;
132 }
133
134 if ( !$content ) { // merge3() failed
135 $this->getResult()->addValue( null,
136 $this->getModuleName(), [ 'status' => 'editconflict' ] );
137 return;
138 }
139
140 // The user will abort the AJAX request by pressing "save", so ignore that
141 ignore_user_abort( true );
142
143 if ( $user->pingLimiter( 'stashedit' ) ) {
144 $status = 'ratelimited';
145 } else {
146 $status = self::parseAndStash( $page, $content, $user, $params['summary'] );
147 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
148 $cache->set( $textKey, $text, self::MAX_CACHE_TTL );
149 }
150
151 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
152 $stats->increment( "editstash.cache_stores.$status" );
153
154 $ret = [ 'status' => $status ];
155 // If we were rate-limited, we still return the pre-existing valid hash if one was passed
156 if ( $status !== 'ratelimited' || $params['stashedtexthash'] !== null ) {
157 $ret['texthash'] = $textHash;
158 }
159
160 $this->getResult()->addValue( null, $this->getModuleName(), $ret );
161 }
162
163 /**
164 * @param WikiPage $page
165 * @param Content $content Edit content
166 * @param User $user
167 * @param string $summary Edit summary
168 * @return string ApiStashEdit::ERROR_* constant
169 * @since 1.25
170 */
171 public static function parseAndStash( WikiPage $page, Content $content, User $user, $summary ) {
172 $logger = LoggerFactory::getInstance( 'StashEdit' );
173
174 $title = $page->getTitle();
175 $key = self::getStashKey( $title, self::getContentHash( $content ), $user );
176 $fname = __METHOD__;
177
178 // Use the master DB to allow for fast blocking locks on the "save path" where this
179 // value might actually be used to complete a page edit. If the edit submission request
180 // happens before this edit stash requests finishes, then the submission will block until
181 // the stash request finishes parsing. For the lock acquisition below, there is not much
182 // need to duplicate parsing of the same content/user/summary bundle, so try to avoid
183 // blocking at all here.
184 $dbw = wfGetDB( DB_MASTER );
185 if ( !$dbw->lock( $key, $fname, 0 ) ) {
186 // De-duplicate requests on the same key
187 return self::ERROR_BUSY;
188 }
189 /** @noinspection PhpUnusedLocalVariableInspection */
190 $unlocker = new ScopedCallback( function () use ( $dbw, $key, $fname ) {
191 $dbw->unlock( $key, $fname );
192 } );
193
194 $cutoffTime = time() - self::PRESUME_FRESH_TTL_SEC;
195
196 // Reuse any freshly build matching edit stash cache
197 $editInfo = self::getStashValue( $key );
198 if ( $editInfo && wfTimestamp( TS_UNIX, $editInfo->timestamp ) >= $cutoffTime ) {
199 $alreadyCached = true;
200 } else {
201 $format = $content->getDefaultFormat();
202 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
203 $alreadyCached = false;
204 }
205
206 if ( $editInfo && $editInfo->output ) {
207 // Let extensions add ParserOutput metadata or warm other caches
208 Hooks::run( 'ParserOutputStashForEdit',
209 [ $page, $content, $editInfo->output, $summary, $user ] );
210
211 $titleStr = (string)$title;
212 if ( $alreadyCached ) {
213 $logger->debug( "Already cached parser output for key '{cachekey}' ('{title}').",
214 [ 'cachekey' => $key, 'title' => $titleStr ] );
215 return self::ERROR_NONE;
216 }
217
218 $code = self::storeStashValue(
219 $key,
220 $editInfo->pstContent,
221 $editInfo->output,
222 $editInfo->timestamp,
223 $user
224 );
225
226 if ( $code === true ) {
227 $logger->debug( "Cached parser output for key '{cachekey}' ('{title}').",
228 [ 'cachekey' => $key, 'title' => $titleStr ] );
229 return self::ERROR_NONE;
230 } elseif ( $code === 'uncacheable' ) {
231 $logger->info(
232 "Uncacheable parser output for key '{cachekey}' ('{title}') [{code}].",
233 [ 'cachekey' => $key, 'title' => $titleStr, 'code' => $code ] );
234 return self::ERROR_UNCACHEABLE;
235 } else {
236 $logger->error( "Failed to cache parser output for key '{cachekey}' ('{title}').",
237 [ 'cachekey' => $key, 'title' => $titleStr, 'code' => $code ] );
238 return self::ERROR_CACHE;
239 }
240 }
241
242 return self::ERROR_PARSE;
243 }
244
245 /**
246 * Check that a prepared edit is in cache and still up-to-date
247 *
248 * This method blocks if the prepared edit is already being rendered,
249 * waiting until rendering finishes before doing final validity checks.
250 *
251 * The cache is rejected if template or file changes are detected.
252 * Note that foreign template or file transclusions are not checked.
253 *
254 * The result is a map (pstContent,output,timestamp) with fields
255 * extracted directly from WikiPage::prepareContentForEdit().
256 *
257 * @param Title $title
258 * @param Content $content
259 * @param User $user User to get parser options from
260 * @return stdClass|bool Returns false on cache miss
261 */
262 public static function checkCache( Title $title, Content $content, User $user ) {
263 if ( $user->isBot() ) {
264 return false; // bots never stash - don't pollute stats
265 }
266
267 $logger = LoggerFactory::getInstance( 'StashEdit' );
268 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
269
270 $key = self::getStashKey( $title, self::getContentHash( $content ), $user );
271 $editInfo = self::getStashValue( $key );
272 if ( !is_object( $editInfo ) ) {
273 $start = microtime( true );
274 // We ignore user aborts and keep parsing. Block on any prior parsing
275 // so as to use its results and make use of the time spent parsing.
276 // Skip this logic if there no master connection in case this method
277 // is called on an HTTP GET request for some reason.
278 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
279 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
280 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
281 $editInfo = self::getStashValue( $key );
282 $dbw->unlock( $key, __METHOD__ );
283 }
284
285 $timeMs = 1000 * max( 0, microtime( true ) - $start );
286 $stats->timing( 'editstash.lock_wait_time', $timeMs );
287 }
288
289 if ( !is_object( $editInfo ) || !$editInfo->output ) {
290 $stats->increment( 'editstash.cache_misses.no_stash' );
291 $logger->debug( "Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
292 return false;
293 }
294
295 $age = time() - wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
296 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
297 // Assume nothing changed in this time
298 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
299 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
300 } elseif ( isset( $editInfo->edits ) && $editInfo->edits === $user->getEditCount() ) {
301 // Logged-in user made no local upload/template edits in the meantime
302 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
303 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
304 } elseif ( $user->isAnon()
305 && self::lastEditTime( $user ) < $editInfo->output->getCacheTime()
306 ) {
307 // Logged-out user made no local upload/template edits in the meantime
308 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
309 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
310 } else {
311 // User may have changed included content
312 $editInfo = false;
313 }
314
315 if ( !$editInfo ) {
316 $stats->increment( 'editstash.cache_misses.proven_stale' );
317 $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
318 } elseif ( $editInfo->output->getFlag( 'vary-revision' ) ) {
319 // This can be used for the initial parse, e.g. for filters or doEditContent(),
320 // but a second parse will be triggered in doEditUpdates(). This is not optimal.
321 $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
322 } elseif ( $editInfo->output->getFlag( 'vary-revision-id' ) ) {
323 // Similar to the above if we didn't guess the ID correctly.
324 $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
325 }
326
327 return $editInfo;
328 }
329
330 /**
331 * @param User $user
332 * @return string|null TS_MW timestamp or null
333 */
334 private static function lastEditTime( User $user ) {
335 $db = wfGetDB( DB_REPLICA );
336 $actorQuery = ActorMigration::newMigration()->getWhere( $db, 'rc_user', $user, false );
337 $time = $db->selectField(
338 [ 'recentchanges' ] + $actorQuery['tables'],
339 'MAX(rc_timestamp)',
340 [ $actorQuery['conds'] ],
341 __METHOD__,
342 [],
343 $actorQuery['joins']
344 );
345
346 return wfTimestampOrNull( TS_MW, $time );
347 }
348
349 /**
350 * Get hash of the content, factoring in model/format
351 *
352 * @param Content $content
353 * @return string
354 */
355 private static function getContentHash( Content $content ) {
356 return sha1( implode( "\n", [
357 $content->getModel(),
358 $content->getDefaultFormat(),
359 $content->serialize( $content->getDefaultFormat() )
360 ] ) );
361 }
362
363 /**
364 * Get the temporary prepared edit stash key for a user
365 *
366 * This key can be used for caching prepared edits provided:
367 * - a) The $user was used for PST options
368 * - b) The parser output was made from the PST using cannonical matching options
369 *
370 * @param Title $title
371 * @param string $contentHash Result of getContentHash()
372 * @param User $user User to get parser options from
373 * @return string
374 */
375 private static function getStashKey( Title $title, $contentHash, User $user ) {
376 return ObjectCache::getLocalClusterInstance()->makeKey(
377 'stashed-edit-info',
378 md5( $title->getPrefixedDBkey() ),
379 // Account for the edit model/text
380 $contentHash,
381 // Account for user name related variables like signatures
382 md5( $user->getId() . "\n" . $user->getName() )
383 );
384 }
385
386 /**
387 * @param string $uuid
388 * @return string
389 */
390 private static function getStashParserOutputKey( $uuid ) {
391 return ObjectCache::getLocalClusterInstance()->makeKey( 'stashed-edit-output', $uuid );
392 }
393
394 /**
395 * @param string $key
396 * @return stdClass|bool Object map (pstContent,output,outputID,timestamp,edits) or false
397 */
398 private static function getStashValue( $key ) {
399 $cache = ObjectCache::getLocalClusterInstance();
400
401 $stashInfo = $cache->get( $key );
402 if ( !is_object( $stashInfo ) ) {
403 return false;
404 }
405
406 $parserOutputKey = self::getStashParserOutputKey( $stashInfo->outputID );
407 $parserOutput = $cache->get( $parserOutputKey );
408 if ( $parserOutput instanceof ParserOutput ) {
409 $stashInfo->output = $parserOutput;
410
411 return $stashInfo;
412 }
413
414 return false;
415 }
416
417 /**
418 * Build a value to store in memcached based on the PST content and parser output
419 *
420 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
421 *
422 * @param string $key
423 * @param Content $pstContent Pre-Save transformed content
424 * @param ParserOutput $parserOutput
425 * @param string $timestamp TS_MW
426 * @param User $user
427 * @return string|bool True or an error code
428 */
429 private static function storeStashValue(
430 $key, Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user
431 ) {
432 // If an item is renewed, mind the cache TTL determined by config and parser functions.
433 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
434 $age = time() - wfTimestamp( TS_UNIX, $parserOutput->getCacheTime() );
435 $ttl = min( $parserOutput->getCacheExpiry() - $age, self::MAX_CACHE_TTL );
436 // Avoid extremely stale user signature timestamps (T84843)
437 if ( $parserOutput->getFlag( 'user-signature' ) ) {
438 $ttl = min( $ttl, self::MAX_SIGNATURE_TTL );
439 }
440
441 if ( $ttl <= 0 ) {
442 return 'uncacheable'; // low TTL due to a tag, magic word, or signature?
443 }
444
445 // Store what is actually needed and split the output into another key (T204742)
446 $parseroutputID = md5( $key );
447 $stashInfo = (object)[
448 'pstContent' => $pstContent,
449 'outputID' => $parseroutputID,
450 'timestamp' => $timestamp,
451 'edits' => $user->getEditCount()
452 ];
453
454 $cache = ObjectCache::getLocalClusterInstance();
455 $ok = $cache->set( $key, $stashInfo, $ttl );
456 if ( $ok ) {
457 $ok = $cache->set(
458 self::getStashParserOutputKey( $parseroutputID ),
459 $parserOutput,
460 $ttl
461 );
462 }
463
464 return $ok ? true : 'store_error';
465 }
466
467 public function getAllowedParams() {
468 return [
469 'title' => [
470 ApiBase::PARAM_TYPE => 'string',
471 ApiBase::PARAM_REQUIRED => true
472 ],
473 'section' => [
474 ApiBase::PARAM_TYPE => 'string',
475 ],
476 'sectiontitle' => [
477 ApiBase::PARAM_TYPE => 'string'
478 ],
479 'text' => [
480 ApiBase::PARAM_TYPE => 'text',
481 ApiBase::PARAM_DFLT => null
482 ],
483 'stashedtexthash' => [
484 ApiBase::PARAM_TYPE => 'string',
485 ApiBase::PARAM_DFLT => null
486 ],
487 'summary' => [
488 ApiBase::PARAM_TYPE => 'string',
489 ],
490 'contentmodel' => [
491 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
492 ApiBase::PARAM_REQUIRED => true
493 ],
494 'contentformat' => [
495 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
496 ApiBase::PARAM_REQUIRED => true
497 ],
498 'baserevid' => [
499 ApiBase::PARAM_TYPE => 'integer',
500 ApiBase::PARAM_REQUIRED => true
501 ]
502 ];
503 }
504
505 public function needsToken() {
506 return 'csrf';
507 }
508
509 public function mustBePosted() {
510 return true;
511 }
512
513 public function isWriteMode() {
514 return true;
515 }
516
517 public function isInternal() {
518 return true;
519 }
520 }