Go to the documentation of this file.
28 use InvalidArgumentException;
83 $this->lagDetectionMethod = isset(
$params[
'lagDetectionMethod'] )
85 :
'Seconds_Behind_Master';
86 $this->lagDetectionOptions = isset(
$params[
'lagDetectionOptions'] )
87 ?
$params[
'lagDetectionOptions']
89 $this->useGTIDs = !empty(
$params[
'useGTIDs' ] );
90 foreach ( [
'KeyPath',
'CertPath',
'CAPath',
'Ciphers' ]
as $name ) {
96 $this->sqlMode = isset(
$params[
'sqlMode'] ) ?
$params[
'sqlMode'] :
'';
97 $this->utf8Mode = !empty(
$params[
'utf8Mode'] );
117 public function open( $server,
$user, $password, $dbName ) {
118 # Close/unset connection handle
121 $this->mServer = $server;
122 $this->mUser =
$user;
123 $this->mPassword = $password;
124 $this->mDBname = $dbName;
129 }
catch ( Exception $ex ) {
135 # Always log connection errors
136 if ( !$this->mConn ) {
140 $this->connLogger->error(
141 "Error connecting to {db_server}: {error}",
143 'method' => __METHOD__,
147 $this->connLogger->debug(
"DB connection error\n" .
148 "Server: $server, User: $user, Password: " .
149 substr( $password, 0, 3 ) .
"..., error: " . $error .
"\n" );
154 if ( $dbName !=
'' ) {
155 MediaWiki\suppressWarnings();
157 MediaWiki\restoreWarnings();
159 $this->queryLogger->error(
160 "Error selecting database {db_name} on server {db_server}",
162 'method' => __METHOD__,
165 $this->queryLogger->debug(
166 "Error selecting database $dbName on server {$this->mServer}" );
178 $set = [
'group_concat_max_len = 262144' ];
180 if ( is_string( $this->sqlMode ) ) {
181 $set[] =
'sql_mode = ' . $this->
addQuotes( $this->sqlMode );
185 foreach ( $this->mSessionVars
as $var => $val ) {
187 if ( !is_int( $val ) && !is_float( $val ) ) {
197 $this->queryLogger->error(
198 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
200 'method' => __METHOD__,
204 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
208 $this->mOpened =
true;
218 if ( $this->utf8Mode ) {
234 abstract protected function mysqlConnect( $realServer );
252 MediaWiki\suppressWarnings();
254 MediaWiki\restoreWarnings();
277 MediaWiki\suppressWarnings();
279 MediaWiki\restoreWarnings();
286 if ( $errno == 2000 || $errno == 2013 ) {
289 'Error in fetchObject(): ' . htmlspecialchars( $this->
lastError() )
313 MediaWiki\suppressWarnings();
315 MediaWiki\restoreWarnings();
322 if ( $errno == 2000 || $errno == 2013 ) {
325 'Error in fetchRow(): ' . htmlspecialchars( $this->
lastError() )
349 MediaWiki\suppressWarnings();
351 MediaWiki\restoreWarnings();
460 if ( $this->mConn ) {
461 # Even if it's non-zero, it can still be invalid
462 MediaWiki\suppressWarnings();
467 MediaWiki\restoreWarnings();
472 $error .=
' (' . $this->mServer .
')';
484 abstract protected function mysqlError( $conn =
null );
493 public function replace( $table, $uniqueIndexes, $rows,
$fname = __METHOD__ ) {
514 if (
$res ===
false ) {
522 foreach (
$res as $plan ) {
523 $rows *= $plan->rows > 0 ? $plan->rows : 1;
530 $table = $this->
tableName( $table,
'raw' );
531 if ( isset( $this->mSessionTempTables[$table] ) ) {
539 return $this->
query(
"SHOW TABLES LIKE '$encLike'",
$fname )->numRows() > 0;
549 $res = $this->
query(
"SELECT * FROM $table LIMIT 1", __METHOD__,
true );
554 for ( $i = 0; $i < $n; $i++ ) {
556 if ( $field == $meta->name ) {
583 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
584 # SHOW INDEX should work for 3.x and up:
585 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
589 $sql =
'SHOW INDEX FROM ' . $table;
598 foreach (
$res as $row ) {
599 if ( $row->Key_name == $index ) {
622 if ( is_bool(
$s ) ) {
628 return parent::addQuotes(
$s );
640 return '`' . str_replace( [
"\0",
'`' ], [
'',
'``' ],
$s ) .
'`';
648 return strlen(
$name ) &&
$name[0] ==
'`' && substr(
$name, -1, 1 ) ==
'`';
670 $res = $this->
query(
'SHOW SLAVE STATUS', __METHOD__ );
671 $row =
$res ?
$res->fetchObject() :
false;
672 if ( $row && strval( $row->Seconds_Behind_Master ) !==
'' ) {
673 return intval( $row->Seconds_Behind_Master );
691 if ( !$masterInfo ) {
692 $this->queryLogger->error(
693 "Unable to query master of {db_server} for server ID",
695 'method' => __METHOD__
702 $conds = [
'server_id' => intval( $masterInfo[
'serverId'] ) ];
707 if (
$time !==
null ) {
709 $dateTime =
new DateTime(
$time,
new DateTimeZone(
'UTC' ) );
710 $timeUnix = (int)$dateTime->format(
'U' ) + $dateTime->format(
'u' ) / 1e6;
712 return max( $nowUnix - $timeUnix, 0.0 );
715 $this->queryLogger->error(
716 "Unable to find pt-heartbeat row for {db_server}",
718 'method' => __METHOD__
727 $key =
$cache->makeGlobalKey(
734 return $cache->getWithSetCallback(
736 $cache::TTL_INDEFINITE,
739 if ( !
$cache->lock( $key, 0, 10 ) ) {
750 $res = $conn->query(
'SELECT @@server_id AS id', __METHOD__ );
751 $row =
$res ?
$res->fetchObject() :
false;
752 $id = $row ? (int)$row->id : 0;
758 return $id ? [
'serverId' => $id,
'asOf' => time() ] :
false;
777 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
779 $row =
$res ?
$res->fetchObject() :
false;
784 return [ $row ? $row->ts :
null, microtime(
true ) ];
792 return parent::getApproximateLagStatus();
795 $key = $this->srvCache->makeGlobalKey(
'mysql-lag', $this->
getServer() );
796 $approxLag = $this->srvCache->get( $key );
798 $approxLag = parent::getApproximateLagStatus();
799 $this->srvCache->set( $key, $approxLag, 1 );
807 throw new InvalidArgumentException(
"Position not an instance of MySQLMasterPos" );
810 if ( $this->
getLBInfo(
'is static' ) ===
true ) {
812 } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
817 if ( $this->useGTIDs && $pos->gtids ) {
819 $gtidArg = $this->
addQuotes( implode(
',', $pos->gtids ) );
820 $res = $this->
doQuery(
"SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
823 $encFile = $this->
addQuotes( $pos->file );
824 $encPos = intval( $pos->pos );
825 $res = $this->
doQuery(
"SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
831 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
835 $status = ( $row[0] !== null ) ? intval( $row[0] ) :
null;
842 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
843 $this->lastKnownReplicaPos = $replicationPos;
848 $this->lastKnownReplicaPos = $pos;
860 $res = $this->
query(
'SHOW SLAVE STATUS', __METHOD__ );
864 $pos = isset( $row->Exec_master_log_pos )
865 ? $row->Exec_master_log_pos
866 : $row->Exec_Master_Log_Pos;
868 if ( $this->useGTIDs ) {
869 $res = $this->
query(
"SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__ );
871 $gtidSet = $gtidRow ? $gtidRow->Value :
'';
876 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos, $gtidSet );
888 $res = $this->
query(
'SHOW MASTER STATUS', __METHOD__ );
893 if ( $this->useGTIDs ) {
894 $res = $this->
query(
"SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__ );
896 $gtidSet = $gtidRow ? $gtidRow->Value :
'';
901 return new MySQLMasterPos( $row->File, $row->Position, $gtidSet );
908 $res = $this->
query(
"SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__ );
911 return $row ? ( strtolower( $row->Value ) ===
'on' ) :
false;
919 return "FORCE INDEX (" . $this->
indexName( $index ) .
")";
927 return "IGNORE INDEX (" . $this->
indexName( $index ) .
")";
934 return 'LOW_PRIORITY';
945 if ( strpos( $version,
'MariaDB' ) !==
false || strpos( $version,
'-maria-' ) !==
false ) {
946 return '[{{int:version-db-mariadb-url}} MariaDB]';
952 return '[{{int:version-db-mysql-url}} MySQL]';
962 if ( $this->serverVersion ===
null ) {
963 $this->serverVersion = $this->
selectField(
'',
'VERSION()',
'', __METHOD__ );
972 if ( isset(
$options[
'connTimeout'] ) ) {
973 $timeout = (int)
$options[
'connTimeout'];
974 $this->
query(
"SET net_read_timeout=$timeout" );
975 $this->
query(
"SET net_write_timeout=$timeout" );
985 if ( strtoupper( substr( $newLine, 0, 9 ) ) ==
'DELIMITER' ) {
986 preg_match(
'/^DELIMITER\s+(\S+)/', $newLine, $m );
987 $this->delimiter = $m[1];
991 return parent::streamStatementEnd( $sql, $newLine );
1004 $result = $this->
query(
"SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1007 return ( $row->lockstatus == 1 );
1016 public function lock( $lockName, $method, $timeout = 5 ) {
1018 $result = $this->
query(
"SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1021 if ( $row->lockstatus == 1 ) {
1022 parent::lock( $lockName, $method, $timeout );
1026 $this->queryLogger->warning( __METHOD__ .
" failed to acquire lock '$lockName'\n" );
1038 public function unlock( $lockName, $method ) {
1040 $result = $this->
query(
"SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1043 if ( $row->lockstatus == 1 ) {
1044 parent::unlock( $lockName, $method );
1048 $this->queryLogger->warning( __METHOD__ .
" failed to release lock '$lockName'\n" );
1056 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1069 foreach ( $write
as $table ) {
1070 $items[] = $this->
tableName( $table ) .
' WRITE';
1072 foreach ( $read
as $table ) {
1073 $items[] = $this->
tableName( $table ) .
' READ';
1076 $sql =
"LOCK TABLES " . implode(
',', $items );
1077 $this->
query( $sql, $method );
1083 $this->
query(
"UNLOCK TABLES", $method );
1092 if (
$value ===
'default' ) {
1093 if ( $this->mDefaultBigSelects ===
null ) {
1094 # Function hasn't been called before so it must already be set to the default
1099 } elseif ( $this->mDefaultBigSelects ===
null ) {
1100 $this->mDefaultBigSelects =
1101 (bool)$this->
selectField(
false,
'@@sql_big_selects',
'', __METHOD__ );
1103 $encValue =
$value ?
'1' :
'0';
1104 $this->
query(
"SET sql_big_selects=$encValue", __METHOD__ );
1119 $delTable, $joinTable, $delVar, $joinVar, $conds,
$fname = __METHOD__
1125 $delTable = $this->
tableName( $delTable );
1126 $joinTable = $this->
tableName( $joinTable );
1127 $sql =
"DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1129 if ( $conds !=
'*' ) {
1147 if ( !
count( $rows ) ) {
1151 if ( !is_array( reset( $rows ) ) ) {
1156 $columns = array_keys( $rows[0] );
1158 $sql =
"INSERT INTO $table (" . implode(
',', $columns ) .
') VALUES ';
1160 foreach ( $rows
as $row ) {
1161 $rowTuples[] =
'(' . $this->
makeList( $row ) .
')';
1163 $sql .= implode(
',', $rowTuples );
1177 return (
int)
$vars[
'Uptime'];
1213 return $errno == 2013 || $errno == 2006;
1224 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
1226 $tmp = $temporary ?
'TEMPORARY ' :
'';
1229 $query =
"CREATE $tmp TABLE $newName (LIKE $oldName)";
1247 $vars = get_object_vars( $table );
1248 $table = array_pop(
$vars );
1250 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1251 $endArray[] = $table;
1263 public function dropTable( $tableName, $fName = __METHOD__ ) {
1264 if ( !$this->
tableExists( $tableName, $fName ) ) {
1268 return $this->
query(
"DROP TABLE IF EXISTS " . $this->
tableName( $tableName ), $fName );
1278 $res = $this->
query(
"SHOW STATUS LIKE '{$which}'" );
1281 foreach (
$res as $row ) {
1282 $status[$row->Variable_name] = $row->Value;
1302 $res = $this->
query(
'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1304 foreach (
$res as $row ) {
1305 array_push( $allViews, $row->$propertyName );
1308 if ( is_null( $prefix ) || $prefix ===
'' ) {
1312 $filteredViews = [];
1313 foreach ( $allViews
as $viewName ) {
1315 if ( strpos( $viewName, $prefix ) === 0 ) {
1316 array_push( $filteredViews, $viewName );
1320 return $filteredViews;
1357 'ar_usertext_timestamp' =>
'usertext_timestamp',
1358 'un_user_id' =>
'user_id',
1359 'un_user_ip' =>
'user_ip',
1362 if ( isset( $renamed[$index] ) ) {
1363 return $renamed[$index];
processing should stop and the error should be shown to the user * false
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:Array with elements of the form "language:title" in the order that they will be output. & $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
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
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Allows to change the fields on the form that will be generated $name
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
null for the wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
This document describes the state of Postgres support in MediaWiki
see documentation in includes Linker php for Linker::makeImageLink & $time
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
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
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
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
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
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
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 as context as context $options
the array() calling protocol came about after MediaWiki 1.4rc1.