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