Merge "Bail out in ApiStashEdit for bots for sanity"
[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 * @author Aaron Schulz
20 */
21
22 use MediaWiki\Logger\LoggerFactory;
23
24 /**
25 * Prepare an edit in shared cache so that it can be reused on edit
26 *
27 * This endpoint can be called via AJAX as the user focuses on the edit
28 * summary box. By the time of submission, the parse may have already
29 * finished, and can be immediately used on page save. Certain parser
30 * functions like {{REVISIONID}} or {{CURRENTTIME}} may cause the cache
31 * to not be used on edit. Template and files used are check for changes
32 * since the output was generated. The cache TTL is also kept low for sanity.
33 *
34 * @ingroup API
35 * @since 1.25
36 */
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
43 const PRESUME_FRESH_TTL_SEC = 30;
44
45 public function execute() {
46 $user = $this->getUser();
47 $params = $this->extractRequestParams();
48
49 if ( $user->isBot() ) { // sanity
50 $this->dieUsage( 'This interface is not supported for bots', 'botsnotsupported' );
51 }
52
53 $page = $this->getTitleOrPageId( $params );
54 $title = $page->getTitle();
55
56 if ( !ContentHandler::getForModelID( $params['contentmodel'] )
57 ->isSupportedFormat( $params['contentformat'] )
58 ) {
59 $this->dieUsage( 'Unsupported content model/format', 'badmodelformat' );
60 }
61
62 // Trim and fix newlines so the key SHA1's match (see RequestContext::getText())
63 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
64 $textContent = ContentHandler::makeContent(
65 $text, $title, $params['contentmodel'], $params['contentformat'] );
66
67 $page = WikiPage::factory( $title );
68 if ( $page->exists() ) {
69 // Page exists: get the merged content with the proposed change
70 $baseRev = Revision::newFromPageId( $page->getId(), $params['baserevid'] );
71 if ( !$baseRev ) {
72 $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
73 }
74 $currentRev = $page->getRevision();
75 if ( !$currentRev ) {
76 $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
77 }
78 // Merge in the new version of the section to get the proposed version
79 $editContent = $page->replaceSectionAtRev(
80 $params['section'],
81 $textContent,
82 $params['sectiontitle'],
83 $baseRev->getId()
84 );
85 if ( !$editContent ) {
86 $this->dieUsage( 'Could not merge updated section.', 'replacefailed' );
87 }
88 if ( $currentRev->getId() == $baseRev->getId() ) {
89 // Base revision was still the latest; nothing to merge
90 $content = $editContent;
91 } else {
92 // Merge the edit into the current version
93 $baseContent = $baseRev->getContent();
94 $currentContent = $currentRev->getContent();
95 if ( !$baseContent || !$currentContent ) {
96 $this->dieUsage( "Missing content for page ID {$page->getId()}", 'missingrev' );
97 }
98 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
99 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
100 }
101 } else {
102 // New pages: use the user-provided content model
103 $content = $textContent;
104 }
105
106 if ( !$content ) { // merge3() failed
107 $this->getResult()->addValue( null,
108 $this->getModuleName(), [ 'status' => 'editconflict' ] );
109 return;
110 }
111
112 // The user will abort the AJAX request by pressing "save", so ignore that
113 ignore_user_abort( true );
114
115 // Use the master DB for fast blocking locks
116 $dbw = wfGetDB( DB_MASTER );
117
118 // Get a key based on the source text, format, and user preferences
119 $key = self::getStashKey( $title, $content, $user );
120 // De-duplicate requests on the same key
121 if ( $user->pingLimiter( 'stashedit' ) ) {
122 $status = 'ratelimited';
123 } elseif ( $dbw->lock( $key, __METHOD__, 1 ) ) {
124 $status = self::parseAndStash( $page, $content, $user );
125 $dbw->unlock( $key, __METHOD__ );
126 } else {
127 $status = 'busy';
128 }
129
130 $this->getResult()->addValue( null, $this->getModuleName(), [ 'status' => $status ] );
131 }
132
133 /**
134 * @param WikiPage $page
135 * @param Content $content
136 * @param User $user
137 * @return integer ApiStashEdit::ERROR_* constant
138 * @since 1.25
139 */
140 public static function parseAndStash( WikiPage $page, Content $content, User $user ) {
141 $cache = ObjectCache::getLocalClusterInstance();
142 $logger = LoggerFactory::getInstance( 'StashEdit' );
143
144 $format = $content->getDefaultFormat();
145 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
146
147 if ( $editInfo && $editInfo->output ) {
148 $key = self::getStashKey( $page->getTitle(), $content, $user );
149
150 // Let extensions add ParserOutput metadata or warm other caches
151 Hooks::run( 'ParserOutputStashForEdit', [ $page, $content, $editInfo->output ] );
152
153 list( $stashInfo, $ttl ) = self::buildStashValue(
154 $editInfo->pstContent,
155 $editInfo->output,
156 $editInfo->timestamp,
157 $user
158 );
159
160 if ( $stashInfo ) {
161 $ok = $cache->set( $key, $stashInfo, $ttl );
162 if ( $ok ) {
163 $logger->debug( "Cached parser output for key '$key'." );
164 return self::ERROR_NONE;
165 } else {
166 $logger->error( "Failed to cache parser output for key '$key'." );
167 return self::ERROR_CACHE;
168 }
169 } else {
170 $logger->info( "Uncacheable parser output for key '$key'." );
171 return self::ERROR_UNCACHEABLE;
172 }
173 }
174
175 return self::ERROR_PARSE;
176 }
177
178 /**
179 * Attempt to cache PST content and corresponding parser output in passing
180 *
181 * This method can be called when the output was already generated for other
182 * reasons. Parsing should not be done just to call this method, however.
183 * $pstOpts must be that of the user doing the edit preview. If $pOpts does
184 * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
185 * will do nothing. Provided the values are cacheable, they will be stored
186 * in memcached so that final edit submission might make use of them.
187 *
188 * @param Page|Article|WikiPage $page Page title
189 * @param Content $content Proposed page content
190 * @param Content $pstContent The result of preSaveTransform() on $content
191 * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
192 * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
193 * @param ParserOptions $pOpts Options for $pOut
194 * @param string $timestamp TS_MW timestamp of parser output generation
195 * @return bool Success
196 */
197 public static function stashEditFromPreview(
198 Page $page, Content $content, Content $pstContent, ParserOutput $pOut,
199 ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp
200 ) {
201 $cache = ObjectCache::getLocalClusterInstance();
202 $logger = LoggerFactory::getInstance( 'StashEdit' );
203
204 // getIsPreview() controls parser function behavior that references things
205 // like user/revision that don't exists yet. The user/text should already
206 // be set correctly by callers, just double check the preview flag.
207 if ( !$pOpts->getIsPreview() ) {
208 return false; // sanity
209 } elseif ( $pOpts->getIsSectionPreview() ) {
210 return false; // short-circuit (need the full content)
211 }
212
213 // PST parser options are for the user (handles signatures, etc...)
214 $user = $pstOpts->getUser();
215 // Get a key based on the source text, format, and user preferences
216 $key = self::getStashKey( $page->getTitle(), $content, $user );
217
218 // Parser output options must match cannonical options.
219 // Treat some options as matching that are different but don't matter.
220 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
221 $canonicalPOpts->setIsPreview( true ); // force match
222 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
223 if ( !$pOpts->matches( $canonicalPOpts ) ) {
224 $logger->info( "Uncacheable preview output for key '$key' (options)." );
225 return false;
226 }
227
228 // Set the time the output was generated
229 $pOut->setCacheTime( wfTimestampNow() );
230
231 // Build a value to cache with a proper TTL
232 list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp, $user );
233 if ( !$stashInfo ) {
234 $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
235 return false;
236 }
237
238 $ok = $cache->set( $key, $stashInfo, $ttl );
239 if ( !$ok ) {
240 $logger->error( "Failed to cache preview parser output for key '$key'." );
241 } else {
242 $logger->debug( "Cached preview output for key '$key'." );
243 }
244
245 return $ok;
246 }
247
248 /**
249 * Check that a prepared edit is in cache and still up-to-date
250 *
251 * This method blocks if the prepared edit is already being rendered,
252 * waiting until rendering finishes before doing final validity checks.
253 *
254 * The cache is rejected if template or file changes are detected.
255 * Note that foreign template or file transclusions are not checked.
256 *
257 * The result is a map (pstContent,output,timestamp) with fields
258 * extracted directly from WikiPage::prepareContentForEdit().
259 *
260 * @param Title $title
261 * @param Content $content
262 * @param User $user User to get parser options from
263 * @return stdClass|bool Returns false on cache miss
264 */
265 public static function checkCache( Title $title, Content $content, User $user ) {
266 if ( $user->isBot() ) {
267 return false; // bots never stash - don't pollute stats
268 }
269
270 $cache = ObjectCache::getLocalClusterInstance();
271 $logger = LoggerFactory::getInstance( 'StashEdit' );
272 $stats = RequestContext::getMain()->getStats();
273
274 $key = self::getStashKey( $title, $content, $user );
275 $editInfo = $cache->get( $key );
276 if ( !is_object( $editInfo ) ) {
277 $start = microtime( true );
278 // We ignore user aborts and keep parsing. Block on any prior parsing
279 // so as to use its results and make use of the time spent parsing.
280 // Skip this logic if there no master connection in case this method
281 // is called on an HTTP GET request for some reason.
282 $lb = wfGetLB();
283 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
284 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
285 $editInfo = $cache->get( $key );
286 $dbw->unlock( $key, __METHOD__ );
287 }
288
289 $timeMs = 1000 * max( 0, microtime( true ) - $start );
290 $stats->timing( 'editstash.lock_wait_time', $timeMs );
291 }
292
293 if ( !is_object( $editInfo ) || !$editInfo->output ) {
294 $stats->increment( 'editstash.cache_misses.no_stash' );
295 $logger->debug( "No cache value for key '$key'." );
296 return false;
297 }
298
299 $age = time() - wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
300 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
301 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
302 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
303 return $editInfo; // assume nothing changed
304 } elseif ( isset( $editInfo->edits ) && $editInfo->edits === $user->getEditCount() ) {
305 // Logged-in user made no local upload/template edits in the meantime
306 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
307 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
308 return $editInfo;
309 } elseif ( $user->isAnon()
310 && self::lastEditTime( $user ) < $editInfo->output->getCacheTime()
311 ) {
312 // Logged-out user made no local upload/template edits in the meantime
313 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
314 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
315 return $editInfo;
316 }
317
318 $dbr = wfGetDB( DB_SLAVE );
319
320 $templates = []; // conditions to find changes/creations
321 $templateUses = 0; // expected existing templates
322 foreach ( $editInfo->output->getTemplateIds() as $ns => $stuff ) {
323 foreach ( $stuff as $dbkey => $revId ) {
324 $templates[(string)$ns][$dbkey] = (int)$revId;
325 ++$templateUses;
326 }
327 }
328 // Check that no templates used in the output changed...
329 if ( count( $templates ) ) {
330 $res = $dbr->select(
331 'page',
332 [ 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ],
333 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
334 __METHOD__
335 );
336 $changed = false;
337 foreach ( $res as $row ) {
338 $changed = $changed || ( $row->page_latest != $templates[$row->ns][$row->dbk] );
339 }
340
341 if ( $changed || $res->numRows() != $templateUses ) {
342 $stats->increment( 'editstash.cache_misses.proven_stale' );
343 $logger->info( "Stale cache for key '$key'; template changed. (age: $age sec)" );
344 return false;
345 }
346 }
347
348 $files = []; // conditions to find changes/creations
349 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
350 $files[$name] = (string)$options['sha1'];
351 }
352 // Check that no files used in the output changed...
353 if ( count( $files ) ) {
354 $res = $dbr->select(
355 'image',
356 [ 'name' => 'img_name', 'img_sha1' ],
357 [ 'img_name' => array_keys( $files ) ],
358 __METHOD__
359 );
360 $changed = false;
361 foreach ( $res as $row ) {
362 $changed = $changed || ( $row->img_sha1 != $files[$row->name] );
363 }
364
365 if ( $changed || $res->numRows() != count( $files ) ) {
366 $stats->increment( 'editstash.cache_misses.proven_stale' );
367 $logger->info( "Stale cache for key '$key'; file changed. (age: $age sec)" );
368 return false;
369 }
370 }
371
372 $stats->increment( 'editstash.cache_hits.proven_fresh' );
373 $logger->debug( "Verified cache hit for key '$key' (age: $age sec)." );
374
375 return $editInfo;
376 }
377
378 /**
379 * @param User $user
380 * @return string|null TS_MW timestamp or null
381 */
382 private static function lastEditTime( User $user ) {
383 $time = wfGetDB( DB_SLAVE )->selectField(
384 'recentchanges',
385 'MAX(rc_timestamp)',
386 [ 'rc_user_text' => $user->getName() ],
387 __METHOD__
388 );
389
390 return wfTimestampOrNull( TS_MW, $time );
391 }
392
393 /**
394 * Get the temporary prepared edit stash key for a user
395 *
396 * This key can be used for caching prepared edits provided:
397 * - a) The $user was used for PST options
398 * - b) The parser output was made from the PST using cannonical matching options
399 *
400 * @param Title $title
401 * @param Content $content
402 * @param User $user User to get parser options from
403 * @return string
404 */
405 private static function getStashKey( Title $title, Content $content, User $user ) {
406 $hash = sha1( implode( ':', [
407 $content->getModel(),
408 $content->getDefaultFormat(),
409 sha1( $content->serialize( $content->getDefaultFormat() ) ),
410 $user->getId() ?: md5( $user->getName() ), // account for user parser options
411 $user->getId() ? $user->getDBTouched() : '-' // handle preference change races
412 ] ) );
413
414 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
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 Content $pstContent
423 * @param ParserOutput $parserOutput
424 * @param string $timestamp TS_MW
425 * @param User $user
426 * @return array (stash info array, TTL in seconds) or (null, 0)
427 */
428 private static function buildStashValue(
429 Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user
430 ) {
431 // If an item is renewed, mind the cache TTL determined by config and parser functions.
432 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
433 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
434 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
435
436 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
437 // Only store what is actually needed
438 $stashInfo = (object)[
439 'pstContent' => $pstContent,
440 'output' => $parserOutput,
441 'timestamp' => $timestamp,
442 'edits' => $user->getEditCount()
443 ];
444 return [ $stashInfo, $ttl ];
445 }
446
447 return [ null, 0 ];
448 }
449
450 public function getAllowedParams() {
451 return [
452 'title' => [
453 ApiBase::PARAM_TYPE => 'string',
454 ApiBase::PARAM_REQUIRED => true
455 ],
456 'section' => [
457 ApiBase::PARAM_TYPE => 'string',
458 ],
459 'sectiontitle' => [
460 ApiBase::PARAM_TYPE => 'string'
461 ],
462 'text' => [
463 ApiBase::PARAM_TYPE => 'text',
464 ApiBase::PARAM_REQUIRED => true
465 ],
466 'contentmodel' => [
467 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
468 ApiBase::PARAM_REQUIRED => true
469 ],
470 'contentformat' => [
471 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
472 ApiBase::PARAM_REQUIRED => true
473 ],
474 'baserevid' => [
475 ApiBase::PARAM_TYPE => 'integer',
476 ApiBase::PARAM_REQUIRED => true
477 ]
478 ];
479 }
480
481 public function needsToken() {
482 return 'csrf';
483 }
484
485 public function mustBePosted() {
486 return true;
487 }
488
489 public function isWriteMode() {
490 return true;
491 }
492
493 public function isInternal() {
494 return true;
495 }
496 }