Merge "Remove "@author Aaron Schulz" annotations"
[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
48 public function execute() {
49 $user = $this->getUser();
50 $params = $this->extractRequestParams();
51
52 if ( $user->isBot() ) { // sanity
53 $this->dieWithError( 'apierror-botsnotsupported' );
54 }
55
56 $cache = ObjectCache::getLocalClusterInstance();
57 $page = $this->getTitleOrPageId( $params );
58 $title = $page->getTitle();
59
60 if ( !ContentHandler::getForModelID( $params['contentmodel'] )
61 ->isSupportedFormat( $params['contentformat'] )
62 ) {
63 $this->dieWithError(
64 [ 'apierror-badformat-generic', $params['contentformat'], $params['contentmodel'] ],
65 'badmodelformat'
66 );
67 }
68
69 $this->requireAtLeastOneParameter( $params, 'stashedtexthash', 'text' );
70
71 $text = null;
72 $textHash = null;
73 if ( strlen( $params['stashedtexthash'] ) ) {
74 // Load from cache since the client indicates the text is the same as last stash
75 $textHash = $params['stashedtexthash'];
76 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
77 $text = $cache->get( $textKey );
78 if ( !is_string( $text ) ) {
79 $this->dieWithError( 'apierror-stashedit-missingtext', 'missingtext' );
80 }
81 } elseif ( $params['text'] !== null ) {
82 // Trim and fix newlines so the key SHA1's match (see WebRequest::getText())
83 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
84 $textHash = sha1( $text );
85 } else {
86 $this->dieWithError( [
87 'apierror-missingparam-at-least-one-of',
88 Message::listParam( [ '<var>stashedtexthash</var>', '<var>text</var>' ] ),
89 2,
90 ], 'missingparam' );
91 }
92
93 $textContent = ContentHandler::makeContent(
94 $text, $title, $params['contentmodel'], $params['contentformat'] );
95
96 $page = WikiPage::factory( $title );
97 if ( $page->exists() ) {
98 // Page exists: get the merged content with the proposed change
99 $baseRev = Revision::newFromPageId( $page->getId(), $params['baserevid'] );
100 if ( !$baseRev ) {
101 $this->dieWithError( [ 'apierror-nosuchrevid', $params['baserevid'] ] );
102 }
103 $currentRev = $page->getRevision();
104 if ( !$currentRev ) {
105 $this->dieWithError( [ 'apierror-missingrev-pageid', $page->getId() ], 'missingrev' );
106 }
107 // Merge in the new version of the section to get the proposed version
108 $editContent = $page->replaceSectionAtRev(
109 $params['section'],
110 $textContent,
111 $params['sectiontitle'],
112 $baseRev->getId()
113 );
114 if ( !$editContent ) {
115 $this->dieWithError( 'apierror-sectionreplacefailed', 'replacefailed' );
116 }
117 if ( $currentRev->getId() == $baseRev->getId() ) {
118 // Base revision was still the latest; nothing to merge
119 $content = $editContent;
120 } else {
121 // Merge the edit into the current version
122 $baseContent = $baseRev->getContent();
123 $currentContent = $currentRev->getContent();
124 if ( !$baseContent || !$currentContent ) {
125 $this->dieWithError( [ 'apierror-missingcontent-pageid', $page->getId() ], 'missingrev' );
126 }
127 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
128 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
129 }
130 } else {
131 // New pages: use the user-provided content model
132 $content = $textContent;
133 }
134
135 if ( !$content ) { // merge3() failed
136 $this->getResult()->addValue( null,
137 $this->getModuleName(), [ 'status' => 'editconflict' ] );
138 return;
139 }
140
141 // The user will abort the AJAX request by pressing "save", so ignore that
142 ignore_user_abort( true );
143
144 if ( $user->pingLimiter( 'stashedit' ) ) {
145 $status = 'ratelimited';
146 } else {
147 $status = self::parseAndStash( $page, $content, $user, $params['summary'] );
148 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
149 $cache->set( $textKey, $text, self::MAX_CACHE_TTL );
150 }
151
152 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
153 $stats->increment( "editstash.cache_stores.$status" );
154
155 $this->getResult()->addValue(
156 null,
157 $this->getModuleName(),
158 [
159 'status' => $status,
160 'texthash' => $textHash
161 ]
162 );
163 }
164
165 /**
166 * @param WikiPage $page
167 * @param Content $content Edit content
168 * @param User $user
169 * @param string $summary Edit summary
170 * @return string ApiStashEdit::ERROR_* constant
171 * @since 1.25
172 */
173 public static function parseAndStash( WikiPage $page, Content $content, User $user, $summary ) {
174 $cache = ObjectCache::getLocalClusterInstance();
175 $logger = LoggerFactory::getInstance( 'StashEdit' );
176
177 $title = $page->getTitle();
178 $key = self::getStashKey( $title, self::getContentHash( $content ), $user );
179
180 // Use the master DB for fast blocking locks
181 $dbw = wfGetDB( DB_MASTER );
182 if ( !$dbw->lock( $key, __METHOD__, 1 ) ) {
183 // De-duplicate requests on the same key
184 return self::ERROR_BUSY;
185 }
186 /** @noinspection PhpUnusedLocalVariableInspection */
187 $unlocker = new ScopedCallback( function () use ( $dbw, $key ) {
188 $dbw->unlock( $key, __METHOD__ );
189 } );
190
191 $cutoffTime = time() - self::PRESUME_FRESH_TTL_SEC;
192
193 // Reuse any freshly build matching edit stash cache
194 $editInfo = $cache->get( $key );
195 if ( $editInfo && wfTimestamp( TS_UNIX, $editInfo->timestamp ) >= $cutoffTime ) {
196 $alreadyCached = true;
197 } else {
198 $format = $content->getDefaultFormat();
199 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
200 $alreadyCached = false;
201 }
202
203 if ( $editInfo && $editInfo->output ) {
204 // Let extensions add ParserOutput metadata or warm other caches
205 Hooks::run( 'ParserOutputStashForEdit',
206 [ $page, $content, $editInfo->output, $summary, $user ] );
207
208 if ( $alreadyCached ) {
209 $logger->debug( "Already cached parser output for key '$key' ('$title')." );
210 return self::ERROR_NONE;
211 }
212
213 list( $stashInfo, $ttl, $code ) = self::buildStashValue(
214 $editInfo->pstContent,
215 $editInfo->output,
216 $editInfo->timestamp,
217 $user
218 );
219
220 if ( $stashInfo ) {
221 $ok = $cache->set( $key, $stashInfo, $ttl );
222 if ( $ok ) {
223 $logger->debug( "Cached parser output for key '$key' ('$title')." );
224 return self::ERROR_NONE;
225 } else {
226 $logger->error( "Failed to cache parser output for key '$key' ('$title')." );
227 return self::ERROR_CACHE;
228 }
229 } else {
230 $logger->info( "Uncacheable parser output for key '$key' ('$title') [$code]." );
231 return self::ERROR_UNCACHEABLE;
232 }
233 }
234
235 return self::ERROR_PARSE;
236 }
237
238 /**
239 * Check that a prepared edit is in cache and still up-to-date
240 *
241 * This method blocks if the prepared edit is already being rendered,
242 * waiting until rendering finishes before doing final validity checks.
243 *
244 * The cache is rejected if template or file changes are detected.
245 * Note that foreign template or file transclusions are not checked.
246 *
247 * The result is a map (pstContent,output,timestamp) with fields
248 * extracted directly from WikiPage::prepareContentForEdit().
249 *
250 * @param Title $title
251 * @param Content $content
252 * @param User $user User to get parser options from
253 * @return stdClass|bool Returns false on cache miss
254 */
255 public static function checkCache( Title $title, Content $content, User $user ) {
256 if ( $user->isBot() ) {
257 return false; // bots never stash - don't pollute stats
258 }
259
260 $cache = ObjectCache::getLocalClusterInstance();
261 $logger = LoggerFactory::getInstance( 'StashEdit' );
262 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
263
264 $key = self::getStashKey( $title, self::getContentHash( $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 = MediaWikiServices::getInstance()->getDBLoadBalancer();
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( "Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
286 return false;
287 }
288
289 $age = time() - wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
290 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
291 // Assume nothing changed in this time
292 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
293 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
294 } elseif ( isset( $editInfo->edits ) && $editInfo->edits === $user->getEditCount() ) {
295 // Logged-in user made no local upload/template edits in the meantime
296 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
297 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
298 } elseif ( $user->isAnon()
299 && self::lastEditTime( $user ) < $editInfo->output->getCacheTime()
300 ) {
301 // Logged-out user made no local upload/template edits in the meantime
302 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
303 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
304 } else {
305 // User may have changed included content
306 $editInfo = false;
307 }
308
309 if ( !$editInfo ) {
310 $stats->increment( 'editstash.cache_misses.proven_stale' );
311 $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
312 } elseif ( $editInfo->output->getFlag( 'vary-revision' ) ) {
313 // This can be used for the initial parse, e.g. for filters or doEditContent(),
314 // but a second parse will be triggered in doEditUpdates(). This is not optimal.
315 $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
316 } elseif ( $editInfo->output->getFlag( 'vary-revision-id' ) ) {
317 // Similar to the above if we didn't guess the ID correctly.
318 $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
319 }
320
321 return $editInfo;
322 }
323
324 /**
325 * @param User $user
326 * @return string|null TS_MW timestamp or null
327 */
328 private static function lastEditTime( User $user ) {
329 $time = wfGetDB( DB_REPLICA )->selectField(
330 'recentchanges',
331 'MAX(rc_timestamp)',
332 [ 'rc_user_text' => $user->getName() ],
333 __METHOD__
334 );
335
336 return wfTimestampOrNull( TS_MW, $time );
337 }
338
339 /**
340 * Get hash of the content, factoring in model/format
341 *
342 * @param Content $content
343 * @return string
344 */
345 private static function getContentHash( Content $content ) {
346 return sha1( implode( "\n", [
347 $content->getModel(),
348 $content->getDefaultFormat(),
349 $content->serialize( $content->getDefaultFormat() )
350 ] ) );
351 }
352
353 /**
354 * Get the temporary prepared edit stash key for a user
355 *
356 * This key can be used for caching prepared edits provided:
357 * - a) The $user was used for PST options
358 * - b) The parser output was made from the PST using cannonical matching options
359 *
360 * @param Title $title
361 * @param string $contentHash Result of getContentHash()
362 * @param User $user User to get parser options from
363 * @return string
364 */
365 private static function getStashKey( Title $title, $contentHash, User $user ) {
366 return ObjectCache::getLocalClusterInstance()->makeKey(
367 'prepared-edit',
368 md5( $title->getPrefixedDBkey() ),
369 // Account for the edit model/text
370 $contentHash,
371 // Account for user name related variables like signatures
372 md5( $user->getId() . "\n" . $user->getName() )
373 );
374 }
375
376 /**
377 * Build a value to store in memcached based on the PST content and parser output
378 *
379 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
380 *
381 * @param Content $pstContent Pre-Save transformed content
382 * @param ParserOutput $parserOutput
383 * @param string $timestamp TS_MW
384 * @param User $user
385 * @return array (stash info array, TTL in seconds, info code) or (null, 0, info code)
386 */
387 private static function buildStashValue(
388 Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user
389 ) {
390 // If an item is renewed, mind the cache TTL determined by config and parser functions.
391 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
392 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
393 $ttl = min( $parserOutput->getCacheExpiry() - $since, self::MAX_CACHE_TTL );
394 if ( $ttl <= 0 ) {
395 return [ null, 0, 'no_ttl' ];
396 }
397
398 // Only store what is actually needed
399 $stashInfo = (object)[
400 'pstContent' => $pstContent,
401 'output' => $parserOutput,
402 'timestamp' => $timestamp,
403 'edits' => $user->getEditCount()
404 ];
405
406 return [ $stashInfo, $ttl, 'ok' ];
407 }
408
409 public function getAllowedParams() {
410 return [
411 'title' => [
412 ApiBase::PARAM_TYPE => 'string',
413 ApiBase::PARAM_REQUIRED => true
414 ],
415 'section' => [
416 ApiBase::PARAM_TYPE => 'string',
417 ],
418 'sectiontitle' => [
419 ApiBase::PARAM_TYPE => 'string'
420 ],
421 'text' => [
422 ApiBase::PARAM_TYPE => 'text',
423 ApiBase::PARAM_DFLT => null
424 ],
425 'stashedtexthash' => [
426 ApiBase::PARAM_TYPE => 'string',
427 ApiBase::PARAM_DFLT => null
428 ],
429 'summary' => [
430 ApiBase::PARAM_TYPE => 'string',
431 ],
432 'contentmodel' => [
433 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
434 ApiBase::PARAM_REQUIRED => true
435 ],
436 'contentformat' => [
437 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
438 ApiBase::PARAM_REQUIRED => true
439 ],
440 'baserevid' => [
441 ApiBase::PARAM_TYPE => 'integer',
442 ApiBase::PARAM_REQUIRED => true
443 ]
444 ];
445 }
446
447 public function needsToken() {
448 return 'csrf';
449 }
450
451 public function mustBePosted() {
452 return true;
453 }
454
455 public function isWriteMode() {
456 return true;
457 }
458
459 public function isInternal() {
460 return true;
461 }
462 }