MediaWiki REL1_27
ApiStashEdit.php
Go to the documentation of this file.
1<?php
23
37class 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
44
45 public function execute() {
46 $user = $this->getUser();
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
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(), [ '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
116 // De-duplicate requests on the same key
117 if ( $user->pingLimiter( 'stashedit' ) ) {
118 $status = 'ratelimited';
119 } elseif ( $dbw->lock( $key, __METHOD__, 1 ) ) {
121 $dbw->unlock( $key, __METHOD__ );
122 } else {
123 $status = 'busy';
124 }
125
126 $this->getResult()->addValue( null, $this->getModuleName(), [ 'status' => $status ] );
127 }
128
136 public static function parseAndStash( WikiPage $page, Content $content, User $user ) {
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 // Let extensions add ParserOutput metadata or warm other caches
147 Hooks::run( 'ParserOutputStashForEdit', [ $page, $content, $editInfo->output ] );
148
149 list( $stashInfo, $ttl ) = self::buildStashValue(
150 $editInfo->pstContent, $editInfo->output, $editInfo->timestamp
151 );
152
153 if ( $stashInfo ) {
154 $ok = $cache->set( $key, $stashInfo, $ttl );
155 if ( $ok ) {
156
157 $logger->debug( "Cached parser output for key '$key'." );
158 return self::ERROR_NONE;
159 } else {
160 $logger->error( "Failed to cache parser output for key '$key'." );
161 return self::ERROR_CACHE;
162 }
163 } else {
164 $logger->info( "Uncacheable parser output for key '$key'." );
166 }
167 }
168
169 return self::ERROR_PARSE;
170 }
171
191 public static function stashEditFromPreview(
192 Page $page, Content $content, Content $pstContent, ParserOutput $pOut,
193 ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp
194 ) {
196 $logger = LoggerFactory::getInstance( 'StashEdit' );
197
198 // getIsPreview() controls parser function behavior that references things
199 // like user/revision that don't exists yet. The user/text should already
200 // be set correctly by callers, just double check the preview flag.
201 if ( !$pOpts->getIsPreview() ) {
202 return false; // sanity
203 } elseif ( $pOpts->getIsSectionPreview() ) {
204 return false; // short-circuit (need the full content)
205 }
206
207 // PST parser options are for the user (handles signatures, etc...)
208 $user = $pstOpts->getUser();
209 // Get a key based on the source text, format, and user preferences
210 $key = self::getStashKey( $page->getTitle(), $content, $user );
211
212 // Parser output options must match cannonical options.
213 // Treat some options as matching that are different but don't matter.
214 $canonicalPOpts = $page->makeParserOptions( 'canonical' );
215 $canonicalPOpts->setIsPreview( true ); // force match
216 $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
217 if ( !$pOpts->matches( $canonicalPOpts ) ) {
218 $logger->info( "Uncacheable preview output for key '$key' (options)." );
219 return false;
220 }
221
222 // Build a value to cache with a proper TTL
223 list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp );
224 if ( !$stashInfo ) {
225 $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
226 return false;
227 }
228
229 $ok = $cache->set( $key, $stashInfo, $ttl );
230 if ( !$ok ) {
231 $logger->error( "Failed to cache preview parser output for key '$key'." );
232 } else {
233 $logger->debug( "Cached preview output for key '$key'." );
234 }
235
236 return $ok;
237 }
238
256 public static function checkCache( Title $title, Content $content, User $user ) {
258 $logger = LoggerFactory::getInstance( 'StashEdit' );
259 $stats = RequestContext::getMain()->getStats();
260
262 $editInfo = $cache->get( $key );
263 if ( !is_object( $editInfo ) ) {
264 $start = microtime( true );
265 // We ignore user aborts and keep parsing. Block on any prior parsing
266 // so as to use its results and make use of the time spent parsing.
267 // Skip this logic if there no master connection in case this method
268 // is called on an HTTP GET request for some reason.
269 $lb = wfGetLB();
270 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
271 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
272 $editInfo = $cache->get( $key );
273 $dbw->unlock( $key, __METHOD__ );
274 }
275
276 $timeMs = 1000 * max( 0, microtime( true ) - $start );
277 $stats->timing( 'editstash.lock_wait_time', $timeMs );
278 }
279
280 if ( !is_object( $editInfo ) || !$editInfo->output ) {
281 $stats->increment( 'editstash.cache_misses.no_stash' );
282 $logger->debug( "No cache value for key '$key'." );
283 return false;
284 }
285
286 $age = time() - wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
287 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
288 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
289 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
290 return $editInfo; // assume nothing changed
291 }
292
293 $dbr = wfGetDB( DB_SLAVE );
294
295 $templates = []; // conditions to find changes/creations
296 $templateUses = 0; // expected existing templates
297 foreach ( $editInfo->output->getTemplateIds() as $ns => $stuff ) {
298 foreach ( $stuff as $dbkey => $revId ) {
299 $templates[(string)$ns][$dbkey] = (int)$revId;
300 ++$templateUses;
301 }
302 }
303 // Check that no templates used in the output changed...
304 if ( count( $templates ) ) {
305 $res = $dbr->select(
306 'page',
307 [ 'ns' => 'page_namespace', 'dbk' => 'page_title', 'page_latest' ],
308 $dbr->makeWhereFrom2d( $templates, 'page_namespace', 'page_title' ),
309 __METHOD__
310 );
311 $changed = false;
312 foreach ( $res as $row ) {
313 $changed = $changed || ( $row->page_latest != $templates[$row->ns][$row->dbk] );
314 }
315
316 if ( $changed || $res->numRows() != $templateUses ) {
317 $stats->increment( 'editstash.cache_misses.proven_stale' );
318 $logger->info( "Stale cache for key '$key'; template changed. (age: $age sec)" );
319 return false;
320 }
321 }
322
323 $files = []; // conditions to find changes/creations
324 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
325 $files[$name] = (string)$options['sha1'];
326 }
327 // Check that no files used in the output changed...
328 if ( count( $files ) ) {
329 $res = $dbr->select(
330 'image',
331 [ 'name' => 'img_name', 'img_sha1' ],
332 [ 'img_name' => array_keys( $files ) ],
333 __METHOD__
334 );
335 $changed = false;
336 foreach ( $res as $row ) {
337 $changed = $changed || ( $row->img_sha1 != $files[$row->name] );
338 }
339
340 if ( $changed || $res->numRows() != count( $files ) ) {
341 $stats->increment( 'editstash.cache_misses.proven_stale' );
342 $logger->info( "Stale cache for key '$key'; file changed. (age: $age sec)" );
343 return false;
344 }
345 }
346
347 $stats->increment( 'editstash.cache_hits.proven_fresh' );
348 $logger->debug( "Verified cache hit for key '$key' (age: $age sec)." );
349
350 return $editInfo;
351 }
352
365 protected static function getStashKey( Title $title, Content $content, User $user ) {
366 $hash = sha1( implode( ':', [
367 $content->getModel(),
368 $content->getDefaultFormat(),
369 sha1( $content->serialize( $content->getDefaultFormat() ) ),
370 $user->getId() ?: md5( $user->getName() ), // account for user parser options
371 $user->getId() ? $user->getDBTouched() : '-' // handle preference change races
372 ] ) );
373
374 return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
375 }
376
387 protected static function buildStashValue(
389 ) {
390 // If an item is renewed, mind the cache TTL determined by config and parser functions
391 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
392 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
393
394 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
395 // Only store what is actually needed
396 $stashInfo = (object)[
397 'pstContent' => $pstContent,
398 'output' => $parserOutput,
399 'timestamp' => $timestamp
400 ];
401 return [ $stashInfo, $ttl ];
402 }
403
404 return [ null, 0 ];
405 }
406
407 public function getAllowedParams() {
408 return [
409 'title' => [
410 ApiBase::PARAM_TYPE => 'string',
412 ],
413 'section' => [
414 ApiBase::PARAM_TYPE => 'string',
415 ],
416 'sectiontitle' => [
417 ApiBase::PARAM_TYPE => 'string'
418 ],
419 'text' => [
420 ApiBase::PARAM_TYPE => 'text',
422 ],
423 'contentmodel' => [
426 ],
427 'contentformat' => [
430 ],
431 'baserevid' => [
432 ApiBase::PARAM_TYPE => 'integer',
434 ]
435 ];
436 }
437
438 public function needsToken() {
439 return 'csrf';
440 }
441
442 public function mustBePosted() {
443 return true;
444 }
445
446 public function isWriteMode() {
447 return true;
448 }
449
450 public function isInternal() {
451 return true;
452 }
453}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfGetLB( $wiki=false)
Get a load balancer object.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfMemcKey()
Make a cache key for the local wiki.
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:39
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition ApiBase.php:112
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:88
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:685
getResult()
Get the result object.
Definition ApiBase.php:584
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:464
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition ApiBase.php:840
dieUsage( $description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition ApiBase.php:1526
Prepare an edit in shared cache so that it can be reused on edit.
const PRESUME_FRESH_TTL_SEC
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
const ERROR_UNCACHEABLE
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
isInternal()
Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party...
static parseAndStash(WikiPage $page, Content $content, User $user)
needsToken()
Returns the token type this module requires in order to execute.
static getStashKey(Title $title, Content $content, User $user)
Get the temporary prepared edit stash key for a user.
isWriteMode()
Indicates whether this module requires write mode.
static checkCache(Title $title, Content $content, User $user)
Check that a prepared edit is in cache and still up-to-date.
static buildStashValue(Content $pstContent, ParserOutput $parserOutput, $timestamp)
Build a value to store in memcached based on the PST content and parser output.
static stashEditFromPreview(Page $page, Content $content, Content $pstContent, ParserOutput $pOut, ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp)
Attempt to cache PST content and corresponding parser output in passing.
mustBePosted()
Indicates whether this module must be called with a POST request.
static getAllContentFormats()
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
static getContentModels()
getUser()
Get the User object.
PSR-3 logger instance factory.
static getLocalClusterInstance()
Get the main cluster-local cache object.
Set options of the Parser.
matches(ParserOptions $other)
Check if these options match that of another options set.
static getMain()
Static methods.
static newFromPageId( $pageId, $revId=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given page ID.
Definition Revision.php:148
Represents a title within MediaWiki.
Definition Title.php:34
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
Class representing a MediaWiki article and history.
Definition WikiPage.php:29
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition WikiPage.php:99
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition globals.txt:64
const DB_MASTER
Definition Defines.php:48
const DB_SLAVE
Definition Defines.php:47
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context $revId
Definition hooks.txt:1041
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition hooks.txt:1007
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:249
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context $parserOutput
Definition hooks.txt:1036
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition hooks.txt:2379
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition hooks.txt:183
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition hooks.txt:1042
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition hooks.txt:1040
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:944
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:1811
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:314
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition hooks.txt:885
$files
if( $limit) $timestamp
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Base interface for content objects.
Definition Content.php:34
Interface for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
Definition Page.php:24
$cache
Definition mcc.php:33
$params