Merge "Don't check namespace in SpecialWantedtemplates"
[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 /** @noinspection PhpUnusedLocalVariableInspection */
116 $unlocker = new ScopedCallback( function() use ( $key ) {
117 global $wgMemc;
118 $wgMemc->unlock( $key );
119 } );
120 $status = self::parseAndStash( $page, $content, $user );
121 } else {
122 $status = 'busy';
123 }
124
125 $this->getResult()->addValue( null, $this->getModuleName(), array( 'status' => $status ) );
126 }
127
128 /**
129 * @param WikiPage $page
130 * @param Content $content
131 * @param User $user
132 * @return integer ApiStashEdit::ERROR_* constant
133 * @since 1.25
134 */
135 public static function parseAndStash( WikiPage $page, Content $content, User $user ) {
136 global $wgMemc;
137
138 $format = $content->getDefaultFormat();
139 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
140
141 if ( $editInfo && $editInfo->output ) {
142 $key = self::getStashKey( $page->getTitle(), $content, $user );
143
144 list( $stashInfo, $ttl ) = self::buildStashValue(
145 $editInfo->pstContent, $editInfo->output, $editInfo->timestamp
146 );
147
148 if ( $stashInfo ) {
149 $ok = $wgMemc->set( $key, $stashInfo, $ttl );
150 if ( $ok ) {
151 wfDebugLog( 'StashEdit', "Cached parser output for key '$key'." );
152 return self::ERROR_NONE;
153 } else {
154 wfDebugLog( 'StashEdit', "Failed to cache parser output for key '$key'." );
155 return self::ERROR_CACHE;
156 }
157 } else {
158 wfDebugLog( 'StashEdit', "Uncacheable parser output for key '$key'." );
159 return self::ERROR_UNCACHEABLE;
160 }
161 }
162
163 return self::ERROR_PARSE;
164 }
165
166 /**
167 * Attempt to cache PST content and corresponding parser output in passing
168 *
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.
175 *
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
184 */
185 public static function stashEditFromPreview(
186 Page $page, Content $content, Content $pstContent, ParserOutput $pOut,
187 ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp
188 ) {
189 global $wgMemc;
190
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)
198 }
199
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 );
204
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)." );
212 return false;
213 }
214
215 // Build a value to cache with a proper TTL
216 list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp );
217 if ( !$stashInfo ) {
218 wfDebugLog( 'StashEdit', "Uncacheable parser output for key '$key' (rev/TTL)." );
219 return false;
220 }
221
222 $ok = $wgMemc->set( $key, $stashInfo, $ttl );
223 if ( !$ok ) {
224 wfDebugLog( 'StashEdit', "Failed to cache preview parser output for key '$key'." );
225 } else {
226 wfDebugLog( 'StashEdit', "Cached preview output for key '$key'." );
227 }
228
229 return $ok;
230 }
231
232 /**
233 * Check that a prepared edit is in cache and still up-to-date
234 *
235 * This method blocks if the prepared edit is already being rendered,
236 * waiting until rendering finishes before doing final validity checks.
237 *
238 * The cache is rejected if template or file changes are detected.
239 * Note that foreign template or file transclusions are not checked.
240 *
241 * The result is a map (pstContent,output,timestamp) with fields
242 * extracted directly from WikiPage::prepareContentForEdit().
243 *
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
248 */
249 public static function checkCache( Title $title, Content $content, User $user ) {
250 global $wgMemc;
251
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 );
261 }
262 $sec = microtime( true ) - $start;
263 if ( $sec > .01 ) {
264 wfDebugLog( 'StashEdit', "Waited $sec seconds on '$key'." );
265 }
266 }
267
268 if ( !is_object( $editInfo ) || !$editInfo->output ) {
269 wfDebugLog( 'StashEdit', "No cache value for key '$key'." );
270 return false;
271 }
272
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
277 }
278
279 $dbr = wfGetDB( DB_SLAVE );
280
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;
286 ++$templateUses;
287 }
288 }
289 // Check that no templates used in the output changed...
290 if ( count( $templates ) ) {
291 $res = $dbr->select(
292 'page',
293 array( 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ),
294 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
295 __METHOD__
296 );
297 $changed = false;
298 foreach ( $res as $row ) {
299 $changed = $changed || ( $row->page_latest != $templates[$row->ns][$row->dbk] );
300 }
301
302 if ( $changed || $res->numRows() != $templateUses ) {
303 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; template changed." );
304 return false;
305 }
306 }
307
308 $files = array(); // conditions to find changes/creations
309 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
310 $files[$name] = (string)$options['sha1'];
311 }
312 // Check that no files used in the output changed...
313 if ( count( $files ) ) {
314 $res = $dbr->select(
315 'image',
316 array( 'name' => 'img_name', 'img_sha1' ),
317 array( 'img_name' => array_keys( $files ) ),
318 __METHOD__
319 );
320 $changed = false;
321 foreach ( $res as $row ) {
322 $changed = $changed || ( $row->img_sha1 != $files[$row->name] );
323 }
324
325 if ( $changed || $res->numRows() != count( $files ) ) {
326 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; file changed." );
327 return false;
328 }
329 }
330
331 wfDebugLog( 'StashEdit', "Cache hit for key '$key'." );
332
333 return $editInfo;
334 }
335
336 /**
337 * Get the temporary prepared edit stash key for a user
338 *
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
342 *
343 * @param Title $title
344 * @param Content $content
345 * @param User $user User to get parser options from
346 * @return string
347 */
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
355 ) ) );
356
357 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
358 }
359
360 /**
361 * Build a value to store in memcached based on the PST content and parser output
362 *
363 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
364 *
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)
369 */
370 protected static function buildStashValue(
371 Content $pstContent, ParserOutput $parserOutput, $timestamp
372 ) {
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 );
376
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
383 );
384 return array( $stashInfo, $ttl );
385 }
386
387 return array( null, 0 );
388 }
389
390 public function getAllowedParams() {
391 return array(
392 'title' => array(
393 ApiBase::PARAM_TYPE => 'string',
394 ApiBase::PARAM_REQUIRED => true
395 ),
396 'section' => array(
397 ApiBase::PARAM_TYPE => 'string',
398 ),
399 'sectiontitle' => array(
400 ApiBase::PARAM_TYPE => 'string'
401 ),
402 'text' => array(
403 ApiBase::PARAM_TYPE => 'text',
404 ApiBase::PARAM_REQUIRED => true
405 ),
406 'contentmodel' => array(
407 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
408 ApiBase::PARAM_REQUIRED => true
409 ),
410 'contentformat' => array(
411 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
412 ApiBase::PARAM_REQUIRED => true
413 ),
414 'baserevid' => array(
415 ApiBase::PARAM_TYPE => 'integer',
416 ApiBase::PARAM_REQUIRED => true
417 )
418 );
419 }
420
421 function needsToken() {
422 return 'csrf';
423 }
424
425 function mustBePosted() {
426 return true;
427 }
428
429 function isInternal() {
430 return true;
431 }
432 }