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