394337411d55454889aa4bd8c71d7f7e9a318bec
[lhc/web/wiklou.git] / includes / installer / SqliteInstaller.php
1 <?php
2 /**
3 * Sqlite-specific installer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Deployment
22 */
23
24 use Wikimedia\Rdbms\Database;
25 use Wikimedia\Rdbms\DatabaseSqlite;
26 use Wikimedia\Rdbms\DBConnectionError;
27
28 /**
29 * Class for setting up the MediaWiki database using SQLLite.
30 *
31 * @ingroup Deployment
32 * @since 1.17
33 */
34 class SqliteInstaller extends DatabaseInstaller {
35 const MINIMUM_VERSION = '3.3.7';
36
37 /**
38 * @var DatabaseSqlite
39 */
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
55 /**
56 *
57 * @return Status
58 */
59 public function checkPrerequisites() {
60 $result = Status::newGood();
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
102 /**
103 * Safe wrapper for PHP's realpath() that fails gracefully if it's unable to canonicalize the path.
104 *
105 * @param string $path
106 *
107 * @return string
108 */
109 private static function realpath( $path ) {
110 $result = realpath( $path );
111 if ( !$result ) {
112 return $path;
113 }
114
115 return $result;
116 }
117
118 /**
119 * @return Status
120 */
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
138 /**
139 * @param string $dir
140 * @param bool $create
141 * @return Status
142 */
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
182 /**
183 * @return Status
184 */
185 public function openConnection() {
186 $status = Status::newGood();
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
200 /**
201 * @return bool
202 */
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
215 /**
216 * @return Status
217 */
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
231 $status = Status::newGood();
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
268 /**
269 * @param $dir
270 * @param $db
271 * @return Status
272 */
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
288 /**
289 * @return Status
290 */
291 public function createTables() {
292 $status = parent::createTables();
293
294 return $this->setupSearchIndex( $status );
295 }
296
297 /**
298 * @param Status $status
299 * @return Status
300 */
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
316 /**
317 * @return string
318 */
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 }