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.
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.
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
19 * @author Aaron Schulz
22 use MediaWiki\Logger\LoggerFactory
;
25 * Prepare an edit in shared cache so that it can be reused on edit
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.
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';
43 const PRESUME_FRESH_TTL_SEC
= 30;
44 const MAX_CACHE_TTL
= 300; // 5 minutes
46 public function execute() {
47 $user = $this->getUser();
48 $params = $this->extractRequestParams();
50 if ( $user->isBot() ) { // sanity
51 $this->dieUsage( 'This interface is not supported for bots', 'botsnotsupported' );
54 $page = $this->getTitleOrPageId( $params );
55 $title = $page->getTitle();
57 if ( !ContentHandler
::getForModelID( $params['contentmodel'] )
58 ->isSupportedFormat( $params['contentformat'] )
60 $this->dieUsage( 'Unsupported content model/format', 'badmodelformat' );
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'] );
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'] );
73 $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
75 $currentRev = $page->getRevision();
77 $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
79 // Merge in the new version of the section to get the proposed version
80 $editContent = $page->replaceSectionAtRev(
83 $params['sectiontitle'],
86 if ( !$editContent ) {
87 $this->dieUsage( 'Could not merge updated section.', 'replacefailed' );
89 if ( $currentRev->getId() == $baseRev->getId() ) {
90 // Base revision was still the latest; nothing to merge
91 $content = $editContent;
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' );
99 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
100 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
103 // New pages: use the user-provided content model
104 $content = $textContent;
107 if ( !$content ) { // merge3() failed
108 $this->getResult()->addValue( null,
109 $this->getModuleName(), [ 'status' => 'editconflict' ] );
113 // The user will abort the AJAX request by pressing "save", so ignore that
114 ignore_user_abort( true );
116 // Use the master DB for fast blocking locks
117 $dbw = wfGetDB( DB_MASTER
);
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__
);
131 $this->getStats()->increment( "editstash.cache_stores.$status" );
133 $this->getResult()->addValue( null, $this->getModuleName(), [ 'status' => $status ] );
137 * @param WikiPage $page
138 * @param Content $content Edit content
140 * @param string $summary Edit summary
141 * @return integer ApiStashEdit::ERROR_* constant
144 public static function parseAndStash( WikiPage
$page, Content
$content, User
$user, $summary ) {
145 $cache = ObjectCache
::getLocalClusterInstance();
146 $logger = LoggerFactory
::getInstance( 'StashEdit' );
148 $format = $content->getDefaultFormat();
149 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
150 $title = $page->getTitle();
152 if ( $editInfo && $editInfo->output
) {
153 $key = self
::getStashKey( $title, $content, $user );
155 // Let extensions add ParserOutput metadata or warm other caches
156 Hooks
::run( 'ParserOutputStashForEdit',
157 [ $page, $content, $editInfo->output
, $summary, $user ] );
159 list( $stashInfo, $ttl, $code ) = self
::buildStashValue(
160 $editInfo->pstContent
,
162 $editInfo->timestamp
,
167 $ok = $cache->set( $key, $stashInfo, $ttl );
169 $logger->debug( "Cached parser output for key '$key' ('$title')." );
170 return self
::ERROR_NONE
;
172 $logger->error( "Failed to cache parser output for key '$key' ('$title')." );
173 return self
::ERROR_CACHE
;
176 $logger->info( "Uncacheable parser output for key '$key' ('$title') [$code]." );
177 return self
::ERROR_UNCACHEABLE
;
181 return self
::ERROR_PARSE
;
185 * Attempt to cache PST content and corresponding parser output in passing
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.
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
203 public static function stashEditFromPreview(
204 Page
$page, Content
$content, Content
$pstContent, ParserOutput
$pOut,
205 ParserOptions
$pstOpts, ParserOptions
$pOpts, $timestamp
207 $cache = ObjectCache
::getLocalClusterInstance();
208 $logger = LoggerFactory
::getInstance( 'StashEdit' );
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)
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 );
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]." );
235 // Set the time the output was generated
236 $pOut->setCacheTime( wfTimestampNow() );
238 // Build a value to cache with a proper TTL
239 list( $stashInfo, $ttl ) = self
::buildStashValue( $pstContent, $pOut, $timestamp, $user );
241 $logger->info( "Uncacheable parser output for key '$key' ('$title') [rev/TTL]." );
245 $ok = $cache->set( $key, $stashInfo, $ttl );
247 $logger->error( "Failed to cache preview parser output for key '$key' ('$title')." );
249 $logger->debug( "Cached preview output for key '$key'." );
256 * Check that a prepared edit is in cache and still up-to-date
258 * This method blocks if the prepared edit is already being rendered,
259 * waiting until rendering finishes before doing final validity checks.
261 * The cache is rejected if template or file changes are detected.
262 * Note that foreign template or file transclusions are not checked.
264 * The result is a map (pstContent,output,timestamp) with fields
265 * extracted directly from WikiPage::prepareContentForEdit().
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
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
277 $cache = ObjectCache
::getLocalClusterInstance();
278 $logger = LoggerFactory
::getInstance( 'StashEdit' );
279 $stats = RequestContext
::getMain()->getStats();
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.
290 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
291 if ( $dbw && $dbw->lock( $key, __METHOD__
, 30 ) ) {
292 $editInfo = $cache->get( $key );
293 $dbw->unlock( $key, __METHOD__
);
296 $timeMs = 1000 * max( 0, microtime( true ) - $start );
297 $stats->timing( 'editstash.lock_wait_time', $timeMs );
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()}'." );
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)." );
316 } elseif ( $user->isAnon()
317 && self
::lastEditTime( $user ) < $editInfo->output
->getCacheTime()
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)." );
325 $stats->increment( 'editstash.cache_misses.proven_stale' );
326 $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
333 * @return string|null TS_MW timestamp or null
335 private static function lastEditTime( User
$user ) {
336 $time = wfGetDB( DB_SLAVE
)->selectField(
339 [ 'rc_user_text' => $user->getName() ],
343 return wfTimestampOrNull( TS_MW
, $time );
347 * Get the temporary prepared edit stash key for a user
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
353 * @param Title $title
354 * @param Content $content
355 * @param User $user User to get parser options from
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
366 md5( $user->getName() )
369 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
373 * Build a value to store in memcached based on the PST content and parser output
375 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
377 * @param Content $pstContent
378 * @param ParserOutput $parserOutput
379 * @param string $timestamp TS_MW
381 * @return array (stash info array, TTL in seconds, info code) or (null, 0, info code)
383 private static function buildStashValue(
384 Content
$pstContent, ParserOutput
$parserOutput, $timestamp, User
$user
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
);
391 return [ null, 0, 'no_ttl' ];
392 } elseif ( $parserOutput->getFlag( 'vary-revision' ) ) {
393 return [ null, 0, 'vary_revision' ];
396 // Only store what is actually needed
397 $stashInfo = (object)[
398 'pstContent' => $pstContent,
399 'output' => $parserOutput,
400 'timestamp' => $timestamp,
401 'edits' => $user->getEditCount()
404 return [ $stashInfo, $ttl, 'ok' ];
407 public function getAllowedParams() {
410 ApiBase
::PARAM_TYPE
=> 'string',
411 ApiBase
::PARAM_REQUIRED
=> true
414 ApiBase
::PARAM_TYPE
=> 'string',
417 ApiBase
::PARAM_TYPE
=> 'string'
420 ApiBase
::PARAM_TYPE
=> 'text',
421 ApiBase
::PARAM_REQUIRED
=> true
424 ApiBase
::PARAM_TYPE
=> 'string',
427 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
428 ApiBase
::PARAM_REQUIRED
=> true
431 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
432 ApiBase
::PARAM_REQUIRED
=> true
435 ApiBase
::PARAM_TYPE
=> 'integer',
436 ApiBase
::PARAM_REQUIRED
=> true
441 public function needsToken() {
445 public function mustBePosted() {
449 public function isWriteMode() {
453 public function isInternal() {