Merge "Special:Newpages feed now shows first revision instead of latest revision"
[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
36 public $minimumVersion = '3.3.7';
37
38 /**
39 * @var DatabaseSqlite
40 */
41 public $db;
42
43 protected $globalNames = [
44 'wgDBname',
45 'wgSQLiteDataDir',
46 ];
47
48 public function getName() {
49 return 'sqlite';
50 }
51
52 public function isCompiled() {
53 return self::checkExtension( 'pdo_sqlite' );
54 }
55
56 /**
57 *
58 * @return Status
59 */
60 public function checkPrerequisites() {
61 $result = Status::newGood();
62 // Bail out if SQLite is too old
63 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
64 if ( version_compare( $db->getServerVersion(), $this->minimumVersion, '<' ) ) {
65 $result->fatal( 'config-outdated-sqlite', $db->getServerVersion(), $this->minimumVersion );
66 }
67 // Check for FTS3 full-text search module
68 if ( DatabaseSqlite::getFulltextSearchModule() != 'FTS3' ) {
69 $result->warning( 'config-no-fts3' );
70 }
71
72 return $result;
73 }
74
75 public function getGlobalDefaults() {
76 $defaults = parent::getGlobalDefaults();
77 if ( isset( $_SERVER['DOCUMENT_ROOT'] ) ) {
78 $path = str_replace(
79 [ '/', '\\' ],
80 DIRECTORY_SEPARATOR,
81 dirname( $_SERVER['DOCUMENT_ROOT'] ) . '/data'
82 );
83
84 $defaults['wgSQLiteDataDir'] = $path;
85 }
86 return $defaults;
87 }
88
89 public function getConnectForm() {
90 return $this->getTextBox(
91 'wgSQLiteDataDir',
92 'config-sqlite-dir', [],
93 $this->parent->getHelpBox( 'config-sqlite-dir-help' )
94 ) .
95 $this->getTextBox(
96 'wgDBname',
97 'config-db-name',
98 [],
99 $this->parent->getHelpBox( 'config-sqlite-name-help' )
100 );
101 }
102
103 /**
104 * Safe wrapper for PHP's realpath() that fails gracefully if it's unable to canonicalize the path.
105 *
106 * @param string $path
107 *
108 * @return string
109 */
110 private static function realpath( $path ) {
111 $result = realpath( $path );
112 if ( !$result ) {
113 return $path;
114 }
115
116 return $result;
117 }
118
119 /**
120 * @return Status
121 */
122 public function submitConnectForm() {
123 $this->setVarsFromRequest( [ 'wgSQLiteDataDir', 'wgDBname' ] );
124
125 # Try realpath() if the directory already exists
126 $dir = self::realpath( $this->getVar( 'wgSQLiteDataDir' ) );
127 $result = self::dataDirOKmaybeCreate( $dir, true /* create? */ );
128 if ( $result->isOK() ) {
129 # Try expanding again in case we've just created it
130 $dir = self::realpath( $dir );
131 $this->setVar( 'wgSQLiteDataDir', $dir );
132 }
133 # Table prefix is not used on SQLite, keep it empty
134 $this->setVar( 'wgDBprefix', '' );
135
136 return $result;
137 }
138
139 /**
140 * @param string $dir
141 * @param bool $create
142 * @return Status
143 */
144 private static function dataDirOKmaybeCreate( $dir, $create = false ) {
145 if ( !is_dir( $dir ) ) {
146 if ( !is_writable( dirname( $dir ) ) ) {
147 $webserverGroup = Installer::maybeGetWebserverPrimaryGroup();
148 if ( $webserverGroup !== null ) {
149 return Status::newFatal(
150 'config-sqlite-parent-unwritable-group',
151 $dir, dirname( $dir ), basename( $dir ),
152 $webserverGroup
153 );
154 } else {
155 return Status::newFatal(
156 'config-sqlite-parent-unwritable-nogroup',
157 $dir, dirname( $dir ), basename( $dir )
158 );
159 }
160 }
161
162 # Called early on in the installer, later we just want to sanity check
163 # if it's still writable
164 if ( $create ) {
165 MediaWiki\suppressWarnings();
166 $ok = wfMkdirParents( $dir, 0700, __METHOD__ );
167 MediaWiki\restoreWarnings();
168 if ( !$ok ) {
169 return Status::newFatal( 'config-sqlite-mkdir-error', $dir );
170 }
171 # Put a .htaccess file in in case the user didn't take our advice
172 file_put_contents( "$dir/.htaccess", "Deny from all\n" );
173 }
174 }
175 if ( !is_writable( $dir ) ) {
176 return Status::newFatal( 'config-sqlite-dir-unwritable', $dir );
177 }
178
179 # We haven't blown up yet, fall through
180 return Status::newGood();
181 }
182
183 /**
184 * @return Status
185 */
186 public function openConnection() {
187 $status = Status::newGood();
188 $dir = $this->getVar( 'wgSQLiteDataDir' );
189 $dbName = $this->getVar( 'wgDBname' );
190 try {
191 # @todo FIXME: Need more sensible constructor parameters, e.g. single associative array
192 $db = Database::factory( 'sqlite', [ 'dbname' => $dbName, 'dbDirectory' => $dir ] );
193 $status->value = $db;
194 } catch ( DBConnectionError $e ) {
195 $status->fatal( 'config-sqlite-connection-error', $e->getMessage() );
196 }
197
198 return $status;
199 }
200
201 /**
202 * @return bool
203 */
204 public function needsUpgrade() {
205 $dir = $this->getVar( 'wgSQLiteDataDir' );
206 $dbName = $this->getVar( 'wgDBname' );
207 // Don't create the data file yet
208 if ( !file_exists( DatabaseSqlite::generateFileName( $dir, $dbName ) ) ) {
209 return false;
210 }
211
212 // If the data file exists, look inside it
213 return parent::needsUpgrade();
214 }
215
216 /**
217 * @return Status
218 */
219 public function setupDatabase() {
220 $dir = $this->getVar( 'wgSQLiteDataDir' );
221
222 # Sanity check. We checked this before but maybe someone deleted the
223 # data dir between then and now
224 $dir_status = self::dataDirOKmaybeCreate( $dir, false /* create? */ );
225 if ( !$dir_status->isOK() ) {
226 return $dir_status;
227 }
228
229 $db = $this->getVar( 'wgDBname' );
230
231 # Make the main and cache stub DB files
232 $status = Status::newGood();
233 $status->merge( $this->makeStubDBFile( $dir, $db ) );
234 $status->merge( $this->makeStubDBFile( $dir, "wikicache" ) );
235 if ( !$status->isOK() ) {
236 return $status;
237 }
238
239 # Nuke the unused settings for clarity
240 $this->setVar( 'wgDBserver', '' );
241 $this->setVar( 'wgDBuser', '' );
242 $this->setVar( 'wgDBpassword', '' );
243 $this->setupSchemaVars();
244
245 # Create the global cache DB
246 try {
247 $conn = Database::factory( 'sqlite', [ 'dbname' => 'wikicache', 'dbDirectory' => $dir ] );
248 # @todo: don't duplicate objectcache definition, though it's very simple
249 $sql =
250 <<<EOT
251 CREATE TABLE IF NOT EXISTS objectcache (
252 keyname BLOB NOT NULL default '' PRIMARY KEY,
253 value BLOB,
254 exptime TEXT
255 )
256 EOT;
257 $conn->query( $sql );
258 $conn->query( "CREATE INDEX IF NOT EXISTS exptime ON objectcache (exptime)" );
259 $conn->query( "PRAGMA journal_mode=WAL" ); // this is permanent
260 $conn->close();
261 } catch ( DBConnectionError $e ) {
262 return Status::newFatal( 'config-sqlite-connection-error', $e->getMessage() );
263 }
264
265 # Open the main DB
266 return $this->getConnection();
267 }
268
269 /**
270 * @param string $dir
271 * @param string $db
272 * @return Status
273 */
274 protected function makeStubDBFile( $dir, $db ) {
275 $file = DatabaseSqlite::generateFileName( $dir, $db );
276 if ( file_exists( $file ) ) {
277 if ( !is_writable( $file ) ) {
278 return Status::newFatal( 'config-sqlite-readonly', $file );
279 }
280 } else {
281 if ( file_put_contents( $file, '' ) === false ) {
282 return Status::newFatal( 'config-sqlite-cant-create-db', $file );
283 }
284 }
285
286 return Status::newGood();
287 }
288
289 /**
290 * @return Status
291 */
292 public function createTables() {
293 $status = parent::createTables();
294
295 return $this->setupSearchIndex( $status );
296 }
297
298 /**
299 * @param Status &$status
300 * @return Status
301 */
302 public function setupSearchIndex( &$status ) {
303 global $IP;
304
305 $module = DatabaseSqlite::getFulltextSearchModule();
306 $fts3tTable = $this->db->checkForEnabledSearch();
307 if ( $fts3tTable && !$module ) {
308 $status->warning( 'config-sqlite-fts3-downgrade' );
309 $this->db->sourceFile( "$IP/maintenance/sqlite/archives/searchindex-no-fts.sql" );
310 } elseif ( !$fts3tTable && $module == 'FTS3' ) {
311 $this->db->sourceFile( "$IP/maintenance/sqlite/archives/searchindex-fts3.sql" );
312 }
313
314 return $status;
315 }
316
317 /**
318 * @return string
319 */
320 public function getLocalSettings() {
321 $dir = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgSQLiteDataDir' ) );
322
323 return "# SQLite-specific settings
324 \$wgSQLiteDataDir = \"{$dir}\";
325 \$wgObjectCaches[CACHE_DB] = [
326 'class' => 'SqlBagOStuff',
327 'loggroup' => 'SQLBagOStuff',
328 'server' => [
329 'type' => 'sqlite',
330 'dbname' => 'wikicache',
331 'tablePrefix' => '',
332 'dbDirectory' => \$wgSQLiteDataDir,
333 'flags' => 0
334 ]
335 ];";
336 }
337 }