Merge "Call $job->teardown() even if Job throws an exception."
[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,
151 $editInfo->output,
152 $editInfo->timestamp,
153 $user
154 );
155
156 if ( $stashInfo ) {
157 $ok = $cache->set( $key, $stashInfo, $ttl );
158 if ( $ok ) {
159 $logger->debug( "Cached parser output for key '$key'." );
160 return self::ERROR_NONE;
161 } else {
162 $logger->error( "Failed to cache parser output for key '$key'." );
163 return self::ERROR_CACHE;
164 }
165 } else {
166 $logger->info( "Uncacheable parser output for key '$key'." );
167 return self::ERROR_UNCACHEABLE;
168 }
169 }
170
171 return self::ERROR_PARSE;
172 }
173
174 /**
175 * Attempt to cache PST content and corresponding parser output in passing
176 *
177 * This method can be called when the output was already generated for other
178 * reasons. Parsing should not be done just to call this method, however.
179 * $pstOpts must be that of the user doing the edit preview. If $pOpts does
180 * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
181 * will do nothing. Provided the values are cacheable, they will be stored
182 * in memcached so that final edit submission might make use of them.
183 *
184 * @param Page|Article|WikiPage $page Page title
185 * @param Content $content Proposed page content
186 * @param Content $pstContent The result of preSaveTransform() on $content
187 * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
188 * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
189 * @param ParserOptions $pOpts Options for $pOut
190 * @param string $timestamp TS_MW timestamp of parser output generation
191 * @return bool Success
192 */
193 public static function stashEditFromPreview(
194 Page $page, Content $content, Content $pstContent, ParserOutput $pOut,
195 ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp
196 ) {
197 $cache = ObjectCache::getLocalClusterInstance();
198 $logger = LoggerFactory::getInstance( 'StashEdit' );
199
200 // getIsPreview() controls parser function behavior that references things
201 // like user/revision that don't exists yet. The user/text should already
202 // be set correctly by callers, just double check the preview flag.
203 if ( !$pOpts->getIsPreview() ) {
204 return false; // sanity
205 } elseif ( $pOpts->getIsSectionPreview() ) {
206 return false; // short-circuit (need the full content)
207 }
208
209 // PST parser options are for the user (handles signatures, etc...)
210 $user = $pstOpts->getUser();
211 // Get a key based on the source text, format, and user preferences
212 $key = self::getStashKey( $page->getTitle(), $content, $user );
213
214 // Parser output options must match cannonical options.
215 // Treat some options as matching that are different but don't matter.
216 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
217 $canonicalPOpts->setIsPreview( true ); // force match
218 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
219 if ( !$pOpts->matches( $canonicalPOpts ) ) {
220 $logger->info( "Uncacheable preview output for key '$key' (options)." );
221 return false;
222 }
223
224 // Set the time the output was generated
225 $pOut->setCacheTime( wfTimestampNow() );
226
227 // Build a value to cache with a proper TTL
228 list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp, $user );
229 if ( !$stashInfo ) {
230 $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
231 return false;
232 }
233
234 $ok = $cache->set( $key, $stashInfo, $ttl );
235 if ( !$ok ) {
236 $logger->error( "Failed to cache preview parser output for key '$key'." );
237 } else {
238 $logger->debug( "Cached preview output for key '$key'." );
239 }
240
241 return $ok;
242 }
243
244 /**
245 * Check that a prepared edit is in cache and still up-to-date
246 *
247 * This method blocks if the prepared edit is already being rendered,
248 * waiting until rendering finishes before doing final validity checks.
249 *
250 * The cache is rejected if template or file changes are detected.
251 * Note that foreign template or file transclusions are not checked.
252 *
253 * The result is a map (pstContent,output,timestamp) with fields
254 * extracted directly from WikiPage::prepareContentForEdit().
255 *
256 * @param Title $title
257 * @param Content $content
258 * @param User $user User to get parser options from
259 * @return stdClass|bool Returns false on cache miss
260 */
261 public static function checkCache( Title $title, Content $content, User $user ) {
262 $cache = ObjectCache::getLocalClusterInstance();
263 $logger = LoggerFactory::getInstance( 'StashEdit' );
264 $stats = RequestContext::getMain()->getStats();
265
266 $key = self::getStashKey( $title, $content, $user );
267 $editInfo = $cache->get( $key );
268 if ( !is_object( $editInfo ) ) {
269 $start = microtime( true );
270 // We ignore user aborts and keep parsing. Block on any prior parsing
271 // so as to use its results and make use of the time spent parsing.
272 // Skip this logic if there no master connection in case this method
273 // is called on an HTTP GET request for some reason.
274 $lb = wfGetLB();
275 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
276 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
277 $editInfo = $cache->get( $key );
278 $dbw->unlock( $key, __METHOD__ );
279 }
280
281 $timeMs = 1000 * max( 0, microtime( true ) - $start );
282 $stats->timing( 'editstash.lock_wait_time', $timeMs );
283 }
284
285 if ( !is_object( $editInfo ) || !$editInfo->output ) {
286 $stats->increment( 'editstash.cache_misses.no_stash' );
287 $logger->debug( "No cache value for key '$key'." );
288 return false;
289 }
290
291 $age = time() - wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
292 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
293 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
294 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
295 return $editInfo; // assume nothing changed
296 } elseif ( isset( $editInfo->edits ) && $editInfo->edits === $user->getEditCount() ) {
297 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
298 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
299 return $editInfo; // use made no local upload/template edits in the meantime
300 }
301
302 $dbr = wfGetDB( DB_SLAVE );
303
304 $templates = []; // conditions to find changes/creations
305 $templateUses = 0; // expected existing templates
306 foreach ( $editInfo->output->getTemplateIds() as $ns => $stuff ) {
307 foreach ( $stuff as $dbkey => $revId ) {
308 $templates[(string)$ns][$dbkey] = (int)$revId;
309 ++$templateUses;
310 }
311 }
312 // Check that no templates used in the output changed...
313 if ( count( $templates ) ) {
314 $res = $dbr->select(
315 'page',
316 [ 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ],
317 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
318 __METHOD__
319 );
320 $changed = false;
321 foreach ( $res as $row ) {
322 $changed = $changed || ( $row->page_latest != $templates[$row->ns][$row->dbk] );
323 }
324
325 if ( $changed || $res->numRows() != $templateUses ) {
326 $stats->increment( 'editstash.cache_misses.proven_stale' );
327 $logger->info( "Stale cache for key '$key'; template changed. (age: $age sec)" );
328 return false;
329 }
330 }
331
332 $files = []; // conditions to find changes/creations
333 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
334 $files[$name] = (string)$options['sha1'];
335 }
336 // Check that no files used in the output changed...
337 if ( count( $files ) ) {
338 $res = $dbr->select(
339 'image',
340 [ 'name' => 'img_name', 'img_sha1' ],
341 [ 'img_name' => array_keys( $files ) ],
342 __METHOD__
343 );
344 $changed = false;
345 foreach ( $res as $row ) {
346 $changed = $changed || ( $row->img_sha1 != $files[$row->name] );
347 }
348
349 if ( $changed || $res->numRows() != count( $files ) ) {
350 $stats->increment( 'editstash.cache_misses.proven_stale' );
351 $logger->info( "Stale cache for key '$key'; file changed. (age: $age sec)" );
352 return false;
353 }
354 }
355
356 $stats->increment( 'editstash.cache_hits.proven_fresh' );
357 $logger->debug( "Verified cache hit for key '$key' (age: $age sec)." );
358
359 return $editInfo;
360 }
361
362 /**
363 * Get the temporary prepared edit stash key for a user
364 *
365 * This key can be used for caching prepared edits provided:
366 * - a) The $user was used for PST options
367 * - b) The parser output was made from the PST using cannonical matching options
368 *
369 * @param Title $title
370 * @param Content $content
371 * @param User $user User to get parser options from
372 * @return string
373 */
374 protected static function getStashKey( Title $title, Content $content, User $user ) {
375 $hash = sha1( implode( ':', [
376 $content->getModel(),
377 $content->getDefaultFormat(),
378 sha1( $content->serialize( $content->getDefaultFormat() ) ),
379 $user->getId() ?: md5( $user->getName() ), // account for user parser options
380 $user->getId() ? $user->getDBTouched() : '-' // handle preference change races
381 ] ) );
382
383 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
384 }
385
386 /**
387 * Build a value to store in memcached based on the PST content and parser output
388 *
389 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
390 *
391 * @param Content $pstContent
392 * @param ParserOutput $parserOutput
393 * @param string $timestamp TS_MW
394 * @param User $user
395 * @return array (stash info array, TTL in seconds) or (null, 0)
396 */
397 protected static function buildStashValue(
398 Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user
399 ) {
400 // If an item is renewed, mind the cache TTL determined by config and parser functions.
401 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
402 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
403 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
404
405 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
406 // Only store what is actually needed
407 $stashInfo = (object)[
408 'pstContent' => $pstContent,
409 'output' => $parserOutput,
410 'timestamp' => $timestamp,
411 'edits' => $user->getEditCount()
412 ];
413 return [ $stashInfo, $ttl ];
414 }
415
416 return [ null, 0 ];
417 }
418
419 public function getAllowedParams() {
420 return [
421 'title' => [
422 ApiBase::PARAM_TYPE => 'string',
423 ApiBase::PARAM_REQUIRED => true
424 ],
425 'section' => [
426 ApiBase::PARAM_TYPE => 'string',
427 ],
428 'sectiontitle' => [
429 ApiBase::PARAM_TYPE => 'string'
430 ],
431 'text' => [
432 ApiBase::PARAM_TYPE => 'text',
433 ApiBase::PARAM_REQUIRED => true
434 ],
435 'contentmodel' => [
436 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
437 ApiBase::PARAM_REQUIRED => true
438 ],
439 'contentformat' => [
440 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
441 ApiBase::PARAM_REQUIRED => true
442 ],
443 'baserevid' => [
444 ApiBase::PARAM_TYPE => 'integer',
445 ApiBase::PARAM_REQUIRED => true
446 ]
447 ];
448 }
449
450 public function needsToken() {
451 return 'csrf';
452 }
453
454 public function mustBePosted() {
455 return true;
456 }
457
458 public function isWriteMode() {
459 return true;
460 }
461
462 public function isInternal() {
463 return true;
464 }
465 }