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