Merge "HTMLForm: Add 'title' type"
[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
280 $templates = array(); // conditions to find changes/creations
281 $templateUses = 0; // expected existing templates
282 foreach ( $editInfo->output->getTemplateIds() as $ns => $stuff ) {
283 foreach ( $stuff as $dbkey => $revId ) {
284 $templates[(string)$ns][$dbkey] = (int)$revId;
285 ++$templateUses;
286 }
287 }
288 // Check that no templates used in the output changed...
289 if ( count( $templates ) ) {
290 $res = $dbr->select(
291 'page',
292 array( 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ),
293 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
294 __METHOD__
295 );
296 $changed = false;
297 foreach ( $res as $row ) {
298 $changed = $changed || ( $row->page_latest != $templates[$row->ns][$row->dbk] );
299 }
300
301 if ( $changed || $res->numRows() != $templateUses ) {
302 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; template changed." );
303 return false;
304 }
305 }
306
307 $files = array(); // conditions to find changes/creations
308 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
309 $files[$name] = (string)$options['sha1'];
310 }
311 // Check that no files used in the output changed...
312 if ( count( $files ) ) {
313 $res = $dbr->select(
314 'image',
315 array( 'name' => 'img_name', 'img_sha1' ),
316 array( 'img_name' => array_keys( $files ) ),
317 __METHOD__
318 );
319 $changed = false;
320 foreach ( $res as $row ) {
321 $changed = $changed || ( $row->img_sha1 != $files[$row->name] );
322 }
323
324 if ( $changed || $res->numRows() != count( $files ) ) {
325 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; file changed." );
326 return false;
327 }
328 }
329
330 wfDebugLog( 'StashEdit', "Cache hit for key '$key'." );
331
332 return $editInfo;
333 }
334
335 /**
336 * Get the temporary prepared edit stash key for a user
337 *
338 * This key can be used for caching prepared edits provided:
339 * - a) The $user was used for PST options
340 * - b) The parser output was made from the PST using cannonical matching options
341 *
342 * @param Title $title
343 * @param Content $content
344 * @param User $user User to get parser options from
345 * @return string
346 */
347 protected static function getStashKey( Title $title, Content $content, User $user ) {
348 $hash = sha1( implode( ':', array(
349 $content->getModel(),
350 $content->getDefaultFormat(),
351 sha1( $content->serialize( $content->getDefaultFormat() ) ),
352 $user->getId() ?: md5( $user->getName() ), // account for user parser options
353 $user->getId() ? $user->getDBTouched() : '-' // handle preference change races
354 ) ) );
355
356 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
357 }
358
359 /**
360 * Build a value to store in memcached based on the PST content and parser output
361 *
362 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
363 *
364 * @param Content $pstContent
365 * @param ParserOutput $parserOutput
366 * @param string $timestamp TS_MW
367 * @return array (stash info array, TTL in seconds) or (null, 0)
368 */
369 protected static function buildStashValue(
370 Content $pstContent, ParserOutput $parserOutput, $timestamp
371 ) {
372 // If an item is renewed, mind the cache TTL determined by config and parser functions
373 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
374 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
375
376 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
377 // Only store what is actually needed
378 $stashInfo = (object)array(
379 'pstContent' => $pstContent,
380 'output' => $parserOutput,
381 'timestamp' => $timestamp
382 );
383 return array( $stashInfo, $ttl );
384 }
385
386 return array( null, 0 );
387 }
388
389 public function getAllowedParams() {
390 return array(
391 'title' => array(
392 ApiBase::PARAM_TYPE => 'string',
393 ApiBase::PARAM_REQUIRED => true
394 ),
395 'section' => array(
396 ApiBase::PARAM_TYPE => 'string',
397 ),
398 'sectiontitle' => array(
399 ApiBase::PARAM_TYPE => 'string'
400 ),
401 'text' => array(
402 ApiBase::PARAM_TYPE => 'text',
403 ApiBase::PARAM_REQUIRED => true
404 ),
405 'contentmodel' => array(
406 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
407 ApiBase::PARAM_REQUIRED => true
408 ),
409 'contentformat' => array(
410 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
411 ApiBase::PARAM_REQUIRED => true
412 ),
413 'baserevid' => array(
414 ApiBase::PARAM_TYPE => 'integer',
415 ApiBase::PARAM_REQUIRED => true
416 )
417 );
418 }
419
420 function needsToken() {
421 return 'csrf';
422 }
423
424 function mustBePosted() {
425 return true;
426 }
427
428 function isInternal() {
429 return true;
430 }
431 }