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