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
23 * Prepare and edit in shared cache so that it can be reused on edit
25 * This endpoint can be called via AJAX as the user focuses on the edit
26 * summary box. By the time of submission, the parse may have already
27 * finished, and can be immediately used on page save. Certain parser
28 * functions like {{REVISIONID}} or {{CURRENTTIME}} may cause the cache
29 * to not be used on edit. Template and files used are check for changes
30 * since the output was generated. The cache TTL is also kept low for sanity.
35 class ApiStashEdit
extends ApiBase
{
36 const ERROR_NONE
= 'stashed';
37 const ERROR_PARSE
= 'error_parse';
38 const ERROR_CACHE
= 'error_cache';
39 const ERROR_UNCACHEABLE
= 'uncacheable';
41 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 // Get a key based on the source text, format, and user preferences
110 $key = self
::getStashKey( $title, $content, $user );
111 // De-duplicate requests on the same key
112 if ( $user->pingLimiter( 'stashedit' ) ) {
113 $status = 'ratelimited';
114 } elseif ( $wgMemc->lock( $key, 0, 30 ) ) {
115 /** @noinspection PhpUnusedLocalVariableInspection */
116 $unlocker = new ScopedCallback( function() use ( $key ) {
118 $wgMemc->unlock( $key );
120 $status = self
::parseAndStash( $page, $content, $user );
125 $this->getResult()->addValue( null, $this->getModuleName(), array( 'status' => $status ) );
129 * @param WikiPage $page
130 * @param Content $content
132 * @return integer ApiStashEdit::ERROR_* constant
135 public static function parseAndStash( WikiPage
$page, Content
$content, User
$user ) {
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
149 $ok = $wgMemc->set( $key, $stashInfo, $ttl );
151 wfDebugLog( 'StashEdit', "Cached parser output for key '$key'." );
152 return self
::ERROR_NONE
;
154 wfDebugLog( 'StashEdit', "Failed to cache parser output for key '$key'." );
155 return self
::ERROR_CACHE
;
158 wfDebugLog( 'StashEdit', "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 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
191 // getIsPreview() controls parser function behavior that references things
192 // like user/revision that don't exists yet. The user/text should already
193 // be set correctly by callers, just double check the preview flag.
194 if ( !$pOpts->getIsPreview() ) {
195 return false; // sanity
196 } elseif ( $pOpts->getIsSectionPreview() ) {
197 return false; // short-circuit (need the full content)
200 // PST parser options are for the user (handles signatures, etc...)
201 $user = $pstOpts->getUser();
202 // Get a key based on the source text, format, and user preferences
203 $key = self
::getStashKey( $page->getTitle(), $content, $user );
205 // Parser output options must match cannonical options.
206 // Treat some options as matching that are different but don't matter.
207 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
208 $canonicalPOpts->setIsPreview( true ); // force match
209 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
210 if ( !$pOpts->matches( $canonicalPOpts ) ) {
211 wfDebugLog( 'StashEdit', "Uncacheable preview output for key '$key' (options)." );
215 // Build a value to cache with a proper TTL
216 list( $stashInfo, $ttl ) = self
::buildStashValue( $pstContent, $pOut, $timestamp );
218 wfDebugLog( 'StashEdit', "Uncacheable parser output for key '$key' (rev/TTL)." );
222 $ok = $wgMemc->set( $key, $stashInfo, $ttl );
224 wfDebugLog( 'StashEdit', "Failed to cache preview parser output for key '$key'." );
226 wfDebugLog( 'StashEdit', "Cached preview output for key '$key'." );
233 * Check that a prepared edit is in cache and still up-to-date
235 * This method blocks if the prepared edit is already being rendered,
236 * waiting until rendering finishes before doing final validity checks.
238 * The cache is rejected if template or file changes are detected.
239 * Note that foreign template or file transclusions are not checked.
241 * The result is a map (pstContent,output,timestamp) with fields
242 * extracted directly from WikiPage::prepareContentForEdit().
244 * @param Title $title
245 * @param Content $content
246 * @param User $user User to get parser options from
247 * @return stdClass|bool Returns false on cache miss
249 public static function checkCache( Title
$title, Content
$content, User
$user ) {
252 $key = self
::getStashKey( $title, $content, $user );
253 $editInfo = $wgMemc->get( $key );
254 if ( !is_object( $editInfo ) ) {
255 $start = microtime( true );
256 // We ignore user aborts and keep parsing. Block on any prior parsing
257 // so as to use it's results and make use of the time spent parsing.
258 if ( $wgMemc->lock( $key, 30, 30 ) ) {
259 $editInfo = $wgMemc->get( $key );
260 $wgMemc->unlock( $key );
262 $sec = microtime( true ) - $start;
264 wfDebugLog( 'StashEdit', "Waited $sec seconds on '$key'." );
268 if ( !is_object( $editInfo ) ||
!$editInfo->output
) {
269 wfDebugLog( 'StashEdit', "No cache value for key '$key'." );
273 $time = wfTimestamp( TS_UNIX
, $editInfo->output
->getTimestamp() );
274 if ( ( time() - $time ) <= 3 ) {
275 wfDebugLog( 'StashEdit', "Timestamp-based cache hit for key '$key'." );
276 return $editInfo; // assume nothing changed
279 $dbr = wfGetDB( DB_SLAVE
);
281 $templates = array(); // conditions to find changes/creations
282 $templateUses = 0; // expected existing templates
283 foreach ( $editInfo->output
->getTemplateIds() as $ns => $stuff ) {
284 foreach ( $stuff as $dbkey => $revId ) {
285 $templates[(string)$ns][$dbkey] = (int)$revId;
289 // Check that no templates used in the output changed...
290 if ( count( $templates ) ) {
293 array( 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ),
294 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
298 foreach ( $res as $row ) {
299 $changed = $changed ||
( $row->page_latest
!= $templates[$row->ns
][$row->dbk
] );
302 if ( $changed ||
$res->numRows() != $templateUses ) {
303 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; template changed." );
308 $files = array(); // conditions to find changes/creations
309 foreach ( $editInfo->output
->getFileSearchOptions() as $name => $options ) {
310 $files[$name] = (string)$options['sha1'];
312 // Check that no files used in the output changed...
313 if ( count( $files ) ) {
316 array( 'name' => 'img_name', 'img_sha1' ),
317 array( 'img_name' => array_keys( $files ) ),
321 foreach ( $res as $row ) {
322 $changed = $changed ||
( $row->img_sha1
!= $files[$row->name
] );
325 if ( $changed ||
$res->numRows() != count( $files ) ) {
326 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; file changed." );
331 wfDebugLog( 'StashEdit', "Cache hit for key '$key'." );
337 * Get the temporary prepared edit stash key for a user
339 * This key can be used for caching prepared edits provided:
340 * - a) The $user was used for PST options
341 * - b) The parser output was made from the PST using cannonical matching options
343 * @param Title $title
344 * @param Content $content
345 * @param User $user User to get parser options from
348 protected static function getStashKey( Title
$title, Content
$content, User
$user ) {
349 $hash = sha1( implode( ':', array(
350 $content->getModel(),
351 $content->getDefaultFormat(),
352 sha1( $content->serialize( $content->getDefaultFormat() ) ),
353 $user->getId() ?
: md5( $user->getName() ), // account for user parser options
354 $user->getId() ?
$user->getDBTouched() : '-' // handle preference change races
357 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
361 * Build a value to store in memcached based on the PST content and parser output
363 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
365 * @param Content $pstContent
366 * @param ParserOutput $parserOutput
367 * @param string $timestamp TS_MW
368 * @return array (stash info array, TTL in seconds) or (null, 0)
370 protected static function buildStashValue(
371 Content
$pstContent, ParserOutput
$parserOutput, $timestamp
373 // If an item is renewed, mind the cache TTL determined by config and parser functions
374 $since = time() - wfTimestamp( TS_UNIX
, $parserOutput->getTimestamp() );
375 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
377 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
378 // Only store what is actually needed
379 $stashInfo = (object)array(
380 'pstContent' => $pstContent,
381 'output' => $parserOutput,
382 'timestamp' => $timestamp
384 return array( $stashInfo, $ttl );
387 return array( null, 0 );
390 public function getAllowedParams() {
393 ApiBase
::PARAM_TYPE
=> 'string',
394 ApiBase
::PARAM_REQUIRED
=> true
397 ApiBase
::PARAM_TYPE
=> 'string',
399 'sectiontitle' => array(
400 ApiBase
::PARAM_TYPE
=> 'string'
403 ApiBase
::PARAM_TYPE
=> 'text',
404 ApiBase
::PARAM_REQUIRED
=> true
406 'contentmodel' => array(
407 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
408 ApiBase
::PARAM_REQUIRED
=> true
410 'contentformat' => array(
411 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
412 ApiBase
::PARAM_REQUIRED
=> true
414 'baserevid' => array(
415 ApiBase
::PARAM_TYPE
=> 'integer',
416 ApiBase
::PARAM_REQUIRED
=> true
421 function needsToken() {
425 function mustBePosted() {
429 function isInternal() {