d8e24421e225cf000ed2a4cda12a54c34f9a95d0
[lhc/web/wiklou.git] / includes / installer / DatabaseInstaller.php
1 <?php
2 /**
3 * DBMS-specific installation helper.
4 *
5 * @file
6 * @ingroup Deployment
7 */
8
9 /**
10 * Base class for DBMS-specific installation helper classes.
11 *
12 * @ingroup Deployment
13 * @since 1.17
14 */
15 abstract class DatabaseInstaller {
16
17 /**
18 * The Installer object.
19 *
20 * TODO: naming this parent is confusing, 'installer' would be clearer.
21 *
22 * @var WebInstaller
23 */
24 public $parent;
25
26 /**
27 * The database connection.
28 *
29 * @var DatabaseBase
30 */
31 public $db = null;
32
33 /**
34 * Internal variables for installation.
35 *
36 * @var array
37 */
38 protected $internalDefaults = array();
39
40 /**
41 * Array of MW configuration globals this class uses.
42 *
43 * @var array
44 */
45 protected $globalNames = array();
46
47 /**
48 * Return the internal name, e.g. 'mysql', or 'sqlite'.
49 */
50 public abstract function getName();
51
52 /**
53 * @return true if the client library is compiled in.
54 */
55 public abstract function isCompiled();
56
57 /**
58 * Get HTML for a web form that configures this database. Configuration
59 * at this time should be the minimum needed to connect and test
60 * whether install or upgrade is required.
61 *
62 * If this is called, $this->parent can be assumed to be a WebInstaller.
63 */
64 public abstract function getConnectForm();
65
66 /**
67 * Set variables based on the request array, assuming it was submitted
68 * via the form returned by getConnectForm(). Validate the connection
69 * settings by attempting to connect with them.
70 *
71 * If this is called, $this->parent can be assumed to be a WebInstaller.
72 *
73 * @return Status
74 */
75 public abstract function submitConnectForm();
76
77 /**
78 * Get HTML for a web form that retrieves settings used for installation.
79 * $this->parent can be assumed to be a WebInstaller.
80 * If the DB type has no settings beyond those already configured with
81 * getConnectForm(), this should return false.
82 */
83 public function getSettingsForm() {
84 return false;
85 }
86
87 /**
88 * Set variables based on the request array, assuming it was submitted via
89 * the form return by getSettingsForm().
90 *
91 * @return Status
92 */
93 public function submitSettingsForm() {
94 return Status::newGood();
95 }
96
97 /**
98 * Open a connection to the database using the administrative user/password
99 * currently defined in the session, without any caching. Returns a status
100 * object. On success, the status object will contain a Database object in
101 * its value member.
102 *
103 * @return Status
104 */
105 public abstract function openConnection( $dbName = null );
106
107 /**
108 * Create the database and return a Status object indicating success or
109 * failure.
110 *
111 * @return Status
112 */
113 public abstract function setupDatabase();
114
115 /**
116 * Connect to the database using the administrative user/password currently
117 * defined in the session. Returns a status object. On success, the status
118 * object will contain a Database object in its value member.
119 *
120 * This will return a cached connection if one is available.
121 *
122 * @return Status
123 */
124 public function getConnection( $dbName = null ) {
125 if ( isset($this->db) && $this->db ) { /* Weirdly get E_STRICT
126 * errors without the
127 * isset */
128 return Status::newGood( $this->db );
129 }
130
131 $status = $this->openConnection( $dbName );
132 if ( $status->isOK() ) {
133 $this->db = $status->value;
134 // Enable autocommit
135 $this->db->clearFlag( DBO_TRX );
136 $this->db->commit();
137 }
138 return $status;
139 }
140
141 /**
142 * Create database tables from scratch.
143 *
144 * @return Status
145 */
146 public function createTables() {
147 $status = $this->getConnection();
148 if ( !$status->isOK() ) {
149 return $status;
150 }
151 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
152
153 if( $this->db->tableExists( 'user' ) ) {
154 $status->warning( 'config-install-tables-exist' );
155 $this->enableLB();
156 return $status;
157 }
158
159 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
160 $this->db->begin( __METHOD__ );
161
162 $error = $this->db->sourceFile( $this->db->getSchema() );
163 if( $error !== true ) {
164 $this->db->reportQueryError( $error, 0, '', __METHOD__ );
165 $this->db->rollback( __METHOD__ );
166 $status->fatal( 'config-install-tables-failed', $error );
167 } else {
168 $this->db->commit( __METHOD__ );
169 }
170 // Resume normal operations
171 if( $status->isOk() ) {
172 $this->enableLB();
173 }
174 return $status;
175 }
176
177 /**
178 * Create the tables for each extension the user enabled
179 * @return Status
180 */
181 public function createExtensionTables() {
182 $status = $this->getConnection();
183 if ( !$status->isOK() ) {
184 return $status;
185 }
186 $updater = DatabaseUpdater::newForDB( $this->db );
187 $extensionUpdates = $updater->getNewExtensions();
188
189 $ourExtensions = array_map( 'strtolower', $this->getVar( '_Extensions' ) );
190
191 foreach( $ourExtensions as $ext ) {
192 if( isset( $extensionUpdates[$ext] ) ) {
193 $this->db->begin( __METHOD__ );
194 $error = $this->db->sourceFile( $extensionUpdates[$ext] );
195 if( $error !== true ) {
196 $this->db->rollback( __METHOD__ );
197 $status->warning( 'config-install-tables-failed', $error );
198 } else {
199 $this->db->commit( __METHOD__ );
200 }
201 }
202 }
203
204 // Now run updates to create tables for old extensions
205 $updater->doUpdates( array( 'extensions' ) );
206
207 return $status;
208 }
209
210 /**
211 * Get the DBMS-specific options for LocalSettings.php generation.
212 *
213 * @return String
214 */
215 public abstract function getLocalSettings();
216
217 /**
218 * Override this to provide DBMS-specific schema variables, to be
219 * substituted into tables.sql and other schema files.
220 */
221 public function getSchemaVars() {
222 return array();
223 }
224
225 /**
226 * Set appropriate schema variables in the current database connection.
227 *
228 * This should be called after any request data has been imported, but before
229 * any write operations to the database.
230 */
231 public function setupSchemaVars() {
232 $status = $this->getConnection();
233 if ( $status->isOK() ) {
234 $status->value->setSchemaVars( $this->getSchemaVars() );
235 } else {
236 throw new MWException( __METHOD__.': unexpected DB connection error' );
237 }
238 }
239
240 /**
241 * Set up LBFactory so that wfGetDB() etc. works.
242 * We set up a special LBFactory instance which returns the current
243 * installer connection.
244 */
245 public function enableLB() {
246 $status = $this->getConnection();
247 if ( !$status->isOK() ) {
248 throw new MWException( __METHOD__.': unexpected DB connection error' );
249 }
250 LBFactory::setInstance( new LBFactory_Single( array(
251 'connection' => $status->value ) ) );
252 }
253
254 /**
255 * Perform database upgrades
256 *
257 * @return Boolean
258 */
259 public function doUpgrade() {
260 $this->setupSchemaVars();
261 $this->enableLB();
262
263 $ret = true;
264 ob_start( array( $this, 'outputHandler' ) );
265 try {
266 $up = DatabaseUpdater::newForDB( $this->db );
267 $up->doUpdates();
268 } catch ( MWException $e ) {
269 echo "\nAn error occured:\n";
270 echo $e->getText();
271 $ret = false;
272 }
273 ob_end_flush();
274 return $ret;
275 }
276
277 /**
278 * Allow DB installers a chance to make last-minute changes before installation
279 * occurs. This happens before setupDatabase() or createTables() is called, but
280 * long after the constructor. Helpful for things like modifying setup steps :)
281 */
282 public function preInstall() {
283
284 }
285
286 /**
287 * Allow DB installers a chance to make checks before upgrade.
288 */
289 public function preUpgrade() {
290
291 }
292
293 /**
294 * Get an array of MW configuration globals that will be configured by this class.
295 */
296 public function getGlobalNames() {
297 return $this->globalNames;
298 }
299
300 /**
301 * Construct and initialise parent.
302 * This is typically only called from Installer::getDBInstaller()
303 */
304 public function __construct( $parent ) {
305 $this->parent = $parent;
306 }
307
308 /**
309 * Convenience function.
310 * Check if a named extension is present.
311 *
312 * @see wfDl
313 */
314 protected static function checkExtension( $name ) {
315 wfSuppressWarnings();
316 $compiled = wfDl( $name );
317 wfRestoreWarnings();
318 return $compiled;
319 }
320
321 /**
322 * Get the internationalised name for this DBMS.
323 */
324 public function getReadableName() {
325 return wfMsg( 'config-type-' . $this->getName() );
326 }
327
328 /**
329 * Get a name=>value map of MW configuration globals that overrides.
330 * DefaultSettings.php
331 */
332 public function getGlobalDefaults() {
333 return array();
334 }
335
336 /**
337 * Get a name=>value map of internal variables used during installation.
338 */
339 public function getInternalDefaults() {
340 return $this->internalDefaults;
341 }
342
343 /**
344 * Get a variable, taking local defaults into account.
345 */
346 public function getVar( $var, $default = null ) {
347 $defaults = $this->getGlobalDefaults();
348 $internal = $this->getInternalDefaults();
349 if ( isset( $defaults[$var] ) ) {
350 $default = $defaults[$var];
351 } elseif ( isset( $internal[$var] ) ) {
352 $default = $internal[$var];
353 }
354 return $this->parent->getVar( $var, $default );
355 }
356
357 /**
358 * Convenience alias for $this->parent->setVar()
359 */
360 public function setVar( $name, $value ) {
361 $this->parent->setVar( $name, $value );
362 }
363
364 /**
365 * Get a labelled text box to configure a local variable.
366 *
367 * @return string
368 */
369 public function getTextBox( $var, $label, $attribs = array(), $helpData = "" ) {
370 $name = $this->getName() . '_' . $var;
371 $value = $this->getVar( $var );
372 if ( !isset( $attribs ) ) {
373 $attribs = array();
374 }
375 return $this->parent->getTextBox( array(
376 'var' => $var,
377 'label' => $label,
378 'attribs' => $attribs,
379 'controlName' => $name,
380 'value' => $value,
381 'help' => $helpData
382 ) );
383 }
384
385 /**
386 * Get a labelled password box to configure a local variable.
387 * Implements password hiding.
388 *
389 * @return string
390 */
391 public function getPasswordBox( $var, $label, $attribs = array(), $helpData = "" ) {
392 $name = $this->getName() . '_' . $var;
393 $value = $this->getVar( $var );
394 if ( !isset( $attribs ) ) {
395 $attribs = array();
396 }
397 return $this->parent->getPasswordBox( array(
398 'var' => $var,
399 'label' => $label,
400 'attribs' => $attribs,
401 'controlName' => $name,
402 'value' => $value,
403 'help' => $helpData
404 ) );
405 }
406
407 /**
408 * Get a labelled checkbox to configure a local boolean variable.
409 *
410 * @return string
411 */
412 public function getCheckBox( $var, $label, $attribs = array(), $helpData = "" ) {
413 $name = $this->getName() . '_' . $var;
414 $value = $this->getVar( $var );
415 return $this->parent->getCheckBox( array(
416 'var' => $var,
417 'label' => $label,
418 'attribs' => $attribs,
419 'controlName' => $name,
420 'value' => $value,
421 'help' => $helpData
422 ));
423 }
424
425 /**
426 * Get a set of labelled radio buttons.
427 *
428 * @param $params Array:
429 * Parameters are:
430 * var: The variable to be configured (required)
431 * label: The message name for the label (required)
432 * itemLabelPrefix: The message name prefix for the item labels (required)
433 * values: List of allowed values (required)
434 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
435 *
436 */
437 public function getRadioSet( $params ) {
438 $params['controlName'] = $this->getName() . '_' . $params['var'];
439 $params['value'] = $this->getVar( $params['var'] );
440 return $this->parent->getRadioSet( $params );
441 }
442
443 /**
444 * Convenience function to set variables based on form data.
445 * Assumes that variables containing "password" in the name are (potentially
446 * fake) passwords.
447 * @param $varNames Array
448 */
449 public function setVarsFromRequest( $varNames ) {
450 return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
451 }
452
453 /**
454 * Determine whether an existing installation of MediaWiki is present in
455 * the configured administrative connection. Returns true if there is
456 * such a wiki, false if the database doesn't exist.
457 *
458 * Traditionally, this is done by testing for the existence of either
459 * the revision table or the cur table.
460 *
461 * @return Boolean
462 */
463 public function needsUpgrade() {
464 $status = $this->getConnection();
465 if ( !$status->isOK() ) {
466 return false;
467 }
468
469 if ( !$this->db->selectDB( $this->getVar( 'wgDBname' ) ) ) {
470 return false;
471 }
472 return $this->db->tableExists( 'cur' ) || $this->db->tableExists( 'revision' );
473 }
474
475 /**
476 * Get a standard install-user fieldset.
477 *
478 * @return String
479 */
480 public function getInstallUserBox() {
481 return
482 Html::openElement( 'fieldset' ) .
483 Html::element( 'legend', array(), wfMsg( 'config-db-install-account' ) ) .
484 $this->getTextBox( '_InstallUser', 'config-db-username', array(), $this->parent->getHelpBox( 'config-db-install-username' ) ) .
485 $this->getPasswordBox( '_InstallPassword', 'config-db-password', array(), $this->parent->getHelpBox( 'config-db-install-password' ) ) .
486 Html::closeElement( 'fieldset' );
487 }
488
489 /**
490 * Submit a standard install user fieldset.
491 */
492 public function submitInstallUserBox() {
493 $this->setVarsFromRequest( array( '_InstallUser', '_InstallPassword' ) );
494 return Status::newGood();
495 }
496
497 /**
498 * Get a standard web-user fieldset
499 * @param $noCreateMsg String: Message to display instead of the creation checkbox.
500 * Set this to false to show a creation checkbox.
501 *
502 * @return String
503 */
504 public function getWebUserBox( $noCreateMsg = false ) {
505 $wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
506 $s = Html::openElement( 'fieldset' ) .
507 Html::element( 'legend', array(), wfMsg( 'config-db-web-account' ) ) .
508 $this->getCheckBox(
509 '_SameAccount', 'config-db-web-account-same',
510 array( 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' )
511 ) .
512 Html::openElement( 'div', array( 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ) ) .
513 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
514 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
515 $this->parent->getHelpBox( 'config-db-web-help' );
516 if ( $noCreateMsg ) {
517 $s .= $this->parent->getWarningBox( wfMsgNoTrans( $noCreateMsg ) );
518 } else {
519 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
520 }
521 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
522 return $s;
523 }
524
525 /**
526 * Submit the form from getWebUserBox().
527 *
528 * @return Status
529 */
530 public function submitWebUserBox() {
531 $this->setVarsFromRequest(
532 array( 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' )
533 );
534
535 if ( $this->getVar( '_SameAccount' ) ) {
536 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
537 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
538 }
539
540 if( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
541 return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
542 }
543
544 return Status::newGood();
545 }
546
547 /**
548 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
549 *
550 * @return Status
551 */
552 public function populateInterwikiTable() {
553 $status = $this->getConnection();
554 if ( !$status->isOK() ) {
555 return $status;
556 }
557 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
558
559 if( $this->db->selectRow( 'interwiki', '*', array(), __METHOD__ ) ) {
560 $status->warning( 'config-install-interwiki-exists' );
561 return $status;
562 }
563 global $IP;
564 wfSuppressWarnings();
565 $rows = file( "$IP/maintenance/interwiki.list",
566 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
567 wfRestoreWarnings();
568 $interwikis = array();
569 if ( !$rows ) {
570 return Status::newFatal( 'config-install-interwiki-list' );
571 }
572 foreach( $rows as $row ) {
573 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
574 if ( $row == "" ) continue;
575 $row .= "||";
576 $interwikis[] = array_combine(
577 array( 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ),
578 explode( '|', $row )
579 );
580 }
581 $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
582 return Status::newGood();
583 }
584
585 public function outputHandler( $string ) {
586 return htmlspecialchars( $string );
587 }
588 }