Merge "Don't trigger 'wikipage.diff' hook for content that looks like a diff"
[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 use MediaWiki\Logger\LoggerFactory;
23
24 /**
25 * Prepare an edit in shared cache so that it can be reused on edit
26 *
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.
33 *
34 * @ingroup API
35 * @since 1.25
36 */
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';
42
43 public function execute() {
44 $cache = ObjectCache::getLocalClusterInstance();
45
46 $user = $this->getUser();
47 $params = $this->extractRequestParams();
48
49 $page = $this->getTitleOrPageId( $params );
50 $title = $page->getTitle();
51
52 if ( !ContentHandler::getForModelID( $params['contentmodel'] )
53 ->isSupportedFormat( $params['contentformat'] )
54 ) {
55 $this->dieUsage( "Unsupported content model/format", 'badmodelformat' );
56 }
57
58 // Trim and fix newlines so the key SHA1's match (see RequestContext::getText())
59 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
60 $textContent = ContentHandler::makeContent(
61 $text, $title, $params['contentmodel'], $params['contentformat'] );
62
63 $page = WikiPage::factory( $title );
64 if ( $page->exists() ) {
65 // Page exists: get the merged content with the proposed change
66 $baseRev = Revision::newFromPageId( $page->getId(), $params['baserevid'] );
67 if ( !$baseRev ) {
68 $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
69 }
70 $currentRev = $page->getRevision();
71 if ( !$currentRev ) {
72 $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
73 }
74 // Merge in the new version of the section to get the proposed version
75 $editContent = $page->replaceSectionAtRev(
76 $params['section'],
77 $textContent,
78 $params['sectiontitle'],
79 $baseRev->getId()
80 );
81 if ( !$editContent ) {
82 $this->dieUsage( "Could not merge updated section.", 'replacefailed' );
83 }
84 if ( $currentRev->getId() == $baseRev->getId() ) {
85 // Base revision was still the latest; nothing to merge
86 $content = $editContent;
87 } else {
88 // Merge the edit into the current version
89 $baseContent = $baseRev->getContent();
90 $currentContent = $currentRev->getContent();
91 if ( !$baseContent || !$currentContent ) {
92 $this->dieUsage( "Missing content for page ID {$page->getId()}", 'missingrev' );
93 }
94 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
95 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
96 }
97 } else {
98 // New pages: use the user-provided content model
99 $content = $textContent;
100 }
101
102 if ( !$content ) { // merge3() failed
103 $this->getResult()->addValue( null,
104 $this->getModuleName(), array( 'status' => 'editconflict' ) );
105 return;
106 }
107
108 // The user will abort the AJAX request by pressing "save", so ignore that
109 ignore_user_abort( true );
110
111 // Use the master DB for fast blocking locks
112 $dbw = wfGetDB( DB_MASTER );
113
114 // Get a key based on the source text, format, and user preferences
115 $key = self::getStashKey( $title, $content, $user );
116 // De-duplicate requests on the same key
117 if ( $user->pingLimiter( 'stashedit' ) ) {
118 $status = 'ratelimited';
119 } elseif ( $dbw->lock( $key, __METHOD__, 1 ) ) {
120 $status = self::parseAndStash( $page, $content, $user );
121 $dbw->unlock( $key, __METHOD__ );
122 } else {
123 $status = 'busy';
124 }
125
126 $this->getResult()->addValue( null, $this->getModuleName(), array( 'status' => $status ) );
127 }
128
129 /**
130 * @param WikiPage $page
131 * @param Content $content
132 * @param User $user
133 * @return integer ApiStashEdit::ERROR_* constant
134 * @since 1.25
135 */
136 public static function parseAndStash( WikiPage $page, Content $content, User $user ) {
137 $cache = ObjectCache::getLocalClusterInstance();
138 $logger = LoggerFactory::getInstance( 'StashEdit' );
139
140 $format = $content->getDefaultFormat();
141 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
142
143 if ( $editInfo && $editInfo->output ) {
144 $key = self::getStashKey( $page->getTitle(), $content, $user );
145
146 list( $stashInfo, $ttl ) = self::buildStashValue(
147 $editInfo->pstContent, $editInfo->output, $editInfo->timestamp
148 );
149
150 if ( $stashInfo ) {
151 $ok = $cache->set( $key, $stashInfo, $ttl );
152 if ( $ok ) {
153 $logger->debug( "Cached parser output for key '$key'." );
154 return self::ERROR_NONE;
155 } else {
156 $logger->error( "Failed to cache parser output for key '$key'." );
157 return self::ERROR_CACHE;
158 }
159 } else {
160 $logger->info( "Uncacheable parser output for key '$key'." );
161 return self::ERROR_UNCACHEABLE;
162 }
163 }
164
165 return self::ERROR_PARSE;
166 }
167
168 /**
169 * Attempt to cache PST content and corresponding parser output in passing
170 *
171 * This method can be called when the output was already generated for other
172 * reasons. Parsing should not be done just to call this method, however.
173 * $pstOpts must be that of the user doing the edit preview. If $pOpts does
174 * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
175 * will do nothing. Provided the values are cacheable, they will be stored
176 * in memcached so that final edit submission might make use of them.
177 *
178 * @param Page|Article|WikiPage $page Page title
179 * @param Content $content Proposed page content
180 * @param Content $pstContent The result of preSaveTransform() on $content
181 * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
182 * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
183 * @param ParserOptions $pOpts Options for $pOut
184 * @param string $timestamp TS_MW timestamp of parser output generation
185 * @return bool Success
186 */
187 public static function stashEditFromPreview(
188 Page $page, Content $content, Content $pstContent, ParserOutput $pOut,
189 ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp
190 ) {
191 $cache = ObjectCache::getLocalClusterInstance();
192 $logger = LoggerFactory::getInstance( 'StashEdit' );
193
194 // getIsPreview() controls parser function behavior that references things
195 // like user/revision that don't exists yet. The user/text should already
196 // be set correctly by callers, just double check the preview flag.
197 if ( !$pOpts->getIsPreview() ) {
198 return false; // sanity
199 } elseif ( $pOpts->getIsSectionPreview() ) {
200 return false; // short-circuit (need the full content)
201 }
202
203 // PST parser options are for the user (handles signatures, etc...)
204 $user = $pstOpts->getUser();
205 // Get a key based on the source text, format, and user preferences
206 $key = self::getStashKey( $page->getTitle(), $content, $user );
207
208 // Parser output options must match cannonical options.
209 // Treat some options as matching that are different but don't matter.
210 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
211 $canonicalPOpts->setIsPreview( true ); // force match
212 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
213 if ( !$pOpts->matches( $canonicalPOpts ) ) {
214 $logger->info( "Uncacheable preview output for key '$key' (options)." );
215 return false;
216 }
217
218 // Build a value to cache with a proper TTL
219 list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp );
220 if ( !$stashInfo ) {
221 $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
222 return false;
223 }
224
225 $ok = $cache->set( $key, $stashInfo, $ttl );
226 if ( !$ok ) {
227 $logger->error( "Failed to cache preview parser output for key '$key'." );
228 } else {
229 $logger->debug( "Cached preview output for key '$key'." );
230 }
231
232 return $ok;
233 }
234
235 /**
236 * Check that a prepared edit is in cache and still up-to-date
237 *
238 * This method blocks if the prepared edit is already being rendered,
239 * waiting until rendering finishes before doing final validity checks.
240 *
241 * The cache is rejected if template or file changes are detected.
242 * Note that foreign template or file transclusions are not checked.
243 *
244 * The result is a map (pstContent,output,timestamp) with fields
245 * extracted directly from WikiPage::prepareContentForEdit().
246 *
247 * @param Title $title
248 * @param Content $content
249 * @param User $user User to get parser options from
250 * @return stdClass|bool Returns false on cache miss
251 */
252 public static function checkCache( Title $title, Content $content, User $user ) {
253 $cache = ObjectCache::getLocalClusterInstance();
254 $logger = LoggerFactory::getInstance( 'StashEdit' );
255 $stats = RequestContext::getMain()->getStats();
256
257 $key = self::getStashKey( $title, $content, $user );
258 $editInfo = $cache->get( $key );
259 if ( !is_object( $editInfo ) ) {
260 $start = microtime( true );
261 // We ignore user aborts and keep parsing. Block on any prior parsing
262 // so as to use its results and make use of the time spent parsing.
263 // Skip this logic if there no master connection in case this method
264 // is called on an HTTP GET request for some reason.
265 $lb = wfGetLB();
266 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
267 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
268 $editInfo = $cache->get( $key );
269 $dbw->unlock( $key, __METHOD__ );
270 }
271
272 $timeMs = 1000 * max( 0, microtime( true ) - $start );
273 $stats->timing( 'editstash.lock-wait-time', $timeMs );
274 }
275
276 if ( !is_object( $editInfo ) || !$editInfo->output ) {
277 $stats->increment( 'editstash.cache-misses' );
278 $logger->debug( "No cache value for key '$key'." );
279 return false;
280 }
281
282 $time = wfTimestamp( TS_UNIX, $editInfo->output->getTimestamp() );
283 if ( ( time() - $time ) <= 3 ) {
284 $stats->increment( 'editstash.cache-hits' );
285 $logger->debug( "Timestamp-based cache hit for key '$key'." );
286 return $editInfo; // assume nothing changed
287 }
288
289 $dbr = wfGetDB( DB_SLAVE );
290
291 $templates = array(); // conditions to find changes/creations
292 $templateUses = 0; // expected existing templates
293 foreach ( $editInfo->output->getTemplateIds() as $ns => $stuff ) {
294 foreach ( $stuff as $dbkey => $revId ) {
295 $templates[(string)$ns][$dbkey] = (int)$revId;
296 ++$templateUses;
297 }
298 }
299 // Check that no templates used in the output changed...
300 if ( count( $templates ) ) {
301 $res = $dbr->select(
302 'page',
303 array( 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ),
304 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
305 __METHOD__
306 );
307 $changed = false;
308 foreach ( $res as $row ) {
309 $changed = $changed || ( $row->page_latest != $templates[$row->ns][$row->dbk] );
310 }
311
312 if ( $changed || $res->numRows() != $templateUses ) {
313 $stats->increment( 'editstash.cache-misses' );
314 $logger->info( "Stale cache for key '$key'; template changed." );
315 return false;
316 }
317 }
318
319 $files = array(); // conditions to find changes/creations
320 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
321 $files[$name] = (string)$options['sha1'];
322 }
323 // Check that no files used in the output changed...
324 if ( count( $files ) ) {
325 $res = $dbr->select(
326 'image',
327 array( 'name' => 'img_name', 'img_sha1' ),
328 array( 'img_name' => array_keys( $files ) ),
329 __METHOD__
330 );
331 $changed = false;
332 foreach ( $res as $row ) {
333 $changed = $changed || ( $row->img_sha1 != $files[$row->name] );
334 }
335
336 if ( $changed || $res->numRows() != count( $files ) ) {
337 $stats->increment( 'editstash.cache-misses' );
338 $logger->info( "Stale cache for key '$key'; file changed." );
339 return false;
340 }
341 }
342
343 $stats->increment( 'editstash.cache-hits' );
344 $logger->debug( "Cache hit for key '$key'." );
345
346 return $editInfo;
347 }
348
349 /**
350 * Get the temporary prepared edit stash key for a user
351 *
352 * This key can be used for caching prepared edits provided:
353 * - a) The $user was used for PST options
354 * - b) The parser output was made from the PST using cannonical matching options
355 *
356 * @param Title $title
357 * @param Content $content
358 * @param User $user User to get parser options from
359 * @return string
360 */
361 protected static function getStashKey( Title $title, Content $content, User $user ) {
362 $hash = sha1( implode( ':', array(
363 $content->getModel(),
364 $content->getDefaultFormat(),
365 sha1( $content->serialize( $content->getDefaultFormat() ) ),
366 $user->getId() ?: md5( $user->getName() ), // account for user parser options
367 $user->getId() ? $user->getDBTouched() : '-' // handle preference change races
368 ) ) );
369
370 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
371 }
372
373 /**
374 * Build a value to store in memcached based on the PST content and parser output
375 *
376 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
377 *
378 * @param Content $pstContent
379 * @param ParserOutput $parserOutput
380 * @param string $timestamp TS_MW
381 * @return array (stash info array, TTL in seconds) or (null, 0)
382 */
383 protected static function buildStashValue(
384 Content $pstContent, ParserOutput $parserOutput, $timestamp
385 ) {
386 // If an item is renewed, mind the cache TTL determined by config and parser functions
387 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
388 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
389
390 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
391 // Only store what is actually needed
392 $stashInfo = (object)array(
393 'pstContent' => $pstContent,
394 'output' => $parserOutput,
395 'timestamp' => $timestamp
396 );
397 return array( $stashInfo, $ttl );
398 }
399
400 return array( null, 0 );
401 }
402
403 public function getAllowedParams() {
404 return array(
405 'title' => array(
406 ApiBase::PARAM_TYPE => 'string',
407 ApiBase::PARAM_REQUIRED => true
408 ),
409 'section' => array(
410 ApiBase::PARAM_TYPE => 'string',
411 ),
412 'sectiontitle' => array(
413 ApiBase::PARAM_TYPE => 'string'
414 ),
415 'text' => array(
416 ApiBase::PARAM_TYPE => 'text',
417 ApiBase::PARAM_REQUIRED => true
418 ),
419 'contentmodel' => array(
420 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
421 ApiBase::PARAM_REQUIRED => true
422 ),
423 'contentformat' => array(
424 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
425 ApiBase::PARAM_REQUIRED => true
426 ),
427 'baserevid' => array(
428 ApiBase::PARAM_TYPE => 'integer',
429 ApiBase::PARAM_REQUIRED => true
430 )
431 );
432 }
433
434 function needsToken() {
435 return 'csrf';
436 }
437
438 function mustBePosted() {
439 return true;
440 }
441
442 function isWriteMode() {
443 return true;
444 }
445
446 function isInternal() {
447 return true;
448 }
449 }