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