wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / api / ApiStashEdit.php
blob8822750ac9d74d678e3a3aec8d07797927e19e2b
1 <?php
2 /**
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
18 * @file
19 * @author Aaron Schulz
22 use MediaWiki\Logger\LoggerFactory;
24 /**
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.
34 * @ingroup API
35 * @since 1.25
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'] )
52 ) {
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'] );
65 if ( !$baseRev ) {
66 $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
68 $currentRev = $page->getRevision();
69 if ( !$currentRev ) {
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(
74 $params['section'],
75 $textContent,
76 $params['sectiontitle'],
77 $baseRev->getId()
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;
85 } else {
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 );
95 } else {
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' ) );
103 return;
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__ );
120 } else {
121 $status = 'busy';
124 $this->getResult()->addValue( null, $this->getModuleName(), array( 'status' => $status ) );
128 * @param WikiPage $page
129 * @param Content $content
130 * @param User $user
131 * @return integer ApiStashEdit::ERROR_* constant
132 * @since 1.25
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 list( $stashInfo, $ttl ) = self::buildStashValue(
145 $editInfo->pstContent, $editInfo->output, $editInfo->timestamp
148 if ( $stashInfo ) {
149 $ok = $cache->set( $key, $stashInfo, $ttl );
150 if ( $ok ) {
151 $logger->debug( "Cached parser output for key '$key'." );
152 return self::ERROR_NONE;
153 } else {
154 $logger->error( "Failed to cache parser output for key '$key'." );
155 return self::ERROR_CACHE;
157 } else {
158 $logger->info( "Uncacheable parser output for key '$key'." );
159 return self::ERROR_UNCACHEABLE;
163 return self::ERROR_PARSE;
167 * Attempt to cache PST content and corresponding parser output in passing
169 * This method can be called when the output was already generated for other
170 * reasons. Parsing should not be done just to call this method, however.
171 * $pstOpts must be that of the user doing the edit preview. If $pOpts does
172 * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
173 * will do nothing. Provided the values are cacheable, they will be stored
174 * in memcached so that final edit submission might make use of them.
176 * @param Page|Article|WikiPage $page Page title
177 * @param Content $content Proposed page content
178 * @param Content $pstContent The result of preSaveTransform() on $content
179 * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
180 * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
181 * @param ParserOptions $pOpts Options for $pOut
182 * @param string $timestamp TS_MW timestamp of parser output generation
183 * @return bool Success
185 public static function stashEditFromPreview(
186 Page $page, Content $content, Content $pstContent, ParserOutput $pOut,
187 ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp
189 $cache = ObjectCache::getLocalClusterInstance();
190 $logger = LoggerFactory::getInstance( 'StashEdit' );
192 // getIsPreview() controls parser function behavior that references things
193 // like user/revision that don't exists yet. The user/text should already
194 // be set correctly by callers, just double check the preview flag.
195 if ( !$pOpts->getIsPreview() ) {
196 return false; // sanity
197 } elseif ( $pOpts->getIsSectionPreview() ) {
198 return false; // short-circuit (need the full content)
201 // PST parser options are for the user (handles signatures, etc...)
202 $user = $pstOpts->getUser();
203 // Get a key based on the source text, format, and user preferences
204 $key = self::getStashKey( $page->getTitle(), $content, $user );
206 // Parser output options must match cannonical options.
207 // Treat some options as matching that are different but don't matter.
208 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
209 $canonicalPOpts->setIsPreview( true ); // force match
210 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
211 if ( !$pOpts->matches( $canonicalPOpts ) ) {
212 $logger->info( "Uncacheable preview output for key '$key' (options)." );
213 return false;
216 // Build a value to cache with a proper TTL
217 list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp );
218 if ( !$stashInfo ) {
219 $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
220 return false;
223 $ok = $cache->set( $key, $stashInfo, $ttl );
224 if ( !$ok ) {
225 $logger->error( "Failed to cache preview parser output for key '$key'." );
226 } else {
227 $logger->debug( "Cached preview output for key '$key'." );
230 return $ok;
234 * Check that a prepared edit is in cache and still up-to-date
236 * This method blocks if the prepared edit is already being rendered,
237 * waiting until rendering finishes before doing final validity checks.
239 * The cache is rejected if template or file changes are detected.
240 * Note that foreign template or file transclusions are not checked.
242 * The result is a map (pstContent,output,timestamp) with fields
243 * extracted directly from WikiPage::prepareContentForEdit().
245 * @param Title $title
246 * @param Content $content
247 * @param User $user User to get parser options from
248 * @return stdClass|bool Returns false on cache miss
250 public static function checkCache( Title $title, Content $content, User $user ) {
251 $cache = ObjectCache::getLocalClusterInstance();
252 $logger = LoggerFactory::getInstance( 'StashEdit' );
253 $stats = RequestContext::getMain()->getStats();
255 $key = self::getStashKey( $title, $content, $user );
256 $editInfo = $cache->get( $key );
257 if ( !is_object( $editInfo ) ) {
258 $start = microtime( true );
259 // We ignore user aborts and keep parsing. Block on any prior parsing
260 // so as to use its results and make use of the time spent parsing.
261 // Skip this logic if there no master connection in case this method
262 // is called on an HTTP GET request for some reason.
263 $lb = wfGetLB();
264 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
265 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
266 $editInfo = $cache->get( $key );
267 $dbw->unlock( $key, __METHOD__ );
270 $timeMs = 1000 * max( 0, microtime( true ) - $start );
271 $stats->timing( 'editstash.lock-wait-time', $timeMs );
274 if ( !is_object( $editInfo ) || !$editInfo->output ) {
275 $stats->increment( 'editstash.cache-misses' );
276 $logger->debug( "No cache value for key '$key'." );
277 return false;
280 $time = wfTimestamp( TS_UNIX, $editInfo->output->getTimestamp() );
281 if ( ( time() - $time ) <= 3 ) {
282 $stats->increment( 'editstash.cache-hits' );
283 $logger->debug( "Timestamp-based cache hit for key '$key'." );
284 return $editInfo; // assume nothing changed
287 $dbr = wfGetDB( DB_SLAVE );
289 $templates = array(); // conditions to find changes/creations
290 $templateUses = 0; // expected existing templates
291 foreach ( $editInfo->output->getTemplateIds() as $ns => $stuff ) {
292 foreach ( $stuff as $dbkey => $revId ) {
293 $templates[(string)$ns][$dbkey] = (int)$revId;
294 ++$templateUses;
297 // Check that no templates used in the output changed...
298 if ( count( $templates ) ) {
299 $res = $dbr->select(
300 'page',
301 array( 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ),
302 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
303 __METHOD__
305 $changed = false;
306 foreach ( $res as $row ) {
307 $changed = $changed || ( $row->page_latest != $templates[$row->ns][$row->dbk] );
310 if ( $changed || $res->numRows() != $templateUses ) {
311 $stats->increment( 'editstash.cache-misses' );
312 $logger->info( "Stale cache for key '$key'; template changed." );
313 return false;
317 $files = array(); // conditions to find changes/creations
318 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
319 $files[$name] = (string)$options['sha1'];
321 // Check that no files used in the output changed...
322 if ( count( $files ) ) {
323 $res = $dbr->select(
324 'image',
325 array( 'name' => 'img_name', 'img_sha1' ),
326 array( 'img_name' => array_keys( $files ) ),
327 __METHOD__
329 $changed = false;
330 foreach ( $res as $row ) {
331 $changed = $changed || ( $row->img_sha1 != $files[$row->name] );
334 if ( $changed || $res->numRows() != count( $files ) ) {
335 $stats->increment( 'editstash.cache-misses' );
336 $logger->info( "Stale cache for key '$key'; file changed." );
337 return false;
341 $stats->increment( 'editstash.cache-hits' );
342 $logger->debug( "Cache hit for key '$key'." );
344 return $editInfo;
348 * Get the temporary prepared edit stash key for a user
350 * This key can be used for caching prepared edits provided:
351 * - a) The $user was used for PST options
352 * - b) The parser output was made from the PST using cannonical matching options
354 * @param Title $title
355 * @param Content $content
356 * @param User $user User to get parser options from
357 * @return string
359 protected static function getStashKey( Title $title, Content $content, User $user ) {
360 $hash = sha1( implode( ':', array(
361 $content->getModel(),
362 $content->getDefaultFormat(),
363 sha1( $content->serialize( $content->getDefaultFormat() ) ),
364 $user->getId() ?: md5( $user->getName() ), // account for user parser options
365 $user->getId() ? $user->getDBTouched() : '-' // handle preference change races
366 ) ) );
368 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
372 * Build a value to store in memcached based on the PST content and parser output
374 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
376 * @param Content $pstContent
377 * @param ParserOutput $parserOutput
378 * @param string $timestamp TS_MW
379 * @return array (stash info array, TTL in seconds) or (null, 0)
381 protected static function buildStashValue(
382 Content $pstContent, ParserOutput $parserOutput, $timestamp
384 // If an item is renewed, mind the cache TTL determined by config and parser functions
385 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
386 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
388 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
389 // Only store what is actually needed
390 $stashInfo = (object)array(
391 'pstContent' => $pstContent,
392 'output' => $parserOutput,
393 'timestamp' => $timestamp
395 return array( $stashInfo, $ttl );
398 return array( null, 0 );
401 public function getAllowedParams() {
402 return array(
403 'title' => array(
404 ApiBase::PARAM_TYPE => 'string',
405 ApiBase::PARAM_REQUIRED => true
407 'section' => array(
408 ApiBase::PARAM_TYPE => 'string',
410 'sectiontitle' => array(
411 ApiBase::PARAM_TYPE => 'string'
413 'text' => array(
414 ApiBase::PARAM_TYPE => 'text',
415 ApiBase::PARAM_REQUIRED => true
417 'contentmodel' => array(
418 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
419 ApiBase::PARAM_REQUIRED => true
421 'contentformat' => array(
422 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
423 ApiBase::PARAM_REQUIRED => true
425 'baserevid' => array(
426 ApiBase::PARAM_TYPE => 'integer',
427 ApiBase::PARAM_REQUIRED => true
432 function needsToken() {
433 return 'csrf';
436 function mustBePosted() {
437 return true;
440 function isWriteMode() {
441 return true;
444 function isInternal() {
445 return true;