MediaWiki  1.27.2
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 
185  $dir = $this->getVar( 'wgSQLiteDataDir' );
186  $dbName = $this->getVar( 'wgDBname' );
187  try {
188  # @todo FIXME: Need more sensible constructor parameters, e.g. single associative array
189  # Setting globals kind of sucks
190  $wgSQLiteDataDir = $dir;
191  $db = DatabaseBase::factory( 'sqlite', [ 'dbname' => $dbName ] );
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 {
247  # @todo FIXME: setting globals kind of sucks
248  $wgSQLiteDataDir = $dir;
249  $conn = DatabaseBase::factory( 'sqlite', [ 'dbname' => "wikicache" ] );
250  # @todo: don't duplicate objectcache definition, though it's very simple
251  $sql =
252 <<<EOT
253  CREATE TABLE IF NOT EXISTS objectcache (
254  keyname BLOB NOT NULL default '' PRIMARY KEY,
255  value BLOB,
256  exptime TEXT
257  )
258 EOT;
259  $conn->query( $sql );
260  $conn->query( "CREATE INDEX IF NOT EXISTS exptime ON objectcache (exptime)" );
261  $conn->query( "PRAGMA journal_mode=WAL" ); // this is permanent
262  $conn->close();
263  } catch ( DBConnectionError $e ) {
264  return Status::newFatal( 'config-sqlite-connection-error', $e->getMessage() );
265  }
266 
267  # Open the main DB
268  return $this->getConnection();
269  }
270 
271  protected function makeStubDBFile( $dir, $db ) {
273  if ( file_exists( $file ) ) {
274  if ( !is_writable( $file ) ) {
275  return Status::newFatal( 'config-sqlite-readonly', $file );
276  }
277  } else {
278  if ( file_put_contents( $file, '' ) === false ) {
279  return Status::newFatal( 'config-sqlite-cant-create-db', $file );
280  }
281  }
282 
283  return Status::newGood();
284  }
285 
289  public function createTables() {
290  $status = parent::createTables();
291 
292  return $this->setupSearchIndex( $status );
293  }
294 
299  public function setupSearchIndex( &$status ) {
300  global $IP;
301 
303  $fts3tTable = $this->db->checkForEnabledSearch();
304  if ( $fts3tTable && !$module ) {
305  $status->warning( 'config-sqlite-fts3-downgrade' );
306  $this->db->sourceFile( "$IP/maintenance/sqlite/archives/searchindex-no-fts.sql" );
307  } elseif ( !$fts3tTable && $module == 'FTS3' ) {
308  $this->db->sourceFile( "$IP/maintenance/sqlite/archives/searchindex-fts3.sql" );
309  }
310 
311  return $status;
312  }
313 
317  public function getLocalSettings() {
318  $dir = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgSQLiteDataDir' ) );
319 
320  return "# SQLite-specific settings
321 \$wgSQLiteDataDir = \"{$dir}\";
322 \$wgObjectCaches[CACHE_DB] = [
323  'class' => 'SqlBagOStuff',
324  'loggroup' => 'SQLBagOStuff',
325  'server' => [
326  'type' => 'sqlite',
327  'dbname' => 'wikicache',
328  'tablePrefix' => '',
329  'flags' => 0
330  ]
331 ];";
332  }
333 }
$wgSQLiteDataDir
To override default SQLite data directory ($docroot/../data)
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:1932
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
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
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':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:1796
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:602
static factory($dbType, $p=[])
Given a DB type, construct the name of the appropriate child class of DatabaseBase.
Definition: Database.php:580
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:1004
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...
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101