86 public function open( $server,
$user, $password, $dbName ) {
87 # Test for driver support, to avoid suppressed fatal error
88 if ( !function_exists(
'sqlsrv_connect' ) ) {
91 "Microsoft SQL Server Native (sqlsrv) functions missing.
92 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
98 # e.g. the class is being loaded
99 if ( !strlen(
$user ) ) {
104 $this->mServer = $server;
106 $this->mUser =
$user;
107 $this->mPassword = $password;
108 $this->mDBname = $dbName;
110 $connectionInfo = [];
113 $connectionInfo[
'Database'] = $dbName;
118 if ( !$wgDBWindowsAuthentication ) {
119 $connectionInfo[
'UID'] =
$user;
120 $connectionInfo[
'PWD'] = $password;
123 MediaWiki\suppressWarnings();
124 $this->mConn = sqlsrv_connect( $server, $connectionInfo );
125 MediaWiki\restoreWarnings();
127 if ( $this->mConn ===
false ) {
131 $this->mOpened =
true;
142 return sqlsrv_close( $this->mConn );
154 } elseif (
$result ===
true ) {
158 return new MssqlResultWrapper( $this,
$result );
168 if ( $this->
debug() ) {
178 if ( preg_match(
'/\bLIMIT\s*/i', $sql ) ) {
184 if ( preg_match(
'#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql,
$matches ) ) {
186 $sql = str_replace(
$matches[0],
"DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
195 if ( $this->mScrollableCursor ) {
196 $scrollArr = [
'Scrollable' => SQLSRV_CURSOR_STATIC ];
201 if ( $this->mPrepareStatements ) {
203 $stmt = sqlsrv_prepare( $this->mConn, $sql, [], $scrollArr );
206 $stmt = sqlsrv_query( $this->mConn, $sql, [], $scrollArr );
213 if ( $this->mIgnoreDupKeyErrors ) {
216 $ignoreErrors[] =
'2601';
217 $ignoreErrors[] =
'2627';
218 $ignoreErrors[] =
'3621';
222 $errors = sqlsrv_errors();
225 foreach ( $errors
as $err ) {
226 if ( !in_array( $err[
'code'], $ignoreErrors ) ) {
237 $this->mAffectedRows = sqlsrv_rows_affected( $stmt );
247 sqlsrv_free_stmt(
$res );
256 return $res->fetchObject();
264 return $res->fetchRow();
278 if (
$ret ===
false ) {
281 $ret = (int)sqlsrv_has_rows(
$res );
296 return sqlsrv_num_fields(
$res );
309 return sqlsrv_field_metadata(
$res )[$n][
'Name'];
326 return $res->seek( $row );
334 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL );
335 if ( $retErrors != null ) {
336 foreach ( $retErrors
as $arrError ) {
340 $strRet =
"No errors found";
351 return '[SQLSTATE ' . $err[
'SQLSTATE'] .
'][Error Code ' . $err[
'code'] .
']' . $err[
'message'];
358 $err = sqlsrv_errors( SQLSRV_ERR_ALL );
359 if ( $err !== null && isset( $err[0] ) ) {
360 return $err[0][
'code'];
395 if ( isset(
$options[
'EXPLAIN'] ) ) {
397 $this->mScrollableCursor =
false;
398 $this->mPrepareStatements =
false;
399 $this->
query(
"SET SHOWPLAN_ALL ON" );
401 $this->
query(
"SET SHOWPLAN_ALL OFF" );
403 if ( isset(
$options[
'FOR COUNT'] ) ) {
405 $this->
query(
"SET SHOWPLAN_ALL OFF" );
409 'COUNT(*) AS EstimateRows',
418 $this->mScrollableCursor =
true;
419 $this->mPrepareStatements =
true;
423 $this->mScrollableCursor =
true;
424 $this->mPrepareStatements =
true;
446 if ( isset(
$options[
'EXPLAIN'] ) ) {
453 if ( strpos( $sql,
'MAX(' ) !==
false || strpos( $sql,
'MIN(' ) !==
false ) {
455 if ( is_array( $table ) ) {
456 foreach ( $table
as $t ) {
463 foreach ( $bitColumns
as $col => $info ) {
465 "MAX({$col})" =>
"MAX(CAST({$col} AS tinyint))",
466 "MIN({$col})" =>
"MIN(CAST({$col} AS tinyint))",
468 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
475 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
478 $this->mScrollableCursor =
false;
480 parent::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
$fname );
481 }
catch ( Exception
$e ) {
482 $this->mScrollableCursor =
true;
485 $this->mScrollableCursor =
true;
488 public function delete( $table, $conds,
$fname = __METHOD__ ) {
489 $this->mScrollableCursor =
false;
491 parent::delete( $table, $conds,
$fname );
492 }
catch ( Exception
$e ) {
493 $this->mScrollableCursor =
true;
496 $this->mScrollableCursor =
true;
524 if ( isset( $row[
'EstimateRows'] ) ) {
525 $rows = (int)$row[
'EstimateRows'];
541 # This does not return the same info as MYSQL would, but that's OK
542 # because MediaWiki never uses the returned value except to check for
543 # the existance of indexes.
544 $sql =
"sp_helpindex '" . $this->
tableName( $table ) .
"'";
552 foreach (
$res as $row ) {
553 if ( $row->index_name == $index ) {
554 $row->Non_unique = !stristr( $row->index_description,
"unique" );
555 $cols = explode(
", ", $row->index_keys );
556 foreach ( $cols
as $col ) {
557 $row->Column_name = trim( $col );
560 } elseif ( $index ==
'PRIMARY' && stristr( $row->index_description,
'PRIMARY' ) ) {
561 $row->Non_unique = 0;
562 $cols = explode(
", ", $row->index_keys );
563 foreach ( $cols
as $col ) {
564 $row->Column_name = trim( $col );
589 # No rows to insert, easy just return now
590 if ( !count( $arrToInsert ) ) {
600 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) {
601 $arrToInsert = [ 0 => $arrToInsert ];
607 $tableRawArr = explode(
'.', preg_replace(
'#\[([^\]]*)\]#',
'$1', $table ) );
608 $tableRaw = array_pop( $tableRawArr );
610 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
611 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
613 if (
$res && sqlsrv_has_rows(
$res ) ) {
615 $identityArr = sqlsrv_fetch_array(
$res, SQLSRV_FETCH_ASSOC );
616 $identity = array_pop( $identityArr );
618 sqlsrv_free_stmt(
$res );
625 if ( in_array(
'IGNORE',
$options ) ) {
627 $this->mIgnoreDupKeyErrors =
true;
630 foreach ( $arrToInsert
as $a ) {
635 $identityClause =
'';
640 foreach ( $a
as $k => $v ) {
641 if ( $k == $identity ) {
642 if ( !is_null( $v ) ) {
645 $sqlPre =
"SET IDENTITY_INSERT $table ON;";
646 $sqlPost =
";SET IDENTITY_INSERT $table OFF;";
656 $identityClause =
"OUTPUT INSERTED.$identity ";
659 $keys = array_keys( $a );
662 $sql = $sqlPre .
'INSERT ' . implode(
' ',
$options ) .
663 " INTO $table (" . implode(
',',
$keys ) .
") $identityClause VALUES (";
667 if ( isset( $binaryColumns[$key] ) ) {
675 if ( is_null(
$value ) ) {
677 } elseif ( is_array(
$value ) || is_object(
$value ) ) {
687 $sql .=
')' . $sqlPost;
690 $this->mScrollableCursor =
false;
693 }
catch ( Exception
$e ) {
694 $this->mScrollableCursor =
true;
695 $this->mIgnoreDupKeyErrors =
false;
698 $this->mScrollableCursor =
true;
700 if ( !is_null( $identity ) ) {
702 $row =
$ret->fetchObject();
703 if ( is_object( $row ) ) {
704 $this->mInsertId = $row->$identity;
708 if ( $this->mAffectedRows == -1 ) {
709 $this->mAffectedRows = 1;
714 $this->mIgnoreDupKeyErrors =
false;
734 $insertOptions = [], $selectOptions = []
736 $this->mScrollableCursor =
false;
738 $ret = parent::insertSelect(
747 }
catch ( Exception
$e ) {
748 $this->mScrollableCursor =
true;
751 $this->mScrollableCursor =
true;
787 $sql =
"UPDATE $opts $table SET " . $this->
makeList( $values,
LIST_SET, $binaryColumns );
789 if ( $conds !== [] && $conds !==
'*' ) {
793 $this->mScrollableCursor =
false;
796 }
catch ( Exception
$e ) {
797 $this->mScrollableCursor =
true;
800 $this->mScrollableCursor =
true;
821 if ( !is_array( $a ) ) {
823 'DatabaseBase::makeList called with incorrect parameters' );
830 foreach ( array_keys( $a )
as $field ) {
831 if ( !isset( $binaryColumns[$field] ) ) {
835 if ( is_array( $a[$field] ) ) {
836 foreach ( $a[$field]
as &$v ) {
841 $a[$field] =
new MssqlBlob( $a[$field] );
846 return parent::makeList( $a, $mode );
856 $sql =
"SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
857 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
861 if ( strtolower( $row[
'DATA_TYPE'] ) !=
'text' ) {
862 $size = $row[
'CHARACTER_MAXIMUM_LENGTH'];
879 if ( $offset ===
false || $offset == 0 ) {
880 if ( strpos( $sql,
"SELECT" ) ===
false ) {
881 return "TOP {$limit} " . $sql;
883 return preg_replace(
'/\bSELECT(\s+DISTINCT)?\b/Dsi',
884 'SELECT$1 TOP ' .
$limit, $sql, 1 );
888 $select = $orderby = [];
889 $s1 = preg_match(
'#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
890 $s2 = preg_match(
'#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
891 $overOrder = $postOrder =
'';
892 $first = $offset + 1;
895 $sub2 =
'sub_' . ( $this->mSubqueryId + 1 );
896 $this->mSubqueryId += 2;
899 throw new DBUnexpectedError( $this,
"Attempting to LIMIT a non-SELECT query\n" );
903 $overOrder =
'ORDER BY (SELECT 1)';
905 if ( !isset( $orderby[2] ) || !$orderby[2] ) {
907 $sql = str_replace( $orderby[1],
'', $sql );
909 $overOrder = $orderby[1];
910 $postOrder =
' ' . $overOrder;
912 $sql =
"SELECT {$select[1]}
914 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
915 FROM ({$sql}) {$sub1}
917 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
935 $pattern =
'/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
936 if ( preg_match( $pattern, $sql,
$matches ) ) {
941 $sql = str_replace(
$matches[0],
'', $sql );
943 return $this->
limitResult( $sql, $row_count, $offset );
953 return "[{{int:version-db-mssql-url}} MS SQL Server]";
960 $server_info = sqlsrv_server_info( $this->mConn );
962 if ( isset( $server_info[
'SQLServerVersion'] ) ) {
963 $version = $server_info[
'SQLServerVersion'];
975 list( $db, $schema, $table ) = $this->
tableName( $table,
'split' );
977 if ( $db !==
false ) {
979 wfDebug(
"Attempting to call tableExists on a remote table" );
983 if ( $schema ===
false ) {
988 $res = $this->
query(
"SELECT 1 FROM INFORMATION_SCHEMA.TABLES
989 WHERE TABLE_TYPE = 'BASE TABLE'
990 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
992 if (
$res->numRows() ) {
1007 list( $db, $schema, $table ) = $this->
tableName( $table,
'split' );
1009 if ( $db !==
false ) {
1011 wfDebug(
"Attempting to call fieldExists on a remote table" );
1015 $res = $this->
query(
"SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1016 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1018 if (
$res->numRows() ) {
1026 list( $db, $schema, $table ) = $this->
tableName( $table,
'split' );
1028 if ( $db !==
false ) {
1030 wfDebug(
"Attempting to call fieldInfo on a remote table" );
1034 $res = $this->
query(
"SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1035 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1037 $meta =
$res->fetchRow();
1050 sqlsrv_begin_transaction( $this->mConn );
1051 $this->mTrxLevel = 1;
1059 sqlsrv_commit( $this->mConn );
1060 $this->mTrxLevel = 0;
1069 sqlsrv_rollback( $this->mConn );
1070 $this->mTrxLevel = 0;
1082 if ( strlen( $identifier ) == 0 ) {
1083 throw new MWException(
"An identifier must not be empty" );
1085 if ( strlen( $identifier ) > 128 ) {
1086 throw new MWException(
"The identifier '$identifier' is too long (max. 128)" );
1088 if ( ( strpos( $identifier,
'[' ) !==
false )
1089 || ( strpos( $identifier,
']' ) !==
false )
1093 throw new MWException(
"Square brackets are not allowed in '$identifier'" );
1096 return "[$identifier]";
1106 return str_replace(
"'",
"''",
$s );
1116 } elseif (
$s instanceof
Blob ) {
1119 $blob =
new MssqlBlob(
$s->fetch() );
1120 return $blob->fetch();
1122 if ( is_bool(
$s ) ) {
1125 return parent::addQuotes(
$s );
1135 return '[' .
$s .
']';
1143 return strlen(
$name ) &&
$name[0] ==
'[' && substr(
$name, -1, 1 ) ==
']';
1153 return addcslashes(
$s,
'\%_[]^' );
1172 return parent::buildLike(
$params ) .
" ESCAPE '\' ";
1181 $this->mDBname = $db;
1182 $this->
query(
"USE $db" );
1184 }
catch ( Exception
$e ) {
1200 if ( is_numeric( $key ) ) {
1201 $noKeyOptions[$option] =
true;
1209 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1210 $startOpts .=
'DISTINCT';
1213 if ( isset( $noKeyOptions[
'FOR XML'] ) ) {
1215 $tailOpts .=
" FOR XML PATH('')";
1219 return [ $startOpts,
'', $tailOpts,
'' ];
1235 return implode(
' + ', $stringList );
1259 $this->mSubqueryId++;
1261 $delimLen = strlen( $delim );
1262 $fld =
"{$field} + {$this->addQuotes( $delim )}";
1263 $sql =
"(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1264 . $this->
selectSQLText( $table, $fld, $conds, null, [
'FOR XML' ], $join_conds )
1265 .
") {$gcsq} ({$field}))";
1274 return "SearchMssql";
1284 $tableRawArr = explode(
'.', preg_replace(
'#\[([^\]]*)\]#',
'$1', $table ) );
1285 $tableRaw = array_pop( $tableRawArr );
1287 if ( $this->mBinaryColumnCache === null ) {
1291 return isset( $this->mBinaryColumnCache[$tableRaw] )
1292 ? $this->mBinaryColumnCache[$tableRaw]
1301 $tableRawArr = explode(
'.', preg_replace(
'#\[([^\]]*)\]#',
'$1', $table ) );
1302 $tableRaw = array_pop( $tableRawArr );
1304 if ( $this->mBitColumnCache === null ) {
1308 return isset( $this->mBitColumnCache[$tableRaw] )
1309 ? $this->mBitColumnCache[$tableRaw]
1314 $res = $this->
select(
'INFORMATION_SCHEMA.COLUMNS',
'*',
1316 'TABLE_CATALOG' => $this->mDBname,
1317 'TABLE_SCHEMA' => $this->mSchema,
1318 'DATA_TYPE' => [
'varbinary',
'binary',
'image',
'bit' ]
1321 $this->mBinaryColumnCache = [];
1322 $this->mBitColumnCache = [];
1323 foreach (
$res as $row ) {
1324 if ( $row->DATA_TYPE ==
'bit' ) {
1325 $this->mBitColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1327 $this->mBinaryColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1338 # Replace reserved words with better ones
1355 if ( $format ==
'split' ) {
1358 $table = explode(
'.', $table );
1359 while ( count( $table ) < 3 ) {
1360 array_unshift( $table,
false );
1373 public function dropTable( $tableName, $fName = __METHOD__ ) {
1374 if ( !$this->
tableExists( $tableName, $fName ) ) {
1379 $sql =
"DROP TABLE " . $this->
tableName( $tableName );
1381 return $this->
query( $sql, $fName );
1424 $this->
name = $info[
'COLUMN_NAME'];
1426 $this->
default = $info[
'COLUMN_DEFAULT'];
1427 $this->max_length = $info[
'CHARACTER_MAXIMUM_LENGTH'];
1428 $this->nullable = !( strtolower( $info[
'IS_NULLABLE'] ) ==
'no' );
1429 $this->
type = $info[
'DATA_TYPE'];
1461 } elseif ( $data instanceof
Blob ) {
1462 $this->mData = $data->fetch();
1463 } elseif ( is_array( $data ) && is_object( $data ) ) {
1466 $this->mData = $data;
1476 if ( $this->mData === null ) {
1481 $dataLength = strlen( $this->mData );
1482 for ( $i = 0; $i < $dataLength; $i++ ) {
1483 $ret .= bin2hex( pack(
'C', ord( $this->mData[$i] ) ) );
1499 if ( $this->mSeekTo !== null ) {
1500 $result = sqlsrv_fetch_object(
$res,
'stdClass', [],
1501 SQLSRV_SCROLL_ABSOLUTE, $this->mSeekTo );
1502 $this->mSeekTo = null;
1521 if ( $this->mSeekTo !== null ) {
1522 $result = sqlsrv_fetch_array(
$res, SQLSRV_FETCH_BOTH,
1523 SQLSRV_SCROLL_ABSOLUTE, $this->mSeekTo );
1524 $this->mSeekTo = null;
1545 $numRows = $this->db->numRows(
$res );
1546 $row = intval( $row );
1548 if ( $numRows === 0 ) {
1550 } elseif ( $row < 0 || $row > $numRows - 1 ) {
1555 $this->mSeekTo = $row;
fieldExists($table, $field, $fname=__METHOD__)
Query whether a given column exists in the mediawiki schema.
getBinaryColumns($table)
Returns an associative array for fields that are of type varbinary, binary, or image $table can be ei...
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
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
the array() calling protocol came about after MediaWiki 1.4rc1.
doCommit($fname=__METHOD__)
End a transaction.
Utility classThis allows us to distinguish a blob from a normal string and an array of strings...
realTableName($name, $format= 'quoted')
call this instead of tableName() in the updater when renaming tables
buildGroupConcatField($delim, $table, $field, $conds= '', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
doBegin($fname=__METHOD__)
Begin a transaction, committing any previously open transaction.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
makeOrderBy($options)
Returns an optional ORDER BY.
doRollback($fname=__METHOD__)
Rollback a transaction.
insertSelect($destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[])
INSERT SELECT wrapper $varMap must be an associative array of the form array( 'dest1' => 'source1'...
resource $mConn
Database connection.
unionSupportsOrderAndLimit()
Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries within th...
isNullable()
Whether this field can store NULL values.
$wgDBmwschema
Mediawiki schema.
isQuotedIdentifier($name)
Base for all database-specific classes representing information about database fields.
when a variable name is used in a it is silently declared as a new local masking the global
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
$wgDBWindowsAuthentication
Use Windows Authentication instead of $wgDBuser / $wgDBpassword for MS SQL Server.
close()
Closes a database connection.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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
freeResult($res)
Free a result object returned by query() or select().
escapeIdentifier($identifier)
Escapes a identifier for use inm SQL.
estimateRowCount($table, $vars= '*', $conds= '', $fname=__METHOD__, $options=[])
Estimate rows in dataset Returns estimated count, based on SHOWPLAN_ALL output This is not necessaril...
scrollableCursor($value=null)
Called in the installer and updater.
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
indexInfo($table, $index, $fname=__METHOD__)
Returns information about an index If errors are explicitly ignored, returns NULL on failure...
fieldInfo($table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
tableExists($table, $fname=__METHOD__)
deleteJoin($delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
debug($debug=null)
Boolean, controls output of large amounts of debug information.
makeSelectOptions($options)
makeList($a, $mode=LIST_COMMA, $binaryColumns=[])
Makes an encoded list of strings from an array.
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
tableName()
Name of table this field belongs to.
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
escapeLikeInternal($s)
MS SQL supports more pattern operators than other databases (ex: [,],^)
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
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
tableName($name, $format= 'quoted')
insertId()
This must be called after nextSequenceVal.
LimitToTopN($sql)
If there is a limit clause, parse it, strip it, and pass the remaining SQL through limitResult() with...
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
$wgDBport
Database port number (for PostgreSQL and Microsoft SQL Server).
insert($table, $arrToInsert, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
limitResult($sql, $limit, $offset=false)
Construct a LIMIT query with optional offset This is used for query pages.
query($sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
closeConnection()
Closes a database connection, if it is open Returns success, true if already closed.
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
makeUpdateOptions($options)
Make UPDATE options for the DatabaseBase::update function.
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 the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
select($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
SELECT wrapper.
fetch()
Returns an unquoted hex representation of a binary string for insertion into varbinary-type fields...
makeGroupByWithHaving($options)
Returns an optional GROUP BY with an optional HAVING.
Result wrapper for grabbing data queried by someone else.
open($server, $user, $password, $dbName)
Usually aborts on failure.
dropTable($tableName, $fName=__METHOD__)
Delete a table.
buildLike()
MS SQL requires specifying the escape character used in a LIKE query or using Square brackets to surr...
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
update($table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
selectSQLText($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
SELECT wrapper.
prepareStatements($value=null)
Called in the installer and updater.
ignoreErrors(array $value=null)
Called in the installer and updater.
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
Allows to change the fields on the form that will be generated $name
textFieldSize($table, $field)