MediaWiki  1.29.1
SqliteInstaller.php
Go to the documentation of this file.
1 <?php
27 
35  const MINIMUM_VERSION = '3.3.7';
36 
40  public $db;
41 
42  protected $globalNames = [
43  'wgDBname',
44  'wgSQLiteDataDir',
45  ];
46 
47  public function getName() {
48  return 'sqlite';
49  }
50 
51  public function isCompiled() {
52  return self::checkExtension( 'pdo_sqlite' );
53  }
54 
59  public function checkPrerequisites() {
61  // Bail out if SQLite is too old
62  $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
63  if ( version_compare( $db->getServerVersion(), self::MINIMUM_VERSION, '<' ) ) {
64  $result->fatal( 'config-outdated-sqlite', $db->getServerVersion(), self::MINIMUM_VERSION );
65  }
66  // Check for FTS3 full-text search module
67  if ( DatabaseSqlite::getFulltextSearchModule() != 'FTS3' ) {
68  $result->warning( 'config-no-fts3' );
69  }
70 
71  return $result;
72  }
73 
74  public function getGlobalDefaults() {
75  $defaults = parent::getGlobalDefaults();
76  if ( isset( $_SERVER['DOCUMENT_ROOT'] ) ) {
77  $path = str_replace(
78  [ '/', '\\' ],
79  DIRECTORY_SEPARATOR,
80  dirname( $_SERVER['DOCUMENT_ROOT'] ) . '/data'
81  );
82 
83  $defaults['wgSQLiteDataDir'] = $path;
84  }
85  return $defaults;
86  }
87 
88  public function getConnectForm() {
89  return $this->getTextBox(
90  'wgSQLiteDataDir',
91  'config-sqlite-dir', [],
92  $this->parent->getHelpBox( 'config-sqlite-dir-help' )
93  ) .
94  $this->getTextBox(
95  'wgDBname',
96  'config-db-name',
97  [],
98  $this->parent->getHelpBox( 'config-sqlite-name-help' )
99  );
100  }
101 
109  private static function realpath( $path ) {
110  $result = realpath( $path );
111  if ( !$result ) {
112  return $path;
113  }
114 
115  return $result;
116  }
117 
121  public function submitConnectForm() {
122  $this->setVarsFromRequest( [ 'wgSQLiteDataDir', 'wgDBname' ] );
123 
124  # Try realpath() if the directory already exists
125  $dir = self::realpath( $this->getVar( 'wgSQLiteDataDir' ) );
126  $result = self::dataDirOKmaybeCreate( $dir, true /* create? */ );
127  if ( $result->isOK() ) {
128  # Try expanding again in case we've just created it
129  $dir = self::realpath( $dir );
130  $this->setVar( 'wgSQLiteDataDir', $dir );
131  }
132  # Table prefix is not used on SQLite, keep it empty
133  $this->setVar( 'wgDBprefix', '' );
134 
135  return $result;
136  }
137 
143  private static function dataDirOKmaybeCreate( $dir, $create = false ) {
144  if ( !is_dir( $dir ) ) {
145  if ( !is_writable( dirname( $dir ) ) ) {
146  $webserverGroup = Installer::maybeGetWebserverPrimaryGroup();
147  if ( $webserverGroup !== null ) {
148  return Status::newFatal(
149  'config-sqlite-parent-unwritable-group',
150  $dir, dirname( $dir ), basename( $dir ),
151  $webserverGroup
152  );
153  } else {
154  return Status::newFatal(
155  'config-sqlite-parent-unwritable-nogroup',
156  $dir, dirname( $dir ), basename( $dir )
157  );
158  }
159  }
160 
161  # Called early on in the installer, later we just want to sanity check
162  # if it's still writable
163  if ( $create ) {
164  MediaWiki\suppressWarnings();
165  $ok = wfMkdirParents( $dir, 0700, __METHOD__ );
166  MediaWiki\restoreWarnings();
167  if ( !$ok ) {
168  return Status::newFatal( 'config-sqlite-mkdir-error', $dir );
169  }
170  # Put a .htaccess file in in case the user didn't take our advice
171  file_put_contents( "$dir/.htaccess", "Deny from all\n" );
172  }
173  }
174  if ( !is_writable( $dir ) ) {
175  return Status::newFatal( 'config-sqlite-dir-unwritable', $dir );
176  }
177 
178  # We haven't blown up yet, fall through
179  return Status::newGood();
180  }
181 
185  public function openConnection() {
187  $dir = $this->getVar( 'wgSQLiteDataDir' );
188  $dbName = $this->getVar( 'wgDBname' );
189  try {
190  # @todo FIXME: Need more sensible constructor parameters, e.g. single associative array
191  $db = Database::factory( 'sqlite', [ 'dbname' => $dbName, 'dbDirectory' => $dir ] );
192  $status->value = $db;
193  } catch ( DBConnectionError $e ) {
194  $status->fatal( 'config-sqlite-connection-error', $e->getMessage() );
195  }
196 
197  return $status;
198  }
199 
203  public function needsUpgrade() {
204  $dir = $this->getVar( 'wgSQLiteDataDir' );
205  $dbName = $this->getVar( 'wgDBname' );
206  // Don't create the data file yet
207  if ( !file_exists( DatabaseSqlite::generateFileName( $dir, $dbName ) ) ) {
208  return false;
209  }
210 
211  // If the data file exists, look inside it
212  return parent::needsUpgrade();
213  }
214 
218  public function setupDatabase() {
219  $dir = $this->getVar( 'wgSQLiteDataDir' );
220 
221  # Sanity check. We checked this before but maybe someone deleted the
222  # data dir between then and now
223  $dir_status = self::dataDirOKmaybeCreate( $dir, false /* create? */ );
224  if ( !$dir_status->isOK() ) {
225  return $dir_status;
226  }
227 
228  $db = $this->getVar( 'wgDBname' );
229 
230  # Make the main and cache stub DB files
232  $status->merge( $this->makeStubDBFile( $dir, $db ) );
233  $status->merge( $this->makeStubDBFile( $dir, "wikicache" ) );
234  if ( !$status->isOK() ) {
235  return $status;
236  }
237 
238  # Nuke the unused settings for clarity
239  $this->setVar( 'wgDBserver', '' );
240  $this->setVar( 'wgDBuser', '' );
241  $this->setVar( 'wgDBpassword', '' );
242  $this->setupSchemaVars();
243 
244  # Create the global cache DB
245  try {
246  $conn = Database::factory( 'sqlite', [ 'dbname' => 'wikicache', 'dbDirectory' => $dir ] );
247  # @todo: don't duplicate objectcache definition, though it's very simple
248  $sql =
249 <<<EOT
250  CREATE TABLE IF NOT EXISTS objectcache (
251  keyname BLOB NOT NULL default '' PRIMARY KEY,
252  value BLOB,
253  exptime TEXT
254  )
255 EOT;
256  $conn->query( $sql );
257  $conn->query( "CREATE INDEX IF NOT EXISTS exptime ON objectcache (exptime)" );
258  $conn->query( "PRAGMA journal_mode=WAL" ); // this is permanent
259  $conn->close();
260  } catch ( DBConnectionError $e ) {
261  return Status::newFatal( 'config-sqlite-connection-error', $e->getMessage() );
262  }
263 
264  # Open the main DB
265  return $this->getConnection();
266  }
267 
273  protected function makeStubDBFile( $dir, $db ) {
274  $file = DatabaseSqlite::generateFileName( $dir, $db );
275  if ( file_exists( $file ) ) {
276  if ( !is_writable( $file ) ) {
277  return Status::newFatal( 'config-sqlite-readonly', $file );
278  }
279  } else {
280  if ( file_put_contents( $file, '' ) === false ) {
281  return Status::newFatal( 'config-sqlite-cant-create-db', $file );
282  }
283  }
284 
285  return Status::newGood();
286  }
287 
291  public function createTables() {
292  $status = parent::createTables();
293 
294  return $this->setupSearchIndex( $status );
295  }
296 
301  public function setupSearchIndex( &$status ) {
302  global $IP;
303 
304  $module = DatabaseSqlite::getFulltextSearchModule();
305  $fts3tTable = $this->db->checkForEnabledSearch();
306  if ( $fts3tTable && !$module ) {
307  $status->warning( 'config-sqlite-fts3-downgrade' );
308  $this->db->sourceFile( "$IP/maintenance/sqlite/archives/searchindex-no-fts.sql" );
309  } elseif ( !$fts3tTable && $module == 'FTS3' ) {
310  $this->db->sourceFile( "$IP/maintenance/sqlite/archives/searchindex-fts3.sql" );
311  }
312 
313  return $status;
314  }
315 
319  public function getLocalSettings() {
320  $dir = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgSQLiteDataDir' ) );
321 
322  return "# SQLite-specific settings
323 \$wgSQLiteDataDir = \"{$dir}\";
324 \$wgObjectCaches[CACHE_DB] = [
325  'class' => 'SqlBagOStuff',
326  'loggroup' => 'SQLBagOStuff',
327  'server' => [
328  'type' => 'sqlite',
329  'dbname' => 'wikicache',
330  'tablePrefix' => '',
331  'dbDirectory' => \$wgSQLiteDataDir,
332  'flags' => 0
333  ]
334 ];";
335  }
336 }
SqliteInstaller\makeStubDBFile
makeStubDBFile( $dir, $db)
Definition: SqliteInstaller.php:273
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:45
SqliteInstaller\setupDatabase
setupDatabase()
Definition: SqliteInstaller.php:218
Wikimedia\Rdbms\DatabaseSqlite
Definition: DatabaseSqlite.php:37
SqliteInstaller
Class for setting up the MediaWiki database using SQLLite.
Definition: SqliteInstaller.php:34
SqliteInstaller\openConnection
openConnection()
Definition: SqliteInstaller.php:185
DatabaseInstaller\checkExtension
static checkExtension( $name)
Convenience function.
Definition: DatabaseInstaller.php:411
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:2080
SqliteInstaller\dataDirOKmaybeCreate
static dataDirOKmaybeCreate( $dir, $create=false)
Definition: SqliteInstaller.php:143
$result
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
Definition: hooks.txt:1954
DatabaseInstaller\getConnection
getConnection()
Connect to the database using the administrative user/password currently defined in the session.
Definition: DatabaseInstaller.php:152
$status
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
Definition: hooks.txt:1049
use
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
Definition: MIT-LICENSE.txt:10
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:63
DatabaseInstaller\getTextBox
getTextBox( $var, $label, $attribs=[], $helpData="")
Get a labelled text box to configure a local variable.
Definition: DatabaseInstaller.php:483
Wikimedia\Rdbms\DatabaseSqlite\getServerVersion
getServerVersion()
Definition: DatabaseSqlite.php:720
SqliteInstaller\getConnectForm
getConnectForm()
Get HTML for a web form that configures this database.
Definition: SqliteInstaller.php:88
SqliteInstaller\isCompiled
isCompiled()
Definition: SqliteInstaller.php:51
php
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
Definition: injection.txt:35
SqliteInstaller\$globalNames
$globalNames
Definition: SqliteInstaller.php:42
SqliteInstaller\realpath
static realpath( $path)
Safe wrapper for PHP's realpath() that fails gracefully if it's unable to canonicalize the path.
Definition: SqliteInstaller.php:109
$IP
$IP
Definition: update.php:3
DatabaseInstaller\setupSchemaVars
setupSchemaVars()
Set appropriate schema variables in the current database connection.
Definition: DatabaseInstaller.php:312
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
$dir
$dir
Definition: Autoload.php:8
SqliteInstaller\MINIMUM_VERSION
const MINIMUM_VERSION
Definition: SqliteInstaller.php:35
SqliteInstaller\setupSearchIndex
setupSearchIndex(&$status)
Definition: SqliteInstaller.php:301
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
value
$status value
Definition: SyntaxHighlight_GeSHi.class.php:309
SqliteInstaller\submitConnectForm
submitConnectForm()
Definition: SqliteInstaller.php:121
DatabaseInstaller\getVar
getVar( $var, $default=null)
Get a variable, taking local defaults into account.
Definition: DatabaseInstaller.php:453
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:76
SqliteInstaller\createTables
createTables()
Definition: SqliteInstaller.php:291
DatabaseInstaller
Base class for DBMS-specific installation helper classes.
Definition: DatabaseInstaller.php:33
SqliteInstaller\getGlobalDefaults
getGlobalDefaults()
Get a name=>value map of MW configuration globals for the default values.
Definition: SqliteInstaller.php:74
SqliteInstaller\checkPrerequisites
checkPrerequisites()
Definition: SqliteInstaller.php:59
SqliteInstaller\getLocalSettings
getLocalSettings()
Definition: SqliteInstaller.php:319
SqliteInstaller\getName
getName()
Return the internal name, e.g.
Definition: SqliteInstaller.php:47
$path
$path
Definition: NoLocalSettings.php:26
SqliteInstaller\needsUpgrade
needsUpgrade()
Definition: SqliteInstaller.php:203
DatabaseInstaller\setVar
setVar( $name, $value)
Convenience alias for $this->parent->setVar()
Definition: DatabaseInstaller.php:470
DatabaseInstaller\setVarsFromRequest
setVarsFromRequest( $varNames)
Convenience function to set variables based on form data.
Definition: DatabaseInstaller.php:576
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
LocalSettingsGenerator\escapePhpString
static escapePhpString( $string)
Returns the escaped version of a string of php code.
Definition: LocalSettingsGenerator.php:114
SqliteInstaller\$db
DatabaseSqlite $db
Definition: SqliteInstaller.php:40
Installer\maybeGetWebserverPrimaryGroup
static maybeGetWebserverPrimaryGroup()
On POSIX systems return the primary group of the webserver we're running under.
Definition: Installer.php:643