53 if (
$user->isBot() ) {
54 $this->
dieUsage(
'This interface is not supported for bots',
'botsnotsupported' );
62 ->isSupportedFormat(
$params[
'contentformat'] )
64 $this->
dieUsage(
'Unsupported content model/format',
'badmodelformat' );
69 if ( strlen(
$params[
'stashedtexthash'] ) ) {
71 $textHash =
$params[
'stashedtexthash'];
72 $textKey =
$cache->makeKey(
'stashedit',
'text', $textHash );
73 $text =
$cache->get( $textKey );
74 if ( !is_string( $text ) ) {
75 $this->
dieUsage(
'No stashed text found with the given hash',
'missingtext' );
77 } elseif (
$params[
'text'] !== null ) {
79 $text = rtrim( str_replace(
"\r\n",
"\n",
$params[
'text'] ) );
80 $textHash = sha1( $text );
83 'The text or stashedtexthash parameter must be given',
'missingtextparam' );
90 if (
$page->exists() ) {
94 $this->
dieUsage(
"No revision ID {$params['baserevid']}",
'missingrev' );
96 $currentRev =
$page->getRevision();
98 $this->
dieUsage(
"No current revision of page ID {$page->getId()}",
'missingrev' );
101 $editContent =
$page->replaceSectionAtRev(
107 if ( !$editContent ) {
108 $this->
dieUsage(
'Could not merge updated section.',
'replacefailed' );
110 if ( $currentRev->getId() == $baseRev->getId() ) {
115 $baseContent = $baseRev->getContent();
116 $currentContent = $currentRev->getContent();
117 if ( !$baseContent || !$currentContent ) {
118 $this->
dieUsage(
"Missing content for page ID {$page->getId()}",
'missingrev' );
135 ignore_user_abort(
true );
137 if (
$user->pingLimiter(
'stashedit' ) ) {
141 $textKey =
$cache->makeKey(
'stashedit',
'text', $textHash );
142 $cache->set( $textKey, $text, self::MAX_CACHE_TTL );
145 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
146 $stats->increment(
"editstash.cache_stores.$status" );
153 'texthash' => $textHash
168 $logger = LoggerFactory::getInstance(
'StashEdit' );
171 $key = self::getStashKey(
$title, self::getContentHash( $content ), $user );
175 if ( !$dbw->lock( $key, __METHOD__, 1 ) ) {
177 return self::ERROR_BUSY;
180 $unlocker =
new ScopedCallback(
function ()
use ( $dbw, $key ) {
181 $dbw->unlock( $key, __METHOD__ );
184 $cutoffTime = time() - self::PRESUME_FRESH_TTL_SEC;
187 $editInfo =
$cache->get( $key );
189 $alreadyCached =
true;
193 $alreadyCached =
false;
196 if ( $editInfo && $editInfo->output ) {
199 [ $page, $content, $editInfo->output,
$summary, $user ] );
201 if ( $alreadyCached ) {
202 $logger->debug(
"Already cached parser output for key '$key' ('$title')." );
203 return self::ERROR_NONE;
206 list( $stashInfo, $ttl,
$code ) = self::buildStashValue(
207 $editInfo->pstContent,
209 $editInfo->timestamp,
214 $ok =
$cache->set( $key, $stashInfo, $ttl );
216 $logger->debug(
"Cached parser output for key '$key' ('$title')." );
217 return self::ERROR_NONE;
219 $logger->error(
"Failed to cache parser output for key '$key' ('$title')." );
220 return self::ERROR_CACHE;
223 $logger->info(
"Uncacheable parser output for key '$key' ('$title') [$code]." );
224 return self::ERROR_UNCACHEABLE;
228 return self::ERROR_PARSE;
249 if ( $user->
isBot() ) {
254 $logger = LoggerFactory::getInstance(
'StashEdit' );
255 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
257 $key = self::getStashKey( $title, self::getContentHash( $content ), $user );
258 $editInfo =
$cache->get( $key );
259 if ( !is_object( $editInfo ) ) {
260 $start = microtime(
true );
265 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
266 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
267 if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
268 $editInfo =
$cache->get( $key );
269 $dbw->unlock( $key, __METHOD__ );
272 $timeMs = 1000 * max( 0, microtime(
true ) - $start );
273 $stats->timing(
'editstash.lock_wait_time', $timeMs );
276 if ( !is_object( $editInfo ) || !$editInfo->output ) {
277 $stats->increment(
'editstash.cache_misses.no_stash' );
278 $logger->debug(
"Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
283 if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
285 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
286 $logger->debug(
"Timestamp-based cache hit for key '$key' (age: $age sec)." );
287 } elseif ( isset( $editInfo->edits ) && $editInfo->edits === $user->
getEditCount() ) {
289 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
290 $logger->debug(
"Edit count based cache hit for key '$key' (age: $age sec)." );
291 } elseif ( $user->
isAnon()
292 && self::lastEditTime( $user ) < $editInfo->output->getCacheTime()
295 $stats->increment(
'editstash.cache_hits.presumed_fresh' );
296 $logger->debug(
"Edit check based cache hit for key '$key' (age: $age sec)." );
303 $stats->increment(
'editstash.cache_misses.proven_stale' );
304 $logger->info(
"Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
305 } elseif ( $editInfo->output->getFlag(
'vary-revision' ) ) {
308 $logger->info(
"Cache for key '$key' ('$title') has vary_revision." );
309 } elseif ( $editInfo->output->getFlag(
'vary-revision-id' ) ) {
311 $logger->info(
"Cache for key '$key' ('$title') has vary_revision_id." );
325 [
'rc_user_text' => $user->
getName() ],
339 return sha1( implode(
"\n", [
386 $ttl = min( $parserOutput->
getCacheExpiry() - $since, self::MAX_CACHE_TTL );
388 return [ null, 0,
'no_ttl' ];
393 'pstContent' => $pstContent,
394 'output' => $parserOutput,
399 return [ $stashInfo, $ttl,
'ok' ];
418 'stashedtexthash' => [
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
static getStashKey(Title $title, $contentHash, User $user)
Get the temporary prepared edit stash key for a user.
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
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
getResult()
Get the result object.
serialize($format=null)
Convenience method for serializing this Content object.
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.
static parseAndStash(WikiPage $page, Content $content, User $user, $summary)
static getAllContentFormats()
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getForModelID($modelId)
Returns the ContentHandler singleton for the given model ID.
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
static getContentModels()
const PARAM_REQUIRED
(boolean) Is the parameter required?
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
static getLocalClusterInstance()
Get the main cluster-local cache 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 MediaWikiServices
static newFromPageId($pageId, $revId=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given page 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
getName()
Get the user name, or the IP of an anonymous user.
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.
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
getTitleOrPageId($params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
getCacheExpiry()
Returns the number of seconds after which this object should expire.
isAnon()
Get whether the user is anonymous.
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
Base interface for content objects.
getTitle()
Get the title object of the article.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
namespace and then decline to actually register it file or subcat img or subcat $title
getModuleName()
Get the name of the module being executed by this instance.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
static makeContent($text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
static lastEditTime(User $user)
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
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
Class representing a MediaWiki article and history.
prepareContentForEdit(Content $content, $revision=null, User $user=null, $serialFormat=null, $useCache=true)
Prepare content which is about to be saved.
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
getId()
Get the user's ID.
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
getEditCount()
Get the user's edit count.
static buildStashValue(Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user)
Build a value to store in memcached based on the PST content and parser output.
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...
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
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
This abstract class implements many basic API functions, and is the base of all API classes...
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
getModel()
Returns the ID of the content model used by this Content object.
wfTimestampOrNull($outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
getUser()
Get the User object.
see documentation in includes Linker php for Linker::makeImageLink & $time
getDefaultFormat()
Convenience method that returns the default serialization format for the content model that this Cont...
const PRESUME_FRESH_TTL_SEC
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
getPrefixedDBkey()
Get the prefixed database key form.
static getContentHash(Content $content)
Get hash of the content, factoring in model/format.