31use InvalidArgumentException;
72 if ( isset( $p[
'dbFilePath'] ) ) {
73 $this->dbPath = $p[
'dbFilePath'];
74 $lockDomain = md5( $this->dbPath );
76 if ( !isset( $p[
'dbname'] ) || !strlen( $p[
'dbname'] ) ) {
77 $p[
'dbname'] = preg_replace(
'/\.sqlite\d?$/',
'', basename( $this->dbPath ) );
79 } elseif ( isset( $p[
'dbDirectory'] ) ) {
80 $this->dbDir = $p[
'dbDirectory'];
81 $lockDomain = $p[
'dbname'];
83 throw new InvalidArgumentException(
"Need 'dbDirectory' or 'dbFilePath' parameter." );
86 $this->trxMode = isset( $p[
'trxMode'] ) ? strtoupper( $p[
'trxMode'] ) :
null;
87 if ( $this->trxMode &&
88 !in_array( $this->trxMode, [
'DEFERRED',
'IMMEDIATE',
'EXCLUSIVE' ] )
90 $this->trxMode =
null;
91 $this->queryLogger->warning(
"Invalid SQLite transaction mode provided." );
95 'domain' => $lockDomain,
96 'lockDirectory' =>
"{$this->dbDir}/locks"
99 parent::__construct( $p );
103 return [ self::ATTR_DB_LEVEL_LOCKING =>
true ];
116 $p[
'dbFilePath'] = $filename;
118 $p[
'tablePrefix'] =
'';
126 if ( $this->dbPath !==
null ) {
130 $this->connectionParams[
'dbname'],
131 $this->connectionParams[
'tablePrefix']
133 } elseif ( $this->dbDir !==
null ) {
135 if ( strlen( $this->connectionParams[
'dbname'] ) ) {
137 $this->connectionParams[
'host'],
138 $this->connectionParams[
'user'],
139 $this->connectionParams[
'password'],
140 $this->connectionParams[
'dbname'],
141 $this->connectionParams[
'schema'],
142 $this->connectionParams[
'tablePrefix']
146 $this->connLogger->debug( __METHOD__ .
': no database opened.' );
149 throw new InvalidArgumentException(
"Need 'dbDirectory' or 'dbFilePath' parameter." );
172 if ( !is_readable( $fileName ) ) {
177 $this->
openFile( $fileName, $dbName, $tablePrefix );
191 protected function openFile( $fileName, $dbName, $tablePrefix ) {
194 $this->dbPath = $fileName;
196 if ( $this->flags & self::DBO_PERSISTENT ) {
197 $this->conn =
new PDO(
"sqlite:$fileName",
'',
'',
198 [ PDO::ATTR_PERSISTENT =>
true ] );
200 $this->conn =
new PDO(
"sqlite:$fileName",
'',
'' );
202 }
catch ( PDOException
$e ) {
203 $err =
$e->getMessage();
206 if ( !$this->conn ) {
207 $this->queryLogger->debug(
"DB connection error: $err\n" );
211 $this->opened = is_object( $this->conn );
212 if ( $this->opened ) {
213 $this->currentDomain =
new DatabaseDomain( $dbName,
null, $tablePrefix );
214 # Set error codes only, don't raise exceptions
215 $this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
216 # Enforce LIKE to be case sensitive, just like MySQL
217 $this->
query(
'PRAGMA case_sensitive_like = 1' );
219 $sync = $this->sessionVars[
'synchronous'] ??
null;
220 if ( in_array( $sync, [
'EXTRA',
'FULL',
'NORMAL' ],
true ) ) {
221 $this->
query(
"PRAGMA synchronous = $sync" );
255 return "$dir/$dbName.sqlite";
263 if ( self::$fulltextEnabled ===
null ) {
264 self::$fulltextEnabled =
false;
265 $table = $this->
tableName(
'searchindex' );
266 $res = $this->
query(
"SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
268 $row =
$res->fetchRow();
269 self::$fulltextEnabled = stristr( $row[
'sql'],
'fts' ) !==
false;
281 static $cachedResult =
null;
282 if ( $cachedResult !==
null ) {
283 return $cachedResult;
285 $cachedResult =
false;
286 $table =
'dummy_search_test';
289 if ( $db->query(
"CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__,
true ) ) {
290 $cachedResult =
'FTS3';
294 return $cachedResult;
314 return $this->
query(
"ATTACH DATABASE $file AS $name",
$fname );
318 return parent::isWriteQuery( $sql ) && !preg_match(
'/^(ATTACH|PRAGMA)\b/i', $sql );
322 return parent::isTransactableQuery( $sql ) && !in_array(
324 [
'ATTACH',
'PRAGMA' ],
337 if (
$res ===
false ) {
342 $this->lastAffectedRowCount = $r->rowCount();
370 $cur = current( $r );
371 if ( is_array( $cur ) ) {
374 foreach ( $cur
as $k => $v ) {
375 if ( !is_numeric( $k ) ) {
396 $cur = current( $r );
397 if ( is_array( $cur ) ) {
416 return is_array( $r ) ? count( $r ) : 0;
425 if ( is_array( $r ) && count( $r ) > 0 ) {
427 return count( $r[0] ) / 2;
441 if ( is_array( $r ) ) {
442 $keys = array_keys( $r[0] );
459 if ( strpos(
$name,
'sqlite_' ) === 0 ) {
463 return str_replace(
'"',
'', parent::tableName(
$name, $format ) );
488 for ( $i = 0; $i < $row; $i++ ) {
498 if ( !is_object( $this->conn ) ) {
499 return "Cannot return last error, no db connection";
501 $e = $this->conn->errorInfo();
510 if ( !is_object( $this->conn ) ) {
511 return "Cannot return last error, no db connection";
513 $info = $this->conn->errorInfo();
527 $tableRaw = $this->
tableName( $table,
'raw' );
528 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
532 $encTable = $this->
addQuotes( $tableRaw );
534 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
536 return $res->numRows() ?
true :
false;
552 if ( !
$res ||
$res->numRows() == 0 ) {
556 foreach (
$res as $row ) {
557 $info[] = $row->name;
570 $row = $this->
selectRow(
'sqlite_master',
'*',
575 if ( !$row || !isset( $row->sql ) ) {
580 $indexPos = strpos( $row->sql,
'INDEX' );
581 if ( $indexPos ===
false ) {
584 $firstPart = substr( $row->sql, 0, $indexPos );
585 $options = explode(
' ', $firstPart );
587 return in_array(
'UNIQUE',
$options );
598 if ( is_numeric( $k ) && ( $v ==
'FOR UPDATE' || $v ==
'LOCK IN SHARE MODE' ) ) {
603 return parent::makeSelectOptions(
$options );
622 # SQLite uses OR IGNORE not just IGNORE
624 if ( $v ==
'IGNORE' ) {
639 return parent::makeInsertOptions(
$options );
651 if ( !count( $a ) ) {
655 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
656 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
660 foreach ( $a
as $v ) {
661 parent::insert( $table, $v,
"$fname/multi-row",
$options );
665 }
catch ( Exception
$e ) {
671 parent::insert( $table, $a,
"$fname/single-row",
$options );
684 if ( !count(
$rows ) ) {
688 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
689 if ( isset(
$rows[0] ) && is_array(
$rows[0] ) ) {
698 }
catch ( Exception
$e ) {
733 $glue = $all ?
' UNION ALL ' :
' UNION ';
735 return implode( $glue, $sqls );
768 return "[{{int:version-db-sqlite-url}} SQLite]";
790 $sql =
'PRAGMA table_info(' . $this->
addQuotes( $tableName ) .
')';
792 foreach (
$res as $row ) {
793 if ( $row->name == $field ) {
802 if ( $this->trxMode ) {
823 return new Blob( $b );
831 if ( $b instanceof
Blob ) {
843 if (
$s instanceof
Blob ) {
844 return "x'" . bin2hex(
$s->fetch() ) .
"'";
845 } elseif ( is_bool(
$s ) ) {
847 } elseif ( strpos( (
string)
$s,
"\0" ) !==
false ) {
857 $this->queryLogger->debug(
859 ': Quoting value containing null byte. ' .
860 'For consistency all binary data should have been ' .
861 'first processed with self::encodeBlob()'
863 return "x'" . bin2hex( (
string)
$s ) .
"'";
872 if ( $length !==
null ) {
875 return 'SUBSTR(' . implode(
',',
$params ) .
')';
884 return 'CAST ( ' . $field .
' AS TEXT )';
893 $args = func_get_args();
894 $function = array_shift(
$args );
896 return $function( ...
$args );
904 $s = parent::replaceVars(
$s );
905 if ( preg_match(
'/^\s*(CREATE|ALTER) TABLE/i',
$s ) ) {
909 $s = preg_replace(
'/\b(var)?binary(\(\d+\))/i',
'BLOB',
$s );
911 $s = preg_replace(
'/\b(un)?signed\b/i',
'',
$s );
913 $s = preg_replace(
'/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i',
'INTEGER',
$s );
916 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
921 $s = preg_replace(
'/\b(var)?char\s*\(.*?\)/i',
'TEXT',
$s );
923 $s = preg_replace(
'/\b(tiny|medium|long)text\b/i',
'TEXT',
$s );
925 $s = preg_replace(
'/\b(tiny|small|medium|long|)blob\b/i',
'BLOB',
$s );
927 $s = preg_replace(
'/\bbool(ean)?\b/i',
'INTEGER',
$s );
929 $s = preg_replace(
'/\b(datetime|timestamp)\b/i',
'TEXT',
$s );
931 $s = preg_replace(
'/\benum\s*\([^)]*\)/i',
'TEXT',
$s );
933 $s = preg_replace(
'/\bbinary\b/i',
'',
$s );
935 $s = preg_replace(
'/\bauto_increment\b/i',
'AUTOINCREMENT',
$s );
937 $s = preg_replace(
'/\)[^);]*(;?)\s*$/',
')\1',
$s );
939 $s = preg_replace(
'/primary key (.*?) autoincrement/i',
'PRIMARY KEY AUTOINCREMENT $1',
$s );
940 } elseif ( preg_match(
'/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i',
$s ) ) {
942 $s = preg_replace(
'/\(\d+\)/',
'',
$s );
944 $s = preg_replace(
'/\bfulltext\b/i',
'',
$s );
945 } elseif ( preg_match(
'/^\s*DROP INDEX/i',
$s ) ) {
947 $s = preg_replace(
'/\sON\s+[^\s]*/i',
'',
$s );
948 } elseif ( preg_match(
'/^\s*INSERT IGNORE\b/i',
$s ) ) {
950 $s = preg_replace(
'/^\s*INSERT IGNORE\b/i',
'INSERT OR IGNORE',
$s );
956 public function lock( $lockName, $method, $timeout = 5 ) {
957 if ( !is_dir(
"{$this->dbDir}/locks" ) ) {
958 if ( !is_writable( $this->dbDir ) || !mkdir(
"{$this->dbDir}/locks" ) ) {
959 throw new DBError( $this,
"Cannot create directory \"{$this->dbDir}/locks\"." );
966 public function unlock( $lockName, $method ) {
977 return '(' . implode(
') || (', $stringList ) .
')';
981 $delim, $table, $field, $conds =
'', $join_conds = []
983 $fld =
"group_concat($field," . $this->
addQuotes( $delim ) .
')';
985 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
997 $res = $this->
query(
"SELECT sql FROM sqlite_master WHERE tbl_name=" .
1001 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
1004 $sql = preg_replace(
1013 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1014 $this->queryLogger->debug(
1015 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1017 $sql = str_replace(
'CREATE TABLE',
'CREATE TEMPORARY TABLE', $sql );
1024 $indexList = $this->
query(
'PRAGMA INDEX_LIST(' . $this->
addQuotes( $oldName ) .
')' );
1025 foreach ( $indexList
as $index ) {
1026 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
1030 if ( $index->unique ) {
1031 $sql =
'CREATE UNIQUE INDEX';
1033 $sql =
'CREATE INDEX';
1036 $indexName = $newName .
'_' . $index->name;
1037 $sql .=
' ' . $indexName .
' ON ' . $newName;
1039 $indexInfo = $this->
query(
'PRAGMA INDEX_INFO(' . $this->
addQuotes( $index->name ) .
')' );
1041 foreach ( $indexInfo
as $indexInfoRow ) {
1042 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
1045 $sql .=
'(' . implode(
',', $fields ) .
')';
1047 $this->
query( $sql );
1071 $vars = get_object_vars( $table );
1072 $table = array_pop(
$vars );
1074 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1075 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
1076 $endArray[] = $table;
1092 public function dropTable( $tableName, $fName = __METHOD__ ) {
1093 if ( !$this->
tableExists( $tableName, $fName ) ) {
1096 $sql =
"DROP TABLE " . $this->
tableName( $tableName );
1098 return $this->
query( $sql, $fName );
1102 parent::setTableAliases( $aliases );
1103 foreach ( $this->tableAliases
as $params ) {
1104 if ( isset( $this->alreadyAttached[
$params[
'dbname']] ) ) {
1108 $this->alreadyAttached[
$params[
'dbname']] =
true;
1115 $this->
query(
"DELETE FROM $encTable WHERE name = $encName",
$fname );
1126 return is_object( $this->conn )
1127 ?
'SQLite ' . (
string)$this->conn->getAttribute( PDO::ATTR_SERVER_VERSION )
1128 :
'(not connected)';
1135 return parent::getBindingHandle();
1142class_alias( DatabaseSqlite::class,
'DatabaseSqlite' );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Simple version of LockManager based on using FS lock files.
Class for handling resource locking.
Class to handle database/prefix specification for IDatabase domains.
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 select() and insert() are usually more convenient. They take care of things like table prefixes and escaping for you. If you really need to make your own SQL
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
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
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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 since 1.28! 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 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
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 & $options
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
Allows to change the fields on the form that will be generated $name
returning false will NOT prevent logging $e
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
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(is_array($mode)) switch( $mode) $input
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file