Go to the documentation of this file.
24 use Wikimedia\ScopedCallback;
53 if (
$user->isBot() ) {
62 ->isSupportedFormat(
$params[
'contentformat'] )
65 [
'apierror-badformat-generic',
$params[
'contentformat'],
$params[
'contentmodel'] ],
74 if ( strlen(
$params[
'stashedtexthash'] ) ) {
76 $textHash =
$params[
'stashedtexthash'];
77 $textKey =
$cache->makeKey(
'stashedit',
'text', $textHash );
78 $text =
$cache->get( $textKey );
79 if ( !is_string( $text ) ) {
80 $this->
dieWithError(
'apierror-stashedit-missingtext',
'missingtext' );
82 } elseif (
$params[
'text'] !==
null ) {
84 $text = rtrim( str_replace(
"\r\n",
"\n",
$params[
'text'] ) );
85 $textHash = sha1( $text );
88 'apierror-missingparam-at-least-one-of',
89 Message::listParam( [
'<var>stashedtexthash</var>',
'<var>text</var>' ] ),
98 if (
$page->exists() ) {
104 $currentRev =
$page->getRevision();
105 if ( !$currentRev ) {
106 $this->
dieWithError( [
'apierror-missingrev-pageid',
$page->getId() ],
'missingrev' );
109 $editContent =
$page->replaceSectionAtRev(
115 if ( !$editContent ) {
116 $this->
dieWithError(
'apierror-sectionreplacefailed',
'replacefailed' );
118 if ( $currentRev->getId() == $baseRev->getId() ) {
123 $baseContent = $baseRev->getContent();
124 $currentContent = $currentRev->getContent();
125 if ( !$baseContent || !$currentContent ) {
126 $this->
dieWithError( [
'apierror-missingcontent-pageid',
$page->getId() ],
'missingrev' );
143 ignore_user_abort(
true );
145 if (
$user->pingLimiter(
'stashedit' ) ) {
149 $textKey =
$cache->makeKey(
'stashedit',
'text', $textHash );
150 $cache->set( $textKey, $text, self::MAX_CACHE_TTL );
153 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
154 $stats->increment(
"editstash.cache_stores.$status" );
161 'texthash' => $textHash
176 $logger = LoggerFactory::getInstance(
'StashEdit' );
183 if ( !$dbw->lock( $key, __METHOD__, 1 ) ) {
188 $unlocker =
new ScopedCallback(
function ()
use ( $dbw, $key ) {
189 $dbw->unlock( $key, __METHOD__ );
195 $editInfo =
$cache->get( $key );
196 if ( $editInfo &&
wfTimestamp( TS_UNIX, $editInfo->timestamp ) >= $cutoffTime ) {
197 $alreadyCached =
true;
199 $format =
$content->getDefaultFormat();
201 $alreadyCached =
false;
204 if ( $editInfo && $editInfo->output ) {
209 if ( $alreadyCached ) {
210 $logger->debug(
"Already cached parser output for key '$key' ('$title')." );
215 $editInfo->pstContent,
217 $editInfo->timestamp,
222 $ok =
$cache->set( $key, $stashInfo, $ttl );
224 $logger->debug(
"Cached parser output for key '$key' ('$title')." );
227 $logger->error(
"Failed to cache parser output for key '$key' ('$title')." );
231 $logger->info(
"Uncacheable parser output for key '$key' ('$title') [$code]." );
257 if (
$user->isBot() ) {
262 $logger = LoggerFactory::getInstance(
'StashEdit' );
263 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
266 $editInfo =
$cache->get( $key );
267 if ( !is_object( $editInfo ) ) {
268 $start = microtime(
true );
273 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
274 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
275 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
276 $editInfo =
$cache->get( $key );
277 $dbw->unlock( $key, __METHOD__ );
280 $timeMs = 1000 * max( 0, microtime(
true ) - $start );
281 $stats->timing(
'editstash.lock_wait_time', $timeMs );
284 if ( !is_object( $editInfo ) || !$editInfo->output ) {
285 $stats->increment(
'editstash.cache_misses.no_stash' );
286 $logger->debug(
"Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
290 $age = time() -
wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
291 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
293 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
294 $logger->debug(
"Timestamp-based cache hit for key '$key' (age: $age sec)." );
295 } elseif ( isset( $editInfo->edits ) && $editInfo->edits ===
$user->getEditCount() ) {
297 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
298 $logger->debug(
"Edit count based cache hit for key '$key' (age: $age sec)." );
299 } elseif (
$user->isAnon()
303 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
304 $logger->debug(
"Edit check based cache hit for key '$key' (age: $age sec)." );
311 $stats->increment(
'editstash.cache_misses.proven_stale' );
312 $logger->info(
"Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
313 } elseif ( $editInfo->output->getFlag(
'vary-revision' ) ) {
316 $logger->info(
"Cache for key '$key' ('$title') has vary_revision." );
317 } elseif ( $editInfo->output->getFlag(
'vary-revision-id' ) ) {
319 $logger->info(
"Cache for key '$key' ('$title') has vary_revision_id." );
333 [
'rc_user_text' =>
$user->getName() ],
347 return sha1( implode(
"\n", [
369 md5(
$title->getPrefixedDBkey() ),
373 md5(
$user->getId() .
"\n" .
$user->getName() )
396 return [
null, 0,
'no_ttl' ];
401 'pstContent' => $pstContent,
403 'timestamp' => $timestamp,
404 'edits' =>
$user->getEditCount()
407 return [ $stashInfo, $ttl,
'ok' ];
426 'stashedtexthash' => [
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
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
static getAllContentFormats()
static getLocalClusterInstance()
Get the main cluster-local cache object.
needsToken()
Returns the token type this module requires in order to execute.
const PARAM_REQUIRED
(boolean) Is the parameter required?
isWriteMode()
Indicates whether this module requires write mode.
const PRESUME_FRESH_TTL_SEC
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
static getContentHash(Content $content)
Get hash of the content, factoring in model/format.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
getResult()
Get the result object.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup 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
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
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 account $user
Class representing a MediaWiki article and history.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
static parseAndStash(WikiPage $page, Content $content, User $user, $summary)
static newFromPageId( $pageId, $revId=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given page ID.
getUser()
Get the User object.
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
This abstract class implements many basic API functions, and is the base of all API classes.
namespace and then decline to actually register it file or subcat img or subcat $title
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
static getContentModels()
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup 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
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
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
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
see documentation in includes Linker php for Linker::makeImageLink & $time
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
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
static buildStashValue(Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user)
Build a value to store in memcached based on the PST content and parser output.
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
isInternal()
Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party...
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
Base interface for content objects.
requireAtLeastOneParameter( $params, $required)
Die if none of a certain set of parameters is set and not false.
static lastEditTime(User $user)
Represents a title within MediaWiki.
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 & $code
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
static getStashKey(Title $title, $contentHash, User $user)
Get the temporary prepared edit stash key for a user.
getModuleName()
Get the name of the module being executed by this instance.
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
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
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 MediaWikiServices
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Prepare an edit in shared cache so that it can be reused on edit.
static checkCache(Title $title, Content $content, User $user)
Check that a prepared edit is in cache and still up-to-date.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup 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
mustBePosted()
Indicates whether this module must be called with a POST request.