94 if ( isset(
$params[
'servers'] ) ) {
95 $this->serverInfos = [];
96 $this->serverTags = [];
97 $this->numServers = count(
$params[
'servers'] );
100 $this->serverInfos[$index] = $info;
101 if ( is_string(
$tag ) ) {
102 $this->serverTags[$index] =
$tag;
104 $this->serverTags[$index] = isset( $info[
'host'] ) ? $info[
'host'] :
"#$index";
108 } elseif ( isset(
$params[
'server'] ) ) {
109 $this->serverInfos = [
$params[
'server'] ];
110 $this->numServers = count( $this->serverInfos );
112 $this->serverInfos =
false;
113 $this->numServers = 1;
115 if ( isset(
$params[
'purgePeriod'] ) ) {
116 $this->purgePeriod = intval(
$params[
'purgePeriod'] );
118 if ( isset(
$params[
'tableName'] ) ) {
121 if ( isset(
$params[
'shards'] ) ) {
122 $this->shards = intval(
$params[
'shards'] );
124 if ( isset(
$params[
'syncTimeout'] ) ) {
125 $this->syncTimeout =
$params[
'syncTimeout'];
127 $this->slaveOnly = !empty(
$params[
'slaveOnly'] );
137 protected function getDB( $serverIndex ) {
138 if ( !isset( $this->conns[$serverIndex] ) ) {
139 if ( $serverIndex >= $this->numServers ) {
140 throw new MWException( __METHOD__ .
": Invalid server index \"$serverIndex\"" );
143 # Don't keep timing out trying to connect for each call if the DB is down
144 if ( isset( $this->connFailureErrors[$serverIndex] )
145 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
147 throw $this->connFailureErrors[$serverIndex];
150 # If server connection info was given, use that
151 if ( $this->serverInfos ) {
152 $info = $this->serverInfos[$serverIndex];
153 $type = isset( $info[
'type'] ) ? $info[
'type'] :
'mysql';
154 $host = isset( $info[
'host'] ) ? $info[
'host'] :
'[unknown]';
155 $this->logger->debug( __CLASS__ .
": connecting to $host" );
165 if (
wfGetDB( $index )->getType() ==
'mysql' ) {
167 $db = $lb->getConnection( $index );
173 $this->logger->debug( sprintf(
"Connection %s will be used for SqlBagOStuff", $db ) );
174 $this->conns[$serverIndex] = $db;
177 return $this->conns[$serverIndex];
186 if ( $this->shards > 1 ) {
187 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
192 if ( $this->numServers > 1 ) {
195 reset( $sortedServers );
196 $serverIndex =
key( $sortedServers );
209 if ( $this->shards > 1 ) {
210 $decimals = strlen( $this->shards - 1 );
212 sprintf(
"%0{$decimals}d", $index );
225 $values = $this->
getMulti( [ $key ] );
226 if ( array_key_exists( $key, $values ) ) {
227 $casToken = $values[$key];
228 return $values[$key];
237 foreach ( $keys
as $key ) {
239 $keysByTable[$serverIndex][
$tableName][] = $key;
245 foreach ( $keysByTable
as $serverIndex => $serverKeys ) {
247 $db = $this->
getDB( $serverIndex );
250 [
'keyname',
'value',
'exptime' ],
251 [
'keyname' => $tableKeys ],
256 $db->trxLevel() ? [
'LOCK IN SHARE MODE' ] : []
258 if (
$res ===
false ) {
261 foreach (
$res as $row ) {
262 $row->serverIndex = $serverIndex;
264 $dataRows[$row->keyname] = $row;
272 foreach ( $keys
as $key ) {
273 if ( isset( $dataRows[$key] ) ) {
274 $row = $dataRows[$key];
275 $this->
debug(
"get: retrieved data; expiry time is " . $row->exptime );
277 $db = $this->
getDB( $row->serverIndex );
278 if ( $this->
isExpired( $db, $row->exptime ) ) {
279 $this->
debug(
"get: key has expired" );
281 $values[$key] = $this->
unserialize( $db->decodeBlob( $row->value ) );
287 $this->
debug(
'get: no matching rows' );
296 foreach ( $data
as $key =>
$value ) {
298 $keysByTable[$serverIndex][
$tableName][] = $key;
304 $exptime = (int)$expiry;
305 foreach ( $keysByTable
as $serverIndex => $serverKeys ) {
307 $db = $this->
getDB( $serverIndex );
314 if ( $exptime < 0 ) {
318 if ( $exptime == 0 ) {
322 $encExpiry = $db->timestamp( $exptime );
326 foreach ( $tableKeys
as $key ) {
329 'value' => $db->encodeBlob( $this->
serialize( $data[$key] ) ),
330 'exptime' => $encExpiry,
355 if ( (
$flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
362 protected function cas( $casToken, $key,
$value, $exptime = 0 ) {
365 $db = $this->
getDB( $serverIndex );
366 $exptime = intval( $exptime );
368 if ( $exptime < 0 ) {
372 if ( $exptime == 0 ) {
376 $encExpiry = $db->timestamp( $exptime );
384 'value' => $db->encodeBlob( $this->serialize(
$value ) ),
385 'exptime' => $encExpiry
389 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
399 return (
bool)$db->affectedRows();
402 public function delete( $key ) {
405 $db = $this->
getDB( $serverIndex );
408 [
'keyname' => $key ],
418 public function incr( $key, $step = 1 ) {
421 $db = $this->
getDB( $serverIndex );
422 $step = intval( $step );
423 $row = $db->selectRow(
425 [
'value',
'exptime' ],
426 [
'keyname' => $key ],
429 if ( $row ===
false ) {
434 $db->delete(
$tableName, [
'keyname' => $key ], __METHOD__ );
435 if ( $this->
isExpired( $db, $row->exptime ) ) {
441 $oldValue = intval( $this->
unserialize( $db->decodeBlob( $row->value ) ) );
442 $newValue = $oldValue + $step;
446 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
447 'exptime' => $row->exptime
448 ], __METHOD__,
'IGNORE' );
450 if ( $db->affectedRows() == 0 ) {
462 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10,
$flags = 0 ) {
463 $ok = $this->
mergeViaCas( $key, $callback, $exptime, $attempts );
464 if ( (
$flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
485 if ( time() > 0x7fffffff ) {
486 return $db->timestamp( 1 << 62 );
488 return $db->timestamp( 0x7fffffff );
493 if ( !$this->purgePeriod || $this->slaveOnly ) {
498 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
503 if ( $now > ( $this->lastExpireAll + 1 ) ) {
504 $this->lastExpireAll = $now;
522 $db = $this->
getDB( $serverIndex );
524 $totalSeconds =
false;
525 $baseConds = [
'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
530 if ( $maxExpTime !==
false ) {
531 $conds[] =
'exptime > ' . $db->addQuotes( $maxExpTime );
535 [
'keyname',
'exptime' ],
538 [
'LIMIT' => 100,
'ORDER BY' =>
'exptime' ] );
539 if ( $rows ===
false || !$rows->numRows() ) {
543 $row = $rows->current();
544 $minExpTime = $row->exptime;
545 if ( $totalSeconds ===
false ) {
549 foreach ( $rows
as $row ) {
550 $keys[] = $row->keyname;
551 $maxExpTime = $row->exptime;
557 'exptime >= ' . $db->addQuotes( $minExpTime ),
558 'exptime < ' . $db->addQuotes( $dbTimestamp ),
563 if ( $progressCallback ) {
564 if ( intval( $totalSeconds ) === 0 ) {
569 if ( $remainingSeconds > $totalSeconds ) {
570 $totalSeconds = $remainingSeconds;
572 $processedSeconds = $totalSeconds - $remainingSeconds;
573 $percent = ( $i + $processedSeconds / $totalSeconds )
574 / $this->shards * 100;
577 + ( $serverIndex / $this->numServers * 100 );
578 call_user_func( $progressCallback, $percent );
598 $db = $this->
getDB( $serverIndex );
621 if ( function_exists(
'gzdeflate' ) ) {
622 return gzdeflate( $serial );
634 if ( function_exists(
'gzinflate' ) ) {
635 MediaWiki\suppressWarnings();
636 $decomp = gzinflate( $serial );
637 MediaWiki\restoreWarnings();
639 if (
false !== $decomp ) {
659 $this->logger->error(
"DBError: {$exception->getMessage()}" );
660 if ( $exception instanceof DBConnectionError ) {
662 $this->logger->debug( __METHOD__ .
": ignoring connection error" );
665 $this->logger->debug( __METHOD__ .
": ignoring query error" );
679 if ( $exception->db && $exception->db->wasReadOnlyError() ) {
680 if ( $exception->db->trxLevel() ) {
682 $exception->db->rollback( __METHOD__ );
688 $this->logger->error(
"DBError: {$exception->getMessage()}" );
689 if ( $exception instanceof DBConnectionError ) {
691 $this->logger->debug( __METHOD__ .
": ignoring connection error" );
694 $this->logger->debug( __METHOD__ .
": ignoring query error" );
705 unset( $this->conns[$serverIndex] );
707 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
708 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
709 unset( $this->connFailureTimes[$serverIndex] );
710 unset( $this->connFailureErrors[$serverIndex] );
712 $this->logger->debug( __METHOD__ .
": Server #$serverIndex already down" );
717 $this->logger->info( __METHOD__ .
": Server #$serverIndex down until " . ( $now + 60 ) );
718 $this->connFailureTimes[$serverIndex] = $now;
719 $this->connFailureErrors[$serverIndex] = $exception;
727 $db = $this->
getDB( $serverIndex );
728 if ( $db->getType() !==
'mysql' ) {
729 throw new MWException( __METHOD__ .
' is not supported on this DB server' );
734 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
735 ' LIKE ' . $db->tableName(
'objectcache' ),
742 if ( !$this->serverInfos ) {
static consistentHashSort(&$array, $key, $separator="\000")
Sort the given array in a pseudo-random order which depends only on the given key and each element va...
getWithToken($key, &$casToken, $flags=0)
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.
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
array[] $serverInfos
(server index => server config)
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
__construct($params)
Constructor.
handleWriteError(DBError $exception, $serverIndex)
Handle a DBQueryError which occurred during a write operation.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
unserialize($serial)
Unserialize and, if necessary, decompress an object.
cas($casToken, $key, $value, $exptime=0)
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes().You will need both of them.------------------------------------------------------------------------Basic query optimisation------------------------------------------------------------------------MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them.Patches containing unacceptably slow features will not be accepted.Unindexed queries are generally not welcome in MediaWiki
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
mergeViaCas($key, $callback, $exptime=0, $attempts=10)
markServerDown($exception, $serverIndex)
Mark a server down due to a DBConnectionError exception.
interface is intended to be more or less compatible with the PHP memcached client.
handleReadError(DBError $exception, $serverIndex)
Handle a DBError which occurred during a read operation.
Exception class for replica DB wait timeouts.
convertExpiry($exptime)
Convert an optionally relative time to an absolute time.
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
string[] $serverTags
(server index => tag/host name)
getMulti(array $keys, $flags=0)
Helper class that detects high-contention DB queries via profiling calls.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
getTableByKey($key)
Get the server index and table name for a given key.
static factory($dbType, $p=[])
Given a DB type, construct the name of the appropriate child class of DatabaseBase.
createTables()
Create shard tables.
setMulti(array $data, $expiry=0)
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 $tag
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
set($key, $value, $exptime=0, $flags=0)
deleteAll()
Delete content of shard tables in every server.
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 & $ret
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
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
wfGetLBFactory()
Get the load balancer factory object.
array $connFailureTimes
UNIX timestamps.
serialize(&$data)
Serialize an object and, if possible, compress the representation.
Class to store objects in the database.
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
setLastError($err)
Set the "last error" registry.
getTableNameByShard($index)
Get the table name for a given shard index.
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 one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
merge($key, callable $callback, $exptime=0, $attempts=10, $flags=0)
array $connFailureErrors
Exceptions.
getDB($serverIndex)
Get a connection to the specified database.
deleteObjectsExpiringBefore($timestamp, $progressCallback=false)
Delete objects from the database which expire before a certain date.