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 * Check that a prepared edit is in cache and still up-to-date
187 * This method blocks if the prepared edit is already being rendered,
188 * waiting until rendering finishes before doing final validity checks.
190 * The cache is rejected if template or file changes are detected.
191 * Note that foreign template or file transclusions are not checked.
193 * The result is a map (pstContent,output,timestamp) with fields
194 * extracted directly from WikiPage::prepareContentForEdit().
196 * @param Title $title
197 * @param Content $content
198 * @param User $user User to get parser options from
199 * @return stdClass|bool Returns false on cache miss
201 public static function checkCache( Title
$title, Content
$content, User
$user ) {
202 if ( $user->isBot() ) {
203 return false; // bots never stash - don't pollute stats
206 $cache = ObjectCache
::getLocalClusterInstance();
207 $logger = LoggerFactory
::getInstance( 'StashEdit' );
208 $stats = RequestContext
::getMain()->getStats();
210 $key = self
::getStashKey( $title, $content, $user );
211 $editInfo = $cache->get( $key );
212 if ( !is_object( $editInfo ) ) {
213 $start = microtime( true );
214 // We ignore user aborts and keep parsing. Block on any prior parsing
215 // so as to use its results and make use of the time spent parsing.
216 // Skip this logic if there no master connection in case this method
217 // is called on an HTTP GET request for some reason.
219 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
220 if ( $dbw && $dbw->lock( $key, __METHOD__
, 30 ) ) {
221 $editInfo = $cache->get( $key );
222 $dbw->unlock( $key, __METHOD__
);
225 $timeMs = 1000 * max( 0, microtime( true ) - $start );
226 $stats->timing( 'editstash.lock_wait_time', $timeMs );
229 if ( !is_object( $editInfo ) ||
!$editInfo->output
) {
230 $stats->increment( 'editstash.cache_misses.no_stash' );
231 $logger->debug( "Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
235 $age = time() - wfTimestamp( TS_UNIX
, $editInfo->output
->getCacheTime() );
236 if ( $age <= self
::PRESUME_FRESH_TTL_SEC
) {
237 // Assume nothing changed in this time
238 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
239 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
240 } elseif ( isset( $editInfo->edits
) && $editInfo->edits
=== $user->getEditCount() ) {
241 // Logged-in user made no local upload/template edits in the meantime
242 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
243 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
244 } elseif ( $user->isAnon()
245 && self
::lastEditTime( $user ) < $editInfo->output
->getCacheTime()
247 // Logged-out user made no local upload/template edits in the meantime
248 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
249 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
251 // User may have changed included content
256 $stats->increment( 'editstash.cache_misses.proven_stale' );
257 $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
258 } elseif ( $editInfo->output
->getFlag( 'vary-revision' ) ) {
259 // This can be used for the initial parse, e.g. for filters or doEditContent(),
260 // but a second parse will be triggered in doEditUpdates(). This is not optimal.
261 $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
262 } elseif ( $editInfo->output
->getFlag( 'vary-revision-id' ) ) {
263 // Similar to the above if we didn't guess the ID correctly.
264 $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
272 * @return string|null TS_MW timestamp or null
274 private static function lastEditTime( User
$user ) {
275 $time = wfGetDB( DB_SLAVE
)->selectField(
278 [ 'rc_user_text' => $user->getName() ],
282 return wfTimestampOrNull( TS_MW
, $time );
286 * Get the temporary prepared edit stash key for a user
288 * This key can be used for caching prepared edits provided:
289 * - a) The $user was used for PST options
290 * - b) The parser output was made from the PST using cannonical matching options
292 * @param Title $title
293 * @param Content $content
294 * @param User $user User to get parser options from
297 private static function getStashKey( Title
$title, Content
$content, User
$user ) {
298 $hash = sha1( implode( ':', [
299 // Account for the edit model/text
300 $content->getModel(),
301 $content->getDefaultFormat(),
302 sha1( $content->serialize( $content->getDefaultFormat() ) ),
303 // Account for user name related variables like signatures
305 md5( $user->getName() )
308 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
312 * Build a value to store in memcached based on the PST content and parser output
314 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
316 * @param Content $pstContent
317 * @param ParserOutput $parserOutput
318 * @param string $timestamp TS_MW
320 * @return array (stash info array, TTL in seconds, info code) or (null, 0, info code)
322 private static function buildStashValue(
323 Content
$pstContent, ParserOutput
$parserOutput, $timestamp, User
$user
325 // If an item is renewed, mind the cache TTL determined by config and parser functions.
326 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
327 $since = time() - wfTimestamp( TS_UNIX
, $parserOutput->getTimestamp() );
328 $ttl = min( $parserOutput->getCacheExpiry() - $since, self
::MAX_CACHE_TTL
);
330 return [ null, 0, 'no_ttl' ];
333 // Only store what is actually needed
334 $stashInfo = (object)[
335 'pstContent' => $pstContent,
336 'output' => $parserOutput,
337 'timestamp' => $timestamp,
338 'edits' => $user->getEditCount()
341 return [ $stashInfo, $ttl, 'ok' ];
344 public function getAllowedParams() {
347 ApiBase
::PARAM_TYPE
=> 'string',
348 ApiBase
::PARAM_REQUIRED
=> true
351 ApiBase
::PARAM_TYPE
=> 'string',
354 ApiBase
::PARAM_TYPE
=> 'string'
357 ApiBase
::PARAM_TYPE
=> 'text',
358 ApiBase
::PARAM_REQUIRED
=> true
361 ApiBase
::PARAM_TYPE
=> 'string',
364 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
365 ApiBase
::PARAM_REQUIRED
=> true
368 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
369 ApiBase
::PARAM_REQUIRED
=> true
372 ApiBase
::PARAM_TYPE
=> 'integer',
373 ApiBase
::PARAM_REQUIRED
=> true
378 public function needsToken() {
382 public function mustBePosted() {
386 public function isWriteMode() {
390 public function isInternal() {