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