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
;
23 use MediaWiki\MediaWikiServices
;
26 * Prepare an edit in shared cache so that it can be reused on edit
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.
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';
45 const PRESUME_FRESH_TTL_SEC
= 30;
46 const MAX_CACHE_TTL
= 300; // 5 minutes
48 public function execute() {
49 $user = $this->getUser();
50 $params = $this->extractRequestParams();
52 if ( $user->isBot() ) { // sanity
53 $this->dieUsage( 'This interface is not supported for bots', 'botsnotsupported' );
56 $cache = ObjectCache
::getLocalClusterInstance();
57 $page = $this->getTitleOrPageId( $params );
58 $title = $page->getTitle();
60 if ( !ContentHandler
::getForModelID( $params['contentmodel'] )
61 ->isSupportedFormat( $params['contentformat'] )
63 $this->dieUsage( 'Unsupported content model/format', 'badmodelformat' );
68 if ( strlen( $params['stashedtexthash'] ) ) {
69 // Load from cache since the client indicates the text is the same as last stash
70 $textHash = $params['stashedtexthash'];
71 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
72 $text = $cache->get( $textKey );
73 if ( !is_string( $text ) ) {
74 $this->dieUsage( 'No stashed text found with the given hash', 'missingtext' );
76 } elseif ( $params['text'] !== null ) {
77 // Trim and fix newlines so the key SHA1's match (see WebRequest::getText())
78 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
79 $textHash = sha1( $text );
82 'The text or stashedtexthash parameter must be given', 'missingtextparam' );
85 $textContent = ContentHandler
::makeContent(
86 $text, $title, $params['contentmodel'], $params['contentformat'] );
88 $page = WikiPage
::factory( $title );
89 if ( $page->exists() ) {
90 // Page exists: get the merged content with the proposed change
91 $baseRev = Revision
::newFromPageId( $page->getId(), $params['baserevid'] );
93 $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
95 $currentRev = $page->getRevision();
97 $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
99 // Merge in the new version of the section to get the proposed version
100 $editContent = $page->replaceSectionAtRev(
103 $params['sectiontitle'],
106 if ( !$editContent ) {
107 $this->dieUsage( 'Could not merge updated section.', 'replacefailed' );
109 if ( $currentRev->getId() == $baseRev->getId() ) {
110 // Base revision was still the latest; nothing to merge
111 $content = $editContent;
113 // Merge the edit into the current version
114 $baseContent = $baseRev->getContent();
115 $currentContent = $currentRev->getContent();
116 if ( !$baseContent ||
!$currentContent ) {
117 $this->dieUsage( "Missing content for page ID {$page->getId()}", 'missingrev' );
119 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
120 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
123 // New pages: use the user-provided content model
124 $content = $textContent;
127 if ( !$content ) { // merge3() failed
128 $this->getResult()->addValue( null,
129 $this->getModuleName(), [ 'status' => 'editconflict' ] );
133 // The user will abort the AJAX request by pressing "save", so ignore that
134 ignore_user_abort( true );
136 if ( $user->pingLimiter( 'stashedit' ) ) {
137 $status = 'ratelimited';
139 $status = self
::parseAndStash( $page, $content, $user, $params['summary'] );
140 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
141 $cache->set( $textKey, $text, self
::MAX_CACHE_TTL
);
144 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
145 $stats->increment( "editstash.cache_stores.$status" );
147 $this->getResult()->addValue(
149 $this->getModuleName(),
152 'texthash' => $textHash
158 * @param WikiPage $page
159 * @param Content $content Edit content
161 * @param string $summary Edit summary
162 * @return integer ApiStashEdit::ERROR_* constant
165 public static function parseAndStash( WikiPage
$page, Content
$content, User
$user, $summary ) {
166 $cache = ObjectCache
::getLocalClusterInstance();
167 $logger = LoggerFactory
::getInstance( 'StashEdit' );
169 $title = $page->getTitle();
170 $key = self
::getStashKey( $title, self
::getContentHash( $content ), $user );
172 // Use the master DB for fast blocking locks
173 $dbw = wfGetDB( DB_MASTER
);
174 if ( !$dbw->lock( $key, __METHOD__
, 1 ) ) {
175 // De-duplicate requests on the same key
176 return self
::ERROR_BUSY
;
178 /** @noinspection PhpUnusedLocalVariableInspection */
179 $unlocker = new ScopedCallback( function () use ( $dbw, $key ) {
180 $dbw->unlock( $key, __METHOD__
);
183 $cutoffTime = time() - self
::PRESUME_FRESH_TTL_SEC
;
185 // Reuse any freshly build matching edit stash cache
186 $editInfo = $cache->get( $key );
187 if ( $editInfo && wfTimestamp( TS_UNIX
, $editInfo->timestamp
) >= $cutoffTime ) {
188 $alreadyCached = true;
190 $format = $content->getDefaultFormat();
191 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
192 $alreadyCached = false;
195 if ( $editInfo && $editInfo->output
) {
196 // Let extensions add ParserOutput metadata or warm other caches
197 Hooks
::run( 'ParserOutputStashForEdit',
198 [ $page, $content, $editInfo->output
, $summary, $user ] );
200 if ( $alreadyCached ) {
201 $logger->debug( "Already cached parser output for key '$key' ('$title')." );
202 return self
::ERROR_NONE
;
205 list( $stashInfo, $ttl, $code ) = self
::buildStashValue(
206 $editInfo->pstContent
,
208 $editInfo->timestamp
,
213 $ok = $cache->set( $key, $stashInfo, $ttl );
215 $logger->debug( "Cached parser output for key '$key' ('$title')." );
216 return self
::ERROR_NONE
;
218 $logger->error( "Failed to cache parser output for key '$key' ('$title')." );
219 return self
::ERROR_CACHE
;
222 $logger->info( "Uncacheable parser output for key '$key' ('$title') [$code]." );
223 return self
::ERROR_UNCACHEABLE
;
227 return self
::ERROR_PARSE
;
231 * Check that a prepared edit is in cache and still up-to-date
233 * This method blocks if the prepared edit is already being rendered,
234 * waiting until rendering finishes before doing final validity checks.
236 * The cache is rejected if template or file changes are detected.
237 * Note that foreign template or file transclusions are not checked.
239 * The result is a map (pstContent,output,timestamp) with fields
240 * extracted directly from WikiPage::prepareContentForEdit().
242 * @param Title $title
243 * @param Content $content
244 * @param User $user User to get parser options from
245 * @return stdClass|bool Returns false on cache miss
247 public static function checkCache( Title
$title, Content
$content, User
$user ) {
248 if ( $user->isBot() ) {
249 return false; // bots never stash - don't pollute stats
252 $cache = ObjectCache
::getLocalClusterInstance();
253 $logger = LoggerFactory
::getInstance( 'StashEdit' );
254 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
256 $key = self
::getStashKey( $title, self
::getContentHash( $content ), $user );
257 $editInfo = $cache->get( $key );
258 if ( !is_object( $editInfo ) ) {
259 $start = microtime( true );
260 // We ignore user aborts and keep parsing. Block on any prior parsing
261 // so as to use its results and make use of the time spent parsing.
262 // Skip this logic if there no master connection in case this method
263 // is called on an HTTP GET request for some reason.
264 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
265 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
266 if ( $dbw && $dbw->lock( $key, __METHOD__
, 30 ) ) {
267 $editInfo = $cache->get( $key );
268 $dbw->unlock( $key, __METHOD__
);
271 $timeMs = 1000 * max( 0, microtime( true ) - $start );
272 $stats->timing( 'editstash.lock_wait_time', $timeMs );
275 if ( !is_object( $editInfo ) ||
!$editInfo->output
) {
276 $stats->increment( 'editstash.cache_misses.no_stash' );
277 $logger->debug( "Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
281 $age = time() - wfTimestamp( TS_UNIX
, $editInfo->output
->getCacheTime() );
282 if ( $age <= self
::PRESUME_FRESH_TTL_SEC
) {
283 // Assume nothing changed in this time
284 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
285 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
286 } elseif ( isset( $editInfo->edits
) && $editInfo->edits
=== $user->getEditCount() ) {
287 // Logged-in user made no local upload/template edits in the meantime
288 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
289 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
290 } elseif ( $user->isAnon()
291 && self
::lastEditTime( $user ) < $editInfo->output
->getCacheTime()
293 // Logged-out user made no local upload/template edits in the meantime
294 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
295 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
297 // User may have changed included content
302 $stats->increment( 'editstash.cache_misses.proven_stale' );
303 $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
304 } elseif ( $editInfo->output
->getFlag( 'vary-revision' ) ) {
305 // This can be used for the initial parse, e.g. for filters or doEditContent(),
306 // but a second parse will be triggered in doEditUpdates(). This is not optimal.
307 $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
308 } elseif ( $editInfo->output
->getFlag( 'vary-revision-id' ) ) {
309 // Similar to the above if we didn't guess the ID correctly.
310 $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
318 * @return string|null TS_MW timestamp or null
320 private static function lastEditTime( User
$user ) {
321 $time = wfGetDB( DB_REPLICA
)->selectField(
324 [ 'rc_user_text' => $user->getName() ],
328 return wfTimestampOrNull( TS_MW
, $time );
332 * Get hash of the content, factoring in model/format
334 * @param Content $content
337 private static function getContentHash( Content
$content ) {
338 return sha1( implode( "\n", [
339 $content->getModel(),
340 $content->getDefaultFormat(),
341 $content->serialize( $content->getDefaultFormat() )
346 * Get the temporary prepared edit stash key for a user
348 * This key can be used for caching prepared edits provided:
349 * - a) The $user was used for PST options
350 * - b) The parser output was made from the PST using cannonical matching options
352 * @param Title $title
353 * @param string $contentHash Result of getContentHash()
354 * @param User $user User to get parser options from
357 private static function getStashKey( Title
$title, $contentHash, User
$user ) {
358 return ObjectCache
::getLocalClusterInstance()->makeKey(
360 md5( $title->getPrefixedDBkey() ),
361 // Account for the edit model/text
363 // Account for user name related variables like signatures
364 md5( $user->getId() . "\n" . $user->getName() )
369 * Build a value to store in memcached based on the PST content and parser output
371 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
373 * @param Content $pstContent Pre-Save transformed content
374 * @param ParserOutput $parserOutput
375 * @param string $timestamp TS_MW
377 * @return array (stash info array, TTL in seconds, info code) or (null, 0, info code)
379 private static function buildStashValue(
380 Content
$pstContent, ParserOutput
$parserOutput, $timestamp, User
$user
382 // If an item is renewed, mind the cache TTL determined by config and parser functions.
383 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
384 $since = time() - wfTimestamp( TS_UNIX
, $parserOutput->getTimestamp() );
385 $ttl = min( $parserOutput->getCacheExpiry() - $since, self
::MAX_CACHE_TTL
);
387 return [ null, 0, 'no_ttl' ];
390 // Only store what is actually needed
391 $stashInfo = (object)[
392 'pstContent' => $pstContent,
393 'output' => $parserOutput,
394 'timestamp' => $timestamp,
395 'edits' => $user->getEditCount()
398 return [ $stashInfo, $ttl, 'ok' ];
401 public function getAllowedParams() {
404 ApiBase
::PARAM_TYPE
=> 'string',
405 ApiBase
::PARAM_REQUIRED
=> true
408 ApiBase
::PARAM_TYPE
=> 'string',
411 ApiBase
::PARAM_TYPE
=> 'string'
414 ApiBase
::PARAM_TYPE
=> 'text',
415 ApiBase
::PARAM_DFLT
=> null
417 'stashedtexthash' => [
418 ApiBase
::PARAM_TYPE
=> 'string',
419 ApiBase
::PARAM_DFLT
=> null
422 ApiBase
::PARAM_TYPE
=> 'string',
425 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
426 ApiBase
::PARAM_REQUIRED
=> true
429 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
430 ApiBase
::PARAM_REQUIRED
=> true
433 ApiBase
::PARAM_TYPE
=> 'integer',
434 ApiBase
::PARAM_REQUIRED
=> true
439 public function needsToken() {
443 public function mustBePosted() {
447 public function isWriteMode() {
451 public function isInternal() {