Merge "AutoloadGenerator.php: Update 'AutoloadClasses' in extension.json"
[lhc/web/wiklou.git] / includes / api / ApiStashEdit.php
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @author Aaron Schulz
20 */
21
22 /**
23 * Prepare and edit in shared cache so that it can be reused on edit
24 *
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.
31 *
32 * @ingroup API
33 * @since 1.25
34 */
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';
40
41 public function execute() {
42 global $wgMemc;
43
44 $user = $this->getUser();
45 $params = $this->extractRequestParams();
46
47 $page = $this->getTitleOrPageId( $params );
48 $title = $page->getTitle();
49
50 if ( !ContentHandler::getForModelID( $params['contentmodel'] )
51 ->isSupportedFormat( $params['contentformat'] )
52 ) {
53 $this->dieUsage( "Unsupported content model/format", 'badmodelformat' );
54 }
55
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'] );
60
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' );
67 }
68 $currentRev = $page->getRevision();
69 if ( !$currentRev ) {
70 $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
71 }
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()
78 );
79 if ( !$editContent ) {
80 $this->dieUsage( "Could not merge updated section.", 'replacefailed' );
81 }
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' );
91 }
92 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
93 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
94 }
95 } else {
96 // New pages: use the user-provided content model
97 $content = $textContent;
98 }
99
100 if ( !$content ) { // merge3() failed
101 $this->getResult()->addValue( null,
102 $this->getModuleName(), array( 'status' => 'editconflict' ) );
103 return;
104 }
105
106 // The user will abort the AJAX request by pressing "save", so ignore that
107 ignore_user_abort( true );
108
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 $unlocker = new ScopedCallback( function() use ( $key ) {
116 global $wgMemc;
117 $wgMemc->unlock( $key );
118 } );
119 $status = self::parseAndStash( $page, $content, $user );
120 } else {
121 $status = 'busy';
122 }
123
124 $this->getResult()->addValue( null, $this->getModuleName(), array( 'status' => $status ) );
125 }
126
127 /**
128 * @param WikiPage $page
129 * @param Content $content
130 * @param User $user
131 * @return integer ApiStashEdit::ERROR_* constant
132 * @since 1.25
133 */
134 public static function parseAndStash( WikiPage $page, Content $content, User $user ) {
135 global $wgMemc;
136
137 $format = $content->getDefaultFormat();
138 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
139
140 if ( $editInfo && $editInfo->output ) {
141 $key = self::getStashKey( $page->getTitle(), $content, $user );
142
143 list( $stashInfo, $ttl ) = self::buildStashValue(
144 $editInfo->pstContent, $editInfo->output, $editInfo->timestamp
145 );
146
147 if ( $stashInfo ) {
148 $ok = $wgMemc->set( $key, $stashInfo, $ttl );
149 if ( $ok ) {
150 wfDebugLog( 'StashEdit', "Cached parser output for key '$key'." );
151 return self::ERROR_NONE;
152 } else {
153 wfDebugLog( 'StashEdit', "Failed to cache parser output for key '$key'." );
154 return self::ERROR_CACHE;
155 }
156 } else {
157 wfDebugLog( 'StashEdit', "Uncacheable parser output for key '$key'." );
158 return self::ERROR_UNCACHEABLE;
159 }
160 }
161
162 return self::ERROR_PARSE;
163 }
164
165 /**
166 * Attempt to cache PST content and corresponding parser output in passing
167 *
168 * This method can be called when the output was already generated for other
169 * reasons. Parsing should not be done just to call this method, however.
170 * $pstOpts must be that of the user doing the edit preview. If $pOpts does
171 * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
172 * will do nothing. Provided the values are cacheable, they will be stored
173 * in memcached so that final edit submission might make use of them.
174 *
175 * @param Article|WikiPage $page Page title
176 * @param Content $content Proposed page content
177 * @param Content $pstContent The result of preSaveTransform() on $content
178 * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
179 * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
180 * @param ParserOptions $pOpts Options for $pOut
181 * @param string $timestamp TS_MW timestamp of parser output generation
182 * @return bool Success
183 */
184 public static function stashEditFromPreview(
185 Page $page, Content $content, Content $pstContent, ParserOutput $pOut,
186 ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp
187 ) {
188 global $wgMemc;
189
190 // getIsPreview() controls parser function behavior that references things
191 // like user/revision that don't exists yet. The user/text should already
192 // be set correctly by callers, just double check the preview flag.
193 if ( !$pOpts->getIsPreview() ) {
194 return false; // sanity
195 } elseif ( $pOpts->getIsSectionPreview() ) {
196 return false; // short-circuit (need the full content)
197 }
198
199 // PST parser options are for the user (handles signatures, etc...)
200 $user = $pstOpts->getUser();
201 // Get a key based on the source text, format, and user preferences
202 $key = self::getStashKey( $page->getTitle(), $content, $user );
203
204 // Parser output options must match cannonical options.
205 // Treat some options as matching that are different but don't matter.
206 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
207 $canonicalPOpts->setIsPreview( true ); // force match
208 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
209 if ( !$pOpts->matches( $canonicalPOpts ) ) {
210 wfDebugLog( 'StashEdit', "Uncacheable preview output for key '$key' (options)." );
211 return false;
212 }
213
214 // Build a value to cache with a proper TTL
215 list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp );
216 if ( !$stashInfo ) {
217 wfDebugLog( 'StashEdit', "Uncacheable parser output for key '$key' (rev/TTL)." );
218 return false;
219 }
220
221 $ok = $wgMemc->set( $key, $stashInfo, $ttl );
222 if ( !$ok ) {
223 wfDebugLog( 'StashEdit', "Failed to cache preview parser output for key '$key'." );
224 } else {
225 wfDebugLog( 'StashEdit', "Cached preview output for key '$key'." );
226 }
227
228 return $ok;
229 }
230
231 /**
232 * Check that a prepared edit is in cache and still up-to-date
233 *
234 * This method blocks if the prepared edit is already being rendered,
235 * waiting until rendering finishes before doing final validity checks.
236 *
237 * The cache is rejected if template or file changes are detected.
238 * Note that foreign template or file transclusions are not checked.
239 *
240 * The result is a map (pstContent,output,timestamp) with fields
241 * extracted directly from WikiPage::prepareContentForEdit().
242 *
243 * @param Title $title
244 * @param Content $content
245 * @param User $user User to get parser options from
246 * @return stdClass|bool Returns false on cache miss
247 */
248 public static function checkCache( Title $title, Content $content, User $user ) {
249 global $wgMemc;
250
251 $key = self::getStashKey( $title, $content, $user );
252 $editInfo = $wgMemc->get( $key );
253 if ( !is_object( $editInfo ) ) {
254 $start = microtime( true );
255 // We ignore user aborts and keep parsing. Block on any prior parsing
256 // so as to use it's results and make use of the time spent parsing.
257 if ( $wgMemc->lock( $key, 30, 30 ) ) {
258 $editInfo = $wgMemc->get( $key );
259 $wgMemc->unlock( $key );
260 }
261 $sec = microtime( true ) - $start;
262 if ( $sec > .01 ) {
263 wfDebugLog( 'StashEdit', "Waited $sec seconds on '$key'." );
264 }
265 }
266
267 if ( !is_object( $editInfo ) || !$editInfo->output ) {
268 wfDebugLog( 'StashEdit', "No cache value for key '$key'." );
269 return false;
270 }
271
272 $time = wfTimestamp( TS_UNIX, $editInfo->output->getTimestamp() );
273 if ( ( time() - $time ) <= 3 ) {
274 wfDebugLog( 'StashEdit', "Timestamp-based cache hit for key '$key'." );
275 return $editInfo; // assume nothing changed
276 }
277
278 $dbr = wfGetDB( DB_SLAVE );
279 // Check that no templates used in the output changed...
280 $cWhr = array(); // conditions to find changes/creations
281 $dWhr = array(); // conditions to find deletions
282 foreach ( $editInfo->output->getTemplateIds() as $ns => $stuff ) {
283 foreach ( $stuff as $dbkey => $revId ) {
284 $cWhr[] = array( 'page_namespace' => $ns, 'page_title' => $dbkey,
285 'page_latest != ' . intval( $revId ) );
286 $dWhr[] = array( 'page_namespace' => $ns, 'page_title' => $dbkey );
287 }
288 }
289 $change = $dbr->selectField( 'page', '1', $dbr->makeList( $cWhr, LIST_OR ), __METHOD__ );
290 $n = $dbr->selectField( 'page', 'COUNT(*)', $dbr->makeList( $dWhr, LIST_OR ), __METHOD__ );
291 if ( $change || $n != count( $dWhr ) ) {
292 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; template changed." );
293 return false;
294 }
295
296 // Check that no files used in the output changed...
297 $cWhr = array(); // conditions to find changes/creations
298 $dWhr = array(); // conditions to find deletions
299 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
300 $cWhr[] = array( 'img_name' => $dbkey,
301 'img_sha1 != ' . $dbr->addQuotes( strval( $options['sha1'] ) ) );
302 $dWhr[] = array( 'img_name' => $dbkey );
303 }
304 $change = $dbr->selectField( 'image', '1', $dbr->makeList( $cWhr, LIST_OR ), __METHOD__ );
305 $n = $dbr->selectField( 'image', 'COUNT(*)', $dbr->makeList( $dWhr, LIST_OR ), __METHOD__ );
306 if ( $change || $n != count( $dWhr ) ) {
307 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; file changed." );
308 return false;
309 }
310
311 wfDebugLog( 'StashEdit', "Cache hit for key '$key'." );
312
313 return $editInfo;
314 }
315
316 /**
317 * Get the temporary prepared edit stash key for a user
318 *
319 * This key can be used for caching prepared edits provided:
320 * - a) The $user was used for PST options
321 * - b) The parser output was made from the PST using cannonical matching options
322 *
323 * @param Title $title
324 * @param Content $content
325 * @param User $user User to get parser options from
326 * @return string
327 */
328 protected static function getStashKey( Title $title, Content $content, User $user ) {
329 $hash = sha1( implode( ':', array(
330 $content->getModel(),
331 $content->getDefaultFormat(),
332 sha1( $content->serialize( $content->getDefaultFormat() ) ),
333 $user->getId() ?: md5( $user->getName() ), // account for user parser options
334 $user->getId() ? $user->getDBTouched() : '-' // handle preference change races
335 ) ) );
336
337 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
338 }
339
340 /**
341 * Build a value to store in memcached based on the PST content and parser output
342 *
343 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
344 *
345 * @param Content $pstContent
346 * @param ParserOutput $parserOutput
347 * @param string $timestamp TS_MW
348 * @return array (stash info array, TTL in seconds) or (null, 0)
349 */
350 protected static function buildStashValue(
351 Content $pstContent, ParserOutput $parserOutput, $timestamp
352 ) {
353 // If an item is renewed, mind the cache TTL determined by config and parser functions
354 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
355 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
356
357 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
358 // Only store what is actually needed
359 $stashInfo = (object)array(
360 'pstContent' => $pstContent,
361 'output' => $parserOutput,
362 'timestamp' => $timestamp
363 );
364 return array( $stashInfo, $ttl );
365 }
366
367 return array( null, 0 );
368 }
369
370 public function getAllowedParams() {
371 return array(
372 'title' => array(
373 ApiBase::PARAM_TYPE => 'string',
374 ApiBase::PARAM_REQUIRED => true
375 ),
376 'section' => array(
377 ApiBase::PARAM_TYPE => 'string',
378 ),
379 'sectiontitle' => array(
380 ApiBase::PARAM_TYPE => 'string'
381 ),
382 'text' => array(
383 ApiBase::PARAM_TYPE => 'text',
384 ApiBase::PARAM_REQUIRED => true
385 ),
386 'contentmodel' => array(
387 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
388 ApiBase::PARAM_REQUIRED => true
389 ),
390 'contentformat' => array(
391 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
392 ApiBase::PARAM_REQUIRED => true
393 ),
394 'baserevid' => array(
395 ApiBase::PARAM_TYPE => 'integer',
396 ApiBase::PARAM_REQUIRED => true
397 )
398 );
399 }
400
401 function needsToken() {
402 return 'csrf';
403 }
404
405 function mustBePosted() {
406 return true;
407 }
408
409 function isInternal() {
410 return true;
411 }
412 }