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 public function execute() {
44 $user = $this->getUser();
45 $params = $this->extractRequestParams();
47 $page = $this->getTitleOrPageId( $params );
48 $title = $page->getTitle();
50 if ( !ContentHandler
::getForModelID( $params['contentmodel'] )
51 ->isSupportedFormat( $params['contentformat'] )
53 $this->dieUsage( "Unsupported content model/format", 'badmodelformat' );
56 // Trim and fix newlines so the key SHA1's match (see RequestContext::getText())
57 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
58 $textContent = ContentHandler
::makeContent(
59 $text, $title, $params['contentmodel'], $params['contentformat'] );
61 $page = WikiPage
::factory( $title );
62 if ( $page->exists() ) {
63 // Page exists: get the merged content with the proposed change
64 $baseRev = Revision
::newFromPageId( $page->getId(), $params['baserevid'] );
66 $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
68 $currentRev = $page->getRevision();
70 $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
72 // Merge in the new version of the section to get the proposed version
73 $editContent = $page->replaceSectionAtRev(
76 $params['sectiontitle'],
79 if ( !$editContent ) {
80 $this->dieUsage( "Could not merge updated section.", 'replacefailed' );
82 if ( $currentRev->getId() == $baseRev->getId() ) {
83 // Base revision was still the latest; nothing to merge
84 $content = $editContent;
86 // Merge the edit into the current version
87 $baseContent = $baseRev->getContent();
88 $currentContent = $currentRev->getContent();
89 if ( !$baseContent ||
!$currentContent ) {
90 $this->dieUsage( "Missing content for page ID {$page->getId()}", 'missingrev' );
92 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
93 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
96 // New pages: use the user-provided content model
97 $content = $textContent;
100 if ( !$content ) { // merge3() failed
101 $this->getResult()->addValue( null,
102 $this->getModuleName(), array( 'status' => 'editconflict' ) );
106 // The user will abort the AJAX request by pressing "save", so ignore that
107 ignore_user_abort( true );
109 // Use the master DB for fast blocking locks
110 $dbw = wfGetDB( DB_MASTER
);
112 // Get a key based on the source text, format, and user preferences
113 $key = self
::getStashKey( $title, $content, $user );
114 // De-duplicate requests on the same key
115 if ( $user->pingLimiter( 'stashedit' ) ) {
116 $status = 'ratelimited';
117 } elseif ( $dbw->lock( $key, __METHOD__
, 1 ) ) {
118 $status = self
::parseAndStash( $page, $content, $user );
119 $dbw->unlock( $key, __METHOD__
);
124 $this->getResult()->addValue( null, $this->getModuleName(), array( 'status' => $status ) );
128 * @param WikiPage $page
129 * @param Content $content
131 * @return integer ApiStashEdit::ERROR_* constant
134 public static function parseAndStash( WikiPage
$page, Content
$content, User
$user ) {
135 $cache = ObjectCache
::getLocalClusterInstance();
136 $logger = LoggerFactory
::getInstance( 'StashEdit' );
138 $format = $content->getDefaultFormat();
139 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
141 if ( $editInfo && $editInfo->output
) {
142 $key = self
::getStashKey( $page->getTitle(), $content, $user );
144 // Let extensions add ParserOutput metadata or warm other caches
145 Hooks
::run( 'ParserOutputStashForEdit', array( $page, $content, $editInfo->output
) );
147 list( $stashInfo, $ttl ) = self
::buildStashValue(
148 $editInfo->pstContent
, $editInfo->output
, $editInfo->timestamp
152 $ok = $cache->set( $key, $stashInfo, $ttl );
155 $logger->debug( "Cached parser output for key '$key'." );
156 return self
::ERROR_NONE
;
158 $logger->error( "Failed to cache parser output for key '$key'." );
159 return self
::ERROR_CACHE
;
162 $logger->info( "Uncacheable parser output for key '$key'." );
163 return self
::ERROR_UNCACHEABLE
;
167 return self
::ERROR_PARSE
;
171 * Attempt to cache PST content and corresponding parser output in passing
173 * This method can be called when the output was already generated for other
174 * reasons. Parsing should not be done just to call this method, however.
175 * $pstOpts must be that of the user doing the edit preview. If $pOpts does
176 * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
177 * will do nothing. Provided the values are cacheable, they will be stored
178 * in memcached so that final edit submission might make use of them.
180 * @param Page|Article|WikiPage $page Page title
181 * @param Content $content Proposed page content
182 * @param Content $pstContent The result of preSaveTransform() on $content
183 * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
184 * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
185 * @param ParserOptions $pOpts Options for $pOut
186 * @param string $timestamp TS_MW timestamp of parser output generation
187 * @return bool Success
189 public static function stashEditFromPreview(
190 Page
$page, Content
$content, Content
$pstContent, ParserOutput
$pOut,
191 ParserOptions
$pstOpts, ParserOptions
$pOpts, $timestamp
193 $cache = ObjectCache
::getLocalClusterInstance();
194 $logger = LoggerFactory
::getInstance( 'StashEdit' );
196 // getIsPreview() controls parser function behavior that references things
197 // like user/revision that don't exists yet. The user/text should already
198 // be set correctly by callers, just double check the preview flag.
199 if ( !$pOpts->getIsPreview() ) {
200 return false; // sanity
201 } elseif ( $pOpts->getIsSectionPreview() ) {
202 return false; // short-circuit (need the full content)
205 // PST parser options are for the user (handles signatures, etc...)
206 $user = $pstOpts->getUser();
207 // Get a key based on the source text, format, and user preferences
208 $key = self
::getStashKey( $page->getTitle(), $content, $user );
210 // Parser output options must match cannonical options.
211 // Treat some options as matching that are different but don't matter.
212 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
213 $canonicalPOpts->setIsPreview( true ); // force match
214 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
215 if ( !$pOpts->matches( $canonicalPOpts ) ) {
216 $logger->info( "Uncacheable preview output for key '$key' (options)." );
220 // Build a value to cache with a proper TTL
221 list( $stashInfo, $ttl ) = self
::buildStashValue( $pstContent, $pOut, $timestamp );
223 $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
227 $ok = $cache->set( $key, $stashInfo, $ttl );
229 $logger->error( "Failed to cache preview parser output for key '$key'." );
231 $logger->debug( "Cached preview output for key '$key'." );
238 * Check that a prepared edit is in cache and still up-to-date
240 * This method blocks if the prepared edit is already being rendered,
241 * waiting until rendering finishes before doing final validity checks.
243 * The cache is rejected if template or file changes are detected.
244 * Note that foreign template or file transclusions are not checked.
246 * The result is a map (pstContent,output,timestamp) with fields
247 * extracted directly from WikiPage::prepareContentForEdit().
249 * @param Title $title
250 * @param Content $content
251 * @param User $user User to get parser options from
252 * @return stdClass|bool Returns false on cache miss
254 public static function checkCache( Title
$title, Content
$content, User
$user ) {
255 $cache = ObjectCache
::getLocalClusterInstance();
256 $logger = LoggerFactory
::getInstance( 'StashEdit' );
257 $stats = RequestContext
::getMain()->getStats();
259 $key = self
::getStashKey( $title, $content, $user );
260 $editInfo = $cache->get( $key );
261 if ( !is_object( $editInfo ) ) {
262 $start = microtime( true );
263 // We ignore user aborts and keep parsing. Block on any prior parsing
264 // so as to use its results and make use of the time spent parsing.
265 // Skip this logic if there no master connection in case this method
266 // is called on an HTTP GET request for some reason.
268 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
269 if ( $dbw && $dbw->lock( $key, __METHOD__
, 30 ) ) {
270 $editInfo = $cache->get( $key );
271 $dbw->unlock( $key, __METHOD__
);
274 $timeMs = 1000 * max( 0, microtime( true ) - $start );
275 $stats->timing( 'editstash.lock-wait-time', $timeMs );
278 if ( !is_object( $editInfo ) ||
!$editInfo->output
) {
279 $stats->increment( 'editstash.cache-misses' );
280 $logger->debug( "No cache value for key '$key'." );
284 $time = wfTimestamp( TS_UNIX
, $editInfo->output
->getTimestamp() );
285 if ( ( time() - $time ) <= 3 ) {
286 $stats->increment( 'editstash.cache-hits' );
287 $logger->debug( "Timestamp-based cache hit for key '$key'." );
288 return $editInfo; // assume nothing changed
291 $dbr = wfGetDB( DB_SLAVE
);
293 $templates = array(); // conditions to find changes/creations
294 $templateUses = 0; // expected existing templates
295 foreach ( $editInfo->output
->getTemplateIds() as $ns => $stuff ) {
296 foreach ( $stuff as $dbkey => $revId ) {
297 $templates[(string)$ns][$dbkey] = (int)$revId;
301 // Check that no templates used in the output changed...
302 if ( count( $templates ) ) {
305 array( 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ),
306 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
310 foreach ( $res as $row ) {
311 $changed = $changed ||
( $row->page_latest
!= $templates[$row->ns
][$row->dbk
] );
314 if ( $changed ||
$res->numRows() != $templateUses ) {
315 $stats->increment( 'editstash.cache-misses' );
316 $logger->info( "Stale cache for key '$key'; template changed." );
321 $files = array(); // conditions to find changes/creations
322 foreach ( $editInfo->output
->getFileSearchOptions() as $name => $options ) {
323 $files[$name] = (string)$options['sha1'];
325 // Check that no files used in the output changed...
326 if ( count( $files ) ) {
329 array( 'name' => 'img_name', 'img_sha1' ),
330 array( 'img_name' => array_keys( $files ) ),
334 foreach ( $res as $row ) {
335 $changed = $changed ||
( $row->img_sha1
!= $files[$row->name
] );
338 if ( $changed ||
$res->numRows() != count( $files ) ) {
339 $stats->increment( 'editstash.cache-misses' );
340 $logger->info( "Stale cache for key '$key'; file changed." );
345 $stats->increment( 'editstash.cache-hits' );
346 $logger->debug( "Cache hit for key '$key'." );
352 * Get the temporary prepared edit stash key for a user
354 * This key can be used for caching prepared edits provided:
355 * - a) The $user was used for PST options
356 * - b) The parser output was made from the PST using cannonical matching options
358 * @param Title $title
359 * @param Content $content
360 * @param User $user User to get parser options from
363 protected static function getStashKey( Title
$title, Content
$content, User
$user ) {
364 $hash = sha1( implode( ':', array(
365 $content->getModel(),
366 $content->getDefaultFormat(),
367 sha1( $content->serialize( $content->getDefaultFormat() ) ),
368 $user->getId() ?
: md5( $user->getName() ), // account for user parser options
369 $user->getId() ?
$user->getDBTouched() : '-' // handle preference change races
372 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
376 * Build a value to store in memcached based on the PST content and parser output
378 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
380 * @param Content $pstContent
381 * @param ParserOutput $parserOutput
382 * @param string $timestamp TS_MW
383 * @return array (stash info array, TTL in seconds) or (null, 0)
385 protected static function buildStashValue(
386 Content
$pstContent, ParserOutput
$parserOutput, $timestamp
388 // If an item is renewed, mind the cache TTL determined by config and parser functions
389 $since = time() - wfTimestamp( TS_UNIX
, $parserOutput->getTimestamp() );
390 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
392 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
393 // Only store what is actually needed
394 $stashInfo = (object)array(
395 'pstContent' => $pstContent,
396 'output' => $parserOutput,
397 'timestamp' => $timestamp
399 return array( $stashInfo, $ttl );
402 return array( null, 0 );
405 public function getAllowedParams() {
408 ApiBase
::PARAM_TYPE
=> 'string',
409 ApiBase
::PARAM_REQUIRED
=> true
412 ApiBase
::PARAM_TYPE
=> 'string',
414 'sectiontitle' => array(
415 ApiBase
::PARAM_TYPE
=> 'string'
418 ApiBase
::PARAM_TYPE
=> 'text',
419 ApiBase
::PARAM_REQUIRED
=> true
421 'contentmodel' => array(
422 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
423 ApiBase
::PARAM_REQUIRED
=> true
425 'contentformat' => array(
426 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
427 ApiBase
::PARAM_REQUIRED
=> true
429 'baserevid' => array(
430 ApiBase
::PARAM_TYPE
=> 'integer',
431 ApiBase
::PARAM_REQUIRED
=> true
436 function needsToken() {
440 function mustBePosted() {
444 function isWriteMode() {
448 function isInternal() {