Debian Codegraph @

includes/installer/SqliteInstaller.php

raw symbols SCIP
1 <?php
2
3 /**
4 * Sqlite-specific installer.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Installer
23 */
24
25 namespace MediaWiki\Installer;
26
27 use MediaWiki\MediaWikiServices;
28 use MediaWiki\Status\Status;
29 use Wikimedia\AtEase\AtEase;
30 use Wikimedia\Rdbms\DatabaseFactory;
31 use Wikimedia\Rdbms\DatabaseSqlite;
32 use Wikimedia\Rdbms\DBConnectionError;
33
34 /**
35 * Class for setting up the MediaWiki database using SQLLite.
36 *
37 * @ingroup Installer
38 * @since 1.17
39 */
40 class SqliteInstaller extends DatabaseInstaller {
41
42 /** @inheritDoc */
43 public static $minimumVersion = '3.8.0';
44 /** @inheritDoc */
45 protected static $notMinimumVersionMessage = 'config-outdated-sqlite';
46
47 /**
48 * @var DatabaseSqlite
49 */
50 public $db;
51
52 /** @inheritDoc */
53 protected $globalNames = [
54 'wgDBname',
55 'wgSQLiteDataDir',
56 ];
57
58 public function getName() {
59 return 'sqlite';
60 }
61
62 public function isCompiled() {
63 return self::checkExtension( 'pdo_sqlite' );
64 }
65
66 public function getConnectForm( WebInstaller $webInstaller ): DatabaseConnectForm {
67 return new SqliteConnectForm( $webInstaller, $this );
68 }
69
70 public function getSettingsForm( WebInstaller $webInstaller ): DatabaseSettingsForm {
71 return new DatabaseSettingsForm( $webInstaller, $this );
72 }
73
74 /**
75 * @return Status
76 */
77 public function checkPrerequisites() {
78 // Bail out if SQLite is too old
79 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
80 $result = static::meetsMinimumRequirement( $db );
81 // Check for FTS3 full-text search module
82 if ( DatabaseSqlite::getFulltextSearchModule() != 'FTS3' ) {
83 $result->warning( 'config-no-fts3' );
84 }
85
86 return $result;
87 }
88
89 public function getGlobalDefaults() {
90 global $IP;
91 $defaults = parent::getGlobalDefaults();
92 if ( !empty( $_SERVER['DOCUMENT_ROOT'] ) ) {
93 $path = dirname( $_SERVER['DOCUMENT_ROOT'] );
94 } else {
95 // We use $IP when unable to get $_SERVER['DOCUMENT_ROOT']
96 $path = $IP;
97 }
98 $defaults['wgSQLiteDataDir'] = str_replace(
99 [ '/', '\\' ],
100 DIRECTORY_SEPARATOR,
101 $path . '/data'
102 );
103 return $defaults;
104 }
105
106 /**
107 * Safe wrapper for PHP's realpath() that fails gracefully if it's unable to canonicalize the path.
108 *
109 * @param string $path
110 *
111 * @return string
112 */
113 public static function realpath( $path ) {
114 return realpath( $path ) ?: $path;
115 }
116
117 /**
118 * Check if the data directory is writable or can be created
119 * @param string $dir Path to the data directory
120 * @return Status Return fatal Status if $dir un-writable or no permission to create a directory
121 */
122 public static function checkDataDir( $dir ): Status {
123 if ( is_dir( $dir ) ) {
124 if ( !is_readable( $dir ) ) {
125 return Status::newFatal( 'config-sqlite-dir-unwritable', $dir );
126 }
127 } elseif ( !is_writable( dirname( $dir ) ) ) {
128 // Check the parent directory if $dir not exists
129 $webserverGroup = Installer::maybeGetWebserverPrimaryGroup();
130 if ( $webserverGroup !== null ) {
131 return Status::newFatal(
132 'config-sqlite-parent-unwritable-group',
133 $dir, dirname( $dir ), basename( $dir ),
134 $webserverGroup
135 );
136 }
137
138 return Status::newFatal(
139 'config-sqlite-parent-unwritable-nogroup',
140 $dir, dirname( $dir ), basename( $dir )
141 );
142 }
143 return Status::newGood();
144 }
145
146 /**
147 * @param string $dir Path to the data directory
148 * @return Status Return good Status if without error
149 */
150 private static function createDataDir( $dir ): Status {
151 if ( !is_dir( $dir ) ) {
152 AtEase::suppressWarnings();
153 $ok = wfMkdirParents( $dir, 0700, __METHOD__ );
154 AtEase::restoreWarnings();
155 if ( !$ok ) {
156 return Status::newFatal( 'config-sqlite-mkdir-error', $dir );
157 }
158 }
159 # Put a .htaccess file in case the user didn't take our advice
160 file_put_contents( "$dir/.htaccess",
161 "Require all denied\n" .
162 "Satisfy All\n" );
163 return Status::newGood();
164 }
165
166 /**
167 * @param string $type
168 * @return ConnectionStatus
169 */
170 public function openConnection( string $type ) {
171 $status = new ConnectionStatus;
172 $dir = $this->getVar( 'wgSQLiteDataDir' );
173 $dbName = $this->getVar( 'wgDBname' );
174
175 // Don't implicitly create the file
176 $file = DatabaseSqlite::generateFileName( $dir, $dbName );
177 if ( !file_exists( $file ) ) {
178 $status->fatal( 'config-sqlite-connection-error',
179 'file does not exist' );
180 return $status;
181 }
182
183 try {
184 $db = MediaWikiServices::getInstance()->getDatabaseFactory()->create(
185 'sqlite', [ 'dbname' => $dbName, 'dbDirectory' => $dir ]
186 );
187 $status->setDB( $db );
188 } catch ( DBConnectionError $e ) {
189 $status->fatal( 'config-sqlite-connection-error', $e->getMessage() );
190 }
191
192 return $status;
193 }
194
195 /**
196 * @return Status
197 */
198 public function setupDatabase() {
199 $dir = $this->getVar( 'wgSQLiteDataDir' );
200
201 # Double check (Only available in web installation). We checked this before but maybe someone
202 # deleted the data dir between then and now
203 $dir_status = self::checkDataDir( $dir );
204 if ( $dir_status->isGood() ) {
205 $res = self::createDataDir( $dir );
206 if ( !$res->isGood() ) {
207 return $res;
208 }
209 } else {
210 return $dir_status;
211 }
212
213 $db = $this->getVar( 'wgDBname' );
214
215 # Make the main and cache stub DB files
216 $status = Status::newGood();
217 $status->merge( $this->makeStubDBFile( $dir, $db ) );
218 $status->merge( $this->makeStubDBFile( $dir, "wikicache" ) );
219 $status->merge( $this->makeStubDBFile( $dir, "{$db}_l10n_cache" ) );
220 $status->merge( $this->makeStubDBFile( $dir, "{$db}_jobqueue" ) );
221 if ( !$status->isOK() ) {
222 return $status;
223 }
224
225 # Nuke the unused settings for clarity
226 $this->setVar( 'wgDBserver', '' );
227 $this->setVar( 'wgDBuser', '' );
228 $this->setVar( 'wgDBpassword', '' );
229
230 # Create the l10n cache DB
231 try {
232 $conn = ( new DatabaseFactory() )->create(
233 'sqlite', [ 'dbname' => "{$db}_l10n_cache", 'dbDirectory' => $dir ] );
234 # @todo: don't duplicate l10n_cache definition, though it's very simple
235 $sql =
236 <<<EOT
237 CREATE TABLE l10n_cache (
238 lc_lang BLOB NOT NULL,
239 lc_key TEXT NOT NULL,
240 lc_value BLOB NOT NULL,
241 PRIMARY KEY (lc_lang, lc_key)
242 );
243 EOT;
244 $conn->query( $sql, __METHOD__ );
245 $conn->query( "PRAGMA journal_mode=WAL", __METHOD__ ); // this is permanent
246 $conn->close( __METHOD__ );
247 } catch ( DBConnectionError $e ) {
248 return Status::newFatal( 'config-sqlite-connection-error', $e->getMessage() );
249 }
250
251 # Create the job queue DB
252 try {
253 $conn = ( new DatabaseFactory() )->create(
254 'sqlite', [ 'dbname' => "{$db}_jobqueue", 'dbDirectory' => $dir ] );
255 # @todo: don't duplicate job definition, though it's very static
256 $sql =
257 <<<EOT
258 CREATE TABLE job (
259 job_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
260 job_cmd BLOB NOT NULL default '',
261 job_namespace INTEGER NOT NULL,
262 job_title TEXT NOT NULL,
263 job_timestamp BLOB NULL default NULL,
264 job_params BLOB NOT NULL,
265 job_random integer NOT NULL default 0,
266 job_attempts integer NOT NULL default 0,
267 job_token BLOB NOT NULL default '',
268 job_token_timestamp BLOB NULL default NULL,
269 job_sha1 BLOB NOT NULL default ''
270 );
271 CREATE INDEX job_sha1 ON job (job_sha1);
272 CREATE INDEX job_cmd_token ON job (job_cmd,job_token,job_random);
273 CREATE INDEX job_cmd_token_id ON job (job_cmd,job_token,job_id);
274 CREATE INDEX job_cmd ON job (job_cmd, job_namespace, job_title, job_params);
275 CREATE INDEX job_timestamp ON job (job_timestamp);
276 EOT;
277 $conn->query( $sql, __METHOD__ );
278 $conn->query( "PRAGMA journal_mode=WAL", __METHOD__ ); // this is permanent
279 $conn->close( __METHOD__ );
280 } catch ( DBConnectionError $e ) {
281 return Status::newFatal( 'config-sqlite-connection-error', $e->getMessage() );
282 }
283
284 # Open the main DB
285 $mainConnStatus = $this->getConnection( self::CONN_CREATE_TABLES );
286 // Use WAL mode. This has better performance
287 // when the DB is being read and written concurrently.
288 // This causes the DB to be created in this mode
289 // so we only have to do this on creation.
290 $mainConnStatus->getDB()->query( "PRAGMA journal_mode=WAL", __METHOD__ );
291 return $mainConnStatus;
292 }
293
294 /**
295 * @param string $dir
296 * @param string $db
297 * @return Status
298 */
299 protected function makeStubDBFile( $dir, $db ) {
300 $file = DatabaseSqlite::generateFileName( $dir, $db );
301
302 if ( file_exists( $file ) ) {
303 if ( !is_writable( $file ) ) {
304 return Status::newFatal( 'config-sqlite-readonly', $file );
305 }
306 return Status::newGood();
307 }
308
309 $oldMask = umask( 0177 );
310 if ( file_put_contents( $file, '' ) === false ) {
311 umask( $oldMask );
312 return Status::newFatal( 'config-sqlite-cant-create-db', $file );
313 }
314 umask( $oldMask );
315
316 return Status::newGood();
317 }
318
319 /**
320 * @return Status
321 */
322 public function createTables() {
323 $status = parent::createTables();
324 return $this->setupSearchIndex( $status );
325 }
326
327 /**
328 * @param Status &$status
329 * @return Status
330 */
331 public function setupSearchIndex( &$status ) {
332 global $IP;
333
334 $module = DatabaseSqlite::getFulltextSearchModule();
335 $searchIndexSql = (string)$this->db->newSelectQueryBuilder()
336 ->select( 'sql' )
337 ->from( 'sqlite_master' )
338 ->where( [ 'tbl_name' => $this->db->tableName( 'searchindex', 'raw' ) ] )
339 ->caller( __METHOD__ )->fetchField();
340 $fts3tTable = ( stristr( $searchIndexSql, 'fts' ) !== false );
341
342 if ( $fts3tTable && !$module ) {
343 $status->warning( 'config-sqlite-fts3-downgrade' );
344 $this->db->sourceFile( "$IP/maintenance/sqlite/archives/searchindex-no-fts.sql" );
345 } elseif ( !$fts3tTable && $module == 'FTS3' ) {
346 $this->db->sourceFile( "$IP/maintenance/sqlite/archives/searchindex-fts3.sql" );
347 }
348
349 return $status;
350 }
351
352 /**
353 * @return string
354 */
355 public function getLocalSettings() {
356 $dir = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgSQLiteDataDir' ) );
357 // These tables have frequent writes and are thus split off from the main one.
358 // Since the code using these tables only uses transactions for writes, then set
359 // them to using BEGIN IMMEDIATE. This avoids frequent lock errors on the first write action.
360 return "# SQLite-specific settings
361 \$wgSQLiteDataDir = \"{$dir}\";
362 \$wgObjectCaches[CACHE_DB] = [
363 'class' => SqlBagOStuff::class,
364 'loggroup' => 'SQLBagOStuff',
365 'server' => [
366 'type' => 'sqlite',
367 'dbname' => 'wikicache',
368 'tablePrefix' => '',
369 'variables' => [ 'synchronous' => 'NORMAL' ],
370 'dbDirectory' => \$wgSQLiteDataDir,
371 'trxMode' => 'IMMEDIATE',
372 'flags' => 0
373 ]
374 ];
375 \$wgLocalisationCacheConf['storeServer'] = [
376 'type' => 'sqlite',
377 'dbname' => \"{\$wgDBname}_l10n_cache\",
378 'tablePrefix' => '',
379 'variables' => [ 'synchronous' => 'NORMAL' ],
380 'dbDirectory' => \$wgSQLiteDataDir,
381 'trxMode' => 'IMMEDIATE',
382 'flags' => 0
383 ];
384 \$wgJobTypeConf['default'] = [
385 'class' => 'JobQueueDB',
386 'claimTTL' => 3600,
387 'server' => [
388 'type' => 'sqlite',
389 'dbname' => \"{\$wgDBname}_jobqueue\",
390 'tablePrefix' => '',
391 'variables' => [ 'synchronous' => 'NORMAL' ],
392 'dbDirectory' => \$wgSQLiteDataDir,
393 'trxMode' => 'IMMEDIATE',
394 'flags' => 0
395 ]
396 ];
397 \$wgResourceLoaderUseObjectCacheForDeps = true;";
398 }
399 }