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;
45 public function execute() {
46 $user = $this->getUser();
47 $params = $this->extractRequestParams();
49 $page = $this->getTitleOrPageId( $params );
50 $title = $page->getTitle();
52 if ( !ContentHandler
::getForModelID( $params['contentmodel'] )
53 ->isSupportedFormat( $params['contentformat'] )
55 $this->dieUsage( 'Unsupported content model/format', 'badmodelformat' );
58 // Trim and fix newlines so the key SHA1's match (see RequestContext::getText())
59 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
60 $textContent = ContentHandler
::makeContent(
61 $text, $title, $params['contentmodel'], $params['contentformat'] );
63 $page = WikiPage
::factory( $title );
64 if ( $page->exists() ) {
65 // Page exists: get the merged content with the proposed change
66 $baseRev = Revision
::newFromPageId( $page->getId(), $params['baserevid'] );
68 $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
70 $currentRev = $page->getRevision();
72 $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
74 // Merge in the new version of the section to get the proposed version
75 $editContent = $page->replaceSectionAtRev(
78 $params['sectiontitle'],
81 if ( !$editContent ) {
82 $this->dieUsage( 'Could not merge updated section.', 'replacefailed' );
84 if ( $currentRev->getId() == $baseRev->getId() ) {
85 // Base revision was still the latest; nothing to merge
86 $content = $editContent;
88 // Merge the edit into the current version
89 $baseContent = $baseRev->getContent();
90 $currentContent = $currentRev->getContent();
91 if ( !$baseContent ||
!$currentContent ) {
92 $this->dieUsage( "Missing content for page ID {$page->getId()}", 'missingrev' );
94 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
95 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
98 // New pages: use the user-provided content model
99 $content = $textContent;
102 if ( !$content ) { // merge3() failed
103 $this->getResult()->addValue( null,
104 $this->getModuleName(), [ 'status' => 'editconflict' ] );
108 // The user will abort the AJAX request by pressing "save", so ignore that
109 ignore_user_abort( true );
111 // Use the master DB for fast blocking locks
112 $dbw = wfGetDB( DB_MASTER
);
114 // Get a key based on the source text, format, and user preferences
115 $key = self
::getStashKey( $title, $content, $user );
116 // De-duplicate requests on the same key
117 if ( $user->pingLimiter( 'stashedit' ) ) {
118 $status = 'ratelimited';
119 } elseif ( $dbw->lock( $key, __METHOD__
, 1 ) ) {
120 $status = self
::parseAndStash( $page, $content, $user );
121 $dbw->unlock( $key, __METHOD__
);
126 $this->getResult()->addValue( null, $this->getModuleName(), [ 'status' => $status ] );
130 * @param WikiPage $page
131 * @param Content $content
133 * @return integer ApiStashEdit::ERROR_* constant
136 public static function parseAndStash( WikiPage
$page, Content
$content, User
$user ) {
137 $cache = ObjectCache
::getLocalClusterInstance();
138 $logger = LoggerFactory
::getInstance( 'StashEdit' );
140 $format = $content->getDefaultFormat();
141 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
143 if ( $editInfo && $editInfo->output
) {
144 $key = self
::getStashKey( $page->getTitle(), $content, $user );
146 // Let extensions add ParserOutput metadata or warm other caches
147 Hooks
::run( 'ParserOutputStashForEdit', [ $page, $content, $editInfo->output
] );
149 list( $stashInfo, $ttl ) = self
::buildStashValue(
150 $editInfo->pstContent
,
152 $editInfo->timestamp
,
157 $ok = $cache->set( $key, $stashInfo, $ttl );
159 $logger->debug( "Cached parser output for key '$key'." );
160 return self
::ERROR_NONE
;
162 $logger->error( "Failed to cache parser output for key '$key'." );
163 return self
::ERROR_CACHE
;
166 $logger->info( "Uncacheable parser output for key '$key'." );
167 return self
::ERROR_UNCACHEABLE
;
171 return self
::ERROR_PARSE
;
175 * Attempt to cache PST content and corresponding parser output in passing
177 * This method can be called when the output was already generated for other
178 * reasons. Parsing should not be done just to call this method, however.
179 * $pstOpts must be that of the user doing the edit preview. If $pOpts does
180 * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
181 * will do nothing. Provided the values are cacheable, they will be stored
182 * in memcached so that final edit submission might make use of them.
184 * @param Page|Article|WikiPage $page Page title
185 * @param Content $content Proposed page content
186 * @param Content $pstContent The result of preSaveTransform() on $content
187 * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
188 * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
189 * @param ParserOptions $pOpts Options for $pOut
190 * @param string $timestamp TS_MW timestamp of parser output generation
191 * @return bool Success
193 public static function stashEditFromPreview(
194 Page
$page, Content
$content, Content
$pstContent, ParserOutput
$pOut,
195 ParserOptions
$pstOpts, ParserOptions
$pOpts, $timestamp
197 $cache = ObjectCache
::getLocalClusterInstance();
198 $logger = LoggerFactory
::getInstance( 'StashEdit' );
200 // getIsPreview() controls parser function behavior that references things
201 // like user/revision that don't exists yet. The user/text should already
202 // be set correctly by callers, just double check the preview flag.
203 if ( !$pOpts->getIsPreview() ) {
204 return false; // sanity
205 } elseif ( $pOpts->getIsSectionPreview() ) {
206 return false; // short-circuit (need the full content)
209 // PST parser options are for the user (handles signatures, etc...)
210 $user = $pstOpts->getUser();
211 // Get a key based on the source text, format, and user preferences
212 $key = self
::getStashKey( $page->getTitle(), $content, $user );
214 // Parser output options must match cannonical options.
215 // Treat some options as matching that are different but don't matter.
216 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
217 $canonicalPOpts->setIsPreview( true ); // force match
218 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
219 if ( !$pOpts->matches( $canonicalPOpts ) ) {
220 $logger->info( "Uncacheable preview output for key '$key' (options)." );
224 // Set the time the output was generated
225 $pOut->setCacheTime( wfTimestampNow() );
227 // Build a value to cache with a proper TTL
228 list( $stashInfo, $ttl ) = self
::buildStashValue( $pstContent, $pOut, $timestamp, $user );
230 $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
234 $ok = $cache->set( $key, $stashInfo, $ttl );
236 $logger->error( "Failed to cache preview parser output for key '$key'." );
238 $logger->debug( "Cached preview output for key '$key'." );
245 * Check that a prepared edit is in cache and still up-to-date
247 * This method blocks if the prepared edit is already being rendered,
248 * waiting until rendering finishes before doing final validity checks.
250 * The cache is rejected if template or file changes are detected.
251 * Note that foreign template or file transclusions are not checked.
253 * The result is a map (pstContent,output,timestamp) with fields
254 * extracted directly from WikiPage::prepareContentForEdit().
256 * @param Title $title
257 * @param Content $content
258 * @param User $user User to get parser options from
259 * @return stdClass|bool Returns false on cache miss
261 public static function checkCache( Title
$title, Content
$content, User
$user ) {
262 $cache = ObjectCache
::getLocalClusterInstance();
263 $logger = LoggerFactory
::getInstance( 'StashEdit' );
264 $stats = RequestContext
::getMain()->getStats();
266 $key = self
::getStashKey( $title, $content, $user );
267 $editInfo = $cache->get( $key );
268 if ( !is_object( $editInfo ) ) {
269 $start = microtime( true );
270 // We ignore user aborts and keep parsing. Block on any prior parsing
271 // so as to use its results and make use of the time spent parsing.
272 // Skip this logic if there no master connection in case this method
273 // is called on an HTTP GET request for some reason.
275 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
276 if ( $dbw && $dbw->lock( $key, __METHOD__
, 30 ) ) {
277 $editInfo = $cache->get( $key );
278 $dbw->unlock( $key, __METHOD__
);
281 $timeMs = 1000 * max( 0, microtime( true ) - $start );
282 $stats->timing( 'editstash.lock_wait_time', $timeMs );
285 if ( !is_object( $editInfo ) ||
!$editInfo->output
) {
286 $stats->increment( 'editstash.cache_misses.no_stash' );
287 $logger->debug( "No cache value for key '$key'." );
291 $age = time() - wfTimestamp( TS_UNIX
, $editInfo->output
->getCacheTime() );
292 if ( $age <= self
::PRESUME_FRESH_TTL_SEC
) {
293 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
294 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
295 return $editInfo; // assume nothing changed
296 } elseif ( isset( $editInfo->edits
) && $editInfo->edits
=== $user->getEditCount() ) {
297 // Logged-in user made no local upload/template edits in the meantime
298 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
299 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
301 } elseif ( $user->isAnon()
302 && self
::lastEditTime( $user ) < $editInfo->output
->getCacheTime()
304 // Logged-out user made no local upload/template edits in the meantime
305 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
306 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
310 $dbr = wfGetDB( DB_SLAVE
);
312 $templates = []; // conditions to find changes/creations
313 $templateUses = 0; // expected existing templates
314 foreach ( $editInfo->output
->getTemplateIds() as $ns => $stuff ) {
315 foreach ( $stuff as $dbkey => $revId ) {
316 $templates[(string)$ns][$dbkey] = (int)$revId;
320 // Check that no templates used in the output changed...
321 if ( count( $templates ) ) {
324 [ 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ],
325 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
329 foreach ( $res as $row ) {
330 $changed = $changed ||
( $row->page_latest
!= $templates[$row->ns
][$row->dbk
] );
333 if ( $changed ||
$res->numRows() != $templateUses ) {
334 $stats->increment( 'editstash.cache_misses.proven_stale' );
335 $logger->info( "Stale cache for key '$key'; template changed. (age: $age sec)" );
340 $files = []; // conditions to find changes/creations
341 foreach ( $editInfo->output
->getFileSearchOptions() as $name => $options ) {
342 $files[$name] = (string)$options['sha1'];
344 // Check that no files used in the output changed...
345 if ( count( $files ) ) {
348 [ 'name' => 'img_name', 'img_sha1' ],
349 [ 'img_name' => array_keys( $files ) ],
353 foreach ( $res as $row ) {
354 $changed = $changed ||
( $row->img_sha1
!= $files[$row->name
] );
357 if ( $changed ||
$res->numRows() != count( $files ) ) {
358 $stats->increment( 'editstash.cache_misses.proven_stale' );
359 $logger->info( "Stale cache for key '$key'; file changed. (age: $age sec)" );
364 $stats->increment( 'editstash.cache_hits.proven_fresh' );
365 $logger->debug( "Verified cache hit for key '$key' (age: $age sec)." );
372 * @return string|null TS_MW timestamp or null
374 private static function lastEditTime( User
$user ) {
375 $time = wfGetDB( DB_SLAVE
)->selectField(
378 [ 'rc_user_text' => $user->getName() ],
382 return wfTimestampOrNull( TS_MW
, $time );
386 * Get the temporary prepared edit stash key for a user
388 * This key can be used for caching prepared edits provided:
389 * - a) The $user was used for PST options
390 * - b) The parser output was made from the PST using cannonical matching options
392 * @param Title $title
393 * @param Content $content
394 * @param User $user User to get parser options from
397 private static function getStashKey( Title
$title, Content
$content, User
$user ) {
398 $hash = sha1( implode( ':', [
399 $content->getModel(),
400 $content->getDefaultFormat(),
401 sha1( $content->serialize( $content->getDefaultFormat() ) ),
402 $user->getId() ?
: md5( $user->getName() ), // account for user parser options
403 $user->getId() ?
$user->getDBTouched() : '-' // handle preference change races
406 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
410 * Build a value to store in memcached based on the PST content and parser output
412 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
414 * @param Content $pstContent
415 * @param ParserOutput $parserOutput
416 * @param string $timestamp TS_MW
418 * @return array (stash info array, TTL in seconds) or (null, 0)
420 private static function buildStashValue(
421 Content
$pstContent, ParserOutput
$parserOutput, $timestamp, User
$user
423 // If an item is renewed, mind the cache TTL determined by config and parser functions.
424 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
425 $since = time() - wfTimestamp( TS_UNIX
, $parserOutput->getTimestamp() );
426 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
428 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
429 // Only store what is actually needed
430 $stashInfo = (object)[
431 'pstContent' => $pstContent,
432 'output' => $parserOutput,
433 'timestamp' => $timestamp,
434 'edits' => $user->getEditCount()
436 return [ $stashInfo, $ttl ];
442 public function getAllowedParams() {
445 ApiBase
::PARAM_TYPE
=> 'string',
446 ApiBase
::PARAM_REQUIRED
=> true
449 ApiBase
::PARAM_TYPE
=> 'string',
452 ApiBase
::PARAM_TYPE
=> 'string'
455 ApiBase
::PARAM_TYPE
=> 'text',
456 ApiBase
::PARAM_REQUIRED
=> true
459 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
460 ApiBase
::PARAM_REQUIRED
=> true
463 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
464 ApiBase
::PARAM_REQUIRED
=> true
467 ApiBase
::PARAM_TYPE
=> 'integer',
468 ApiBase
::PARAM_REQUIRED
=> true
473 public function needsToken() {
477 public function mustBePosted() {
481 public function isWriteMode() {
485 public function isInternal() {