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