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 $cache = ObjectCache
::getLocalClusterInstance();
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(), array( 'status' => 'editconflict' ) );
108 // The user will abort the AJAX request by pressing "save", so ignore that
109 ignore_user_abort( true );
111 // Get a key based on the source text, format, and user preferences
112 $key = self
::getStashKey( $title, $content, $user );
113 // De-duplicate requests on the same key
114 if ( $user->pingLimiter( 'stashedit' ) ) {
115 $status = 'ratelimited';
116 } elseif ( $cache->lock( $key, 0, 30 ) ) {
117 /** @noinspection PhpUnusedLocalVariableInspection */
118 $unlocker = new ScopedCallback( function() use ( $cache, $key ) {
119 $cache->unlock( $key );
121 $status = self
::parseAndStash( $page, $content, $user );
126 $this->getResult()->addValue( null, $this->getModuleName(), array( '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 list( $stashInfo, $ttl ) = self
::buildStashValue(
147 $editInfo->pstContent
, $editInfo->output
, $editInfo->timestamp
151 $ok = $cache->set( $key, $stashInfo, $ttl );
153 $logger->debug( "Cached parser output for key '$key'." );
154 return self
::ERROR_NONE
;
156 $logger->error( "Failed to cache parser output for key '$key'." );
157 return self
::ERROR_CACHE
;
160 $logger->info( "Uncacheable parser output for key '$key'." );
161 return self
::ERROR_UNCACHEABLE
;
165 return self
::ERROR_PARSE
;
169 * Attempt to cache PST content and corresponding parser output in passing
171 * This method can be called when the output was already generated for other
172 * reasons. Parsing should not be done just to call this method, however.
173 * $pstOpts must be that of the user doing the edit preview. If $pOpts does
174 * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
175 * will do nothing. Provided the values are cacheable, they will be stored
176 * in memcached so that final edit submission might make use of them.
178 * @param Page|Article|WikiPage $page Page title
179 * @param Content $content Proposed page content
180 * @param Content $pstContent The result of preSaveTransform() on $content
181 * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
182 * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
183 * @param ParserOptions $pOpts Options for $pOut
184 * @param string $timestamp TS_MW timestamp of parser output generation
185 * @return bool Success
187 public static function stashEditFromPreview(
188 Page
$page, Content
$content, Content
$pstContent, ParserOutput
$pOut,
189 ParserOptions
$pstOpts, ParserOptions
$pOpts, $timestamp
191 $cache = ObjectCache
::getLocalClusterInstance();
192 $logger = LoggerFactory
::getInstance( 'StashEdit' );
194 // getIsPreview() controls parser function behavior that references things
195 // like user/revision that don't exists yet. The user/text should already
196 // be set correctly by callers, just double check the preview flag.
197 if ( !$pOpts->getIsPreview() ) {
198 return false; // sanity
199 } elseif ( $pOpts->getIsSectionPreview() ) {
200 return false; // short-circuit (need the full content)
203 // PST parser options are for the user (handles signatures, etc...)
204 $user = $pstOpts->getUser();
205 // Get a key based on the source text, format, and user preferences
206 $key = self
::getStashKey( $page->getTitle(), $content, $user );
208 // Parser output options must match cannonical options.
209 // Treat some options as matching that are different but don't matter.
210 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
211 $canonicalPOpts->setIsPreview( true ); // force match
212 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
213 if ( !$pOpts->matches( $canonicalPOpts ) ) {
214 $logger->info( "Uncacheable preview output for key '$key' (options)." );
218 // Build a value to cache with a proper TTL
219 list( $stashInfo, $ttl ) = self
::buildStashValue( $pstContent, $pOut, $timestamp );
221 $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
225 $ok = $cache->set( $key, $stashInfo, $ttl );
227 $logger->error( "Failed to cache preview parser output for key '$key'." );
229 $logger->debug( "Cached preview output for key '$key'." );
236 * Check that a prepared edit is in cache and still up-to-date
238 * This method blocks if the prepared edit is already being rendered,
239 * waiting until rendering finishes before doing final validity checks.
241 * The cache is rejected if template or file changes are detected.
242 * Note that foreign template or file transclusions are not checked.
244 * The result is a map (pstContent,output,timestamp) with fields
245 * extracted directly from WikiPage::prepareContentForEdit().
247 * @param Title $title
248 * @param Content $content
249 * @param User $user User to get parser options from
250 * @return stdClass|bool Returns false on cache miss
252 public static function checkCache( Title
$title, Content
$content, User
$user ) {
253 $cache = ObjectCache
::getLocalClusterInstance();
254 $logger = LoggerFactory
::getInstance( 'StashEdit' );
256 $key = self
::getStashKey( $title, $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 it's results and make use of the time spent parsing.
262 if ( $cache->lock( $key, 30, 30 ) ) {
263 $editInfo = $cache->get( $key );
264 $cache->unlock( $key );
266 $sec = microtime( true ) - $start;
268 $logger->warning( "Waited $sec seconds on '$key'." );
272 if ( !is_object( $editInfo ) ||
!$editInfo->output
) {
273 $logger->debug( "No cache value for key '$key'." );
277 $time = wfTimestamp( TS_UNIX
, $editInfo->output
->getTimestamp() );
278 if ( ( time() - $time ) <= 3 ) {
279 $logger->debug( "Timestamp-based cache hit for key '$key'." );
280 return $editInfo; // assume nothing changed
283 $dbr = wfGetDB( DB_SLAVE
);
285 $templates = array(); // conditions to find changes/creations
286 $templateUses = 0; // expected existing templates
287 foreach ( $editInfo->output
->getTemplateIds() as $ns => $stuff ) {
288 foreach ( $stuff as $dbkey => $revId ) {
289 $templates[(string)$ns][$dbkey] = (int)$revId;
293 // Check that no templates used in the output changed...
294 if ( count( $templates ) ) {
297 array( 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ),
298 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
302 foreach ( $res as $row ) {
303 $changed = $changed ||
( $row->page_latest
!= $templates[$row->ns
][$row->dbk
] );
306 if ( $changed ||
$res->numRows() != $templateUses ) {
307 $logger->info( "Stale cache for key '$key'; template changed." );
312 $files = array(); // conditions to find changes/creations
313 foreach ( $editInfo->output
->getFileSearchOptions() as $name => $options ) {
314 $files[$name] = (string)$options['sha1'];
316 // Check that no files used in the output changed...
317 if ( count( $files ) ) {
320 array( 'name' => 'img_name', 'img_sha1' ),
321 array( 'img_name' => array_keys( $files ) ),
325 foreach ( $res as $row ) {
326 $changed = $changed ||
( $row->img_sha1
!= $files[$row->name
] );
329 if ( $changed ||
$res->numRows() != count( $files ) ) {
330 $logger->info( "Stale cache for key '$key'; file changed." );
335 $logger->debug( "Cache hit for key '$key'." );
341 * Get the temporary prepared edit stash key for a user
343 * This key can be used for caching prepared edits provided:
344 * - a) The $user was used for PST options
345 * - b) The parser output was made from the PST using cannonical matching options
347 * @param Title $title
348 * @param Content $content
349 * @param User $user User to get parser options from
352 protected static function getStashKey( Title
$title, Content
$content, User
$user ) {
353 $hash = sha1( implode( ':', array(
354 $content->getModel(),
355 $content->getDefaultFormat(),
356 sha1( $content->serialize( $content->getDefaultFormat() ) ),
357 $user->getId() ?
: md5( $user->getName() ), // account for user parser options
358 $user->getId() ?
$user->getDBTouched() : '-' // handle preference change races
361 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
365 * Build a value to store in memcached based on the PST content and parser output
367 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
369 * @param Content $pstContent
370 * @param ParserOutput $parserOutput
371 * @param string $timestamp TS_MW
372 * @return array (stash info array, TTL in seconds) or (null, 0)
374 protected static function buildStashValue(
375 Content
$pstContent, ParserOutput
$parserOutput, $timestamp
377 // If an item is renewed, mind the cache TTL determined by config and parser functions
378 $since = time() - wfTimestamp( TS_UNIX
, $parserOutput->getTimestamp() );
379 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
381 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
382 // Only store what is actually needed
383 $stashInfo = (object)array(
384 'pstContent' => $pstContent,
385 'output' => $parserOutput,
386 'timestamp' => $timestamp
388 return array( $stashInfo, $ttl );
391 return array( null, 0 );
394 public function getAllowedParams() {
397 ApiBase
::PARAM_TYPE
=> 'string',
398 ApiBase
::PARAM_REQUIRED
=> true
401 ApiBase
::PARAM_TYPE
=> 'string',
403 'sectiontitle' => array(
404 ApiBase
::PARAM_TYPE
=> 'string'
407 ApiBase
::PARAM_TYPE
=> 'text',
408 ApiBase
::PARAM_REQUIRED
=> true
410 'contentmodel' => array(
411 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
412 ApiBase
::PARAM_REQUIRED
=> true
414 'contentformat' => array(
415 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
416 ApiBase
::PARAM_REQUIRED
=> true
418 'baserevid' => array(
419 ApiBase
::PARAM_TYPE
=> 'integer',
420 ApiBase
::PARAM_REQUIRED
=> true
425 function needsToken() {
429 function mustBePosted() {
433 function isInternal() {