Refactor diffs
[mediawiki.git] / includes / installer / DatabaseInstaller.php
blob0110ac52f6e727e66e745e75db4cc3712303f3fe
1 <?php
2 /**
3 * DBMS-specific installation helper.
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.
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.
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
20 * @file
21 * @ingroup Deployment
24 /**
25 * Base class for DBMS-specific installation helper classes.
27 * @ingroup Deployment
28 * @since 1.17
30 abstract class DatabaseInstaller {
32 /**
33 * The Installer object.
35 * @todo Naming this parent is confusing, 'installer' would be clearer.
37 * @var WebInstaller
39 public $parent;
41 /**
42 * The database connection.
44 * @var DatabaseBase
46 public $db = null;
48 /**
49 * Internal variables for installation.
51 * @var array
53 protected $internalDefaults = array();
55 /**
56 * Array of MW configuration globals this class uses.
58 * @var array
60 protected $globalNames = array();
62 /**
63 * Return the internal name, e.g. 'mysql', or 'sqlite'.
65 abstract public function getName();
67 /**
68 * @return bool Returns true if the client library is compiled in.
70 abstract public function isCompiled();
72 /**
73 * Checks for installation prerequisites other than those checked by isCompiled()
74 * @since 1.19
75 * @return Status
77 public function checkPrerequisites() {
78 return Status::newGood();
81 /**
82 * Get HTML for a web form that configures this database. Configuration
83 * at this time should be the minimum needed to connect and test
84 * whether install or upgrade is required.
86 * If this is called, $this->parent can be assumed to be a WebInstaller.
88 abstract public function getConnectForm();
90 /**
91 * Set variables based on the request array, assuming it was submitted
92 * via the form returned by getConnectForm(). Validate the connection
93 * settings by attempting to connect with them.
95 * If this is called, $this->parent can be assumed to be a WebInstaller.
97 * @return Status
99 abstract public function submitConnectForm();
102 * Get HTML for a web form that retrieves settings used for installation.
103 * $this->parent can be assumed to be a WebInstaller.
104 * If the DB type has no settings beyond those already configured with
105 * getConnectForm(), this should return false.
106 * @return bool
108 public function getSettingsForm() {
109 return false;
113 * Set variables based on the request array, assuming it was submitted via
114 * the form return by getSettingsForm().
116 * @return Status
118 public function submitSettingsForm() {
119 return Status::newGood();
123 * Open a connection to the database using the administrative user/password
124 * currently defined in the session, without any caching. Returns a status
125 * object. On success, the status object will contain a Database object in
126 * its value member.
128 * @return Status
130 abstract public function openConnection();
133 * Create the database and return a Status object indicating success or
134 * failure.
136 * @return Status
138 abstract public function setupDatabase();
141 * Connect to the database using the administrative user/password currently
142 * defined in the session. Returns a status object. On success, the status
143 * object will contain a Database object in its value member.
145 * This will return a cached connection if one is available.
147 * @return Status
149 public function getConnection() {
150 if ( $this->db ) {
151 return Status::newGood( $this->db );
154 $status = $this->openConnection();
155 if ( $status->isOK() ) {
156 $this->db = $status->value;
157 // Enable autocommit
158 $this->db->clearFlag( DBO_TRX );
159 $this->db->commit( __METHOD__ );
162 return $status;
166 * Create database tables from scratch.
168 * @return Status
170 public function createTables() {
171 $status = $this->getConnection();
172 if ( !$status->isOK() ) {
173 return $status;
175 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
177 if ( $this->db->tableExists( 'archive', __METHOD__ ) ) {
178 $status->warning( 'config-install-tables-exist' );
179 $this->enableLB();
181 return $status;
184 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
185 $this->db->begin( __METHOD__ );
187 $error = $this->db->sourceFile( $this->db->getSchemaPath() );
188 if ( $error !== true ) {
189 $this->db->reportQueryError( $error, 0, '', __METHOD__ );
190 $this->db->rollback( __METHOD__ );
191 $status->fatal( 'config-install-tables-failed', $error );
192 } else {
193 $this->db->commit( __METHOD__ );
195 // Resume normal operations
196 if ( $status->isOk() ) {
197 $this->enableLB();
200 return $status;
204 * Create the tables for each extension the user enabled
205 * @return Status
207 public function createExtensionTables() {
208 $status = $this->getConnection();
209 if ( !$status->isOK() ) {
210 return $status;
213 // Now run updates to create tables for old extensions
214 DatabaseUpdater::newForDB( $this->db )->doUpdates( array( 'extensions' ) );
216 return $status;
220 * Get the DBMS-specific options for LocalSettings.php generation.
222 * @return String
224 abstract public function getLocalSettings();
227 * Override this to provide DBMS-specific schema variables, to be
228 * substituted into tables.sql and other schema files.
229 * @return array
231 public function getSchemaVars() {
232 return array();
236 * Set appropriate schema variables in the current database connection.
238 * This should be called after any request data has been imported, but before
239 * any write operations to the database.
241 public function setupSchemaVars() {
242 $status = $this->getConnection();
243 if ( $status->isOK() ) {
244 $status->value->setSchemaVars( $this->getSchemaVars() );
245 } else {
246 throw new MWException( __METHOD__ . ': unexpected DB connection error' );
251 * Set up LBFactory so that wfGetDB() etc. works.
252 * We set up a special LBFactory instance which returns the current
253 * installer connection.
255 public function enableLB() {
256 $status = $this->getConnection();
257 if ( !$status->isOK() ) {
258 throw new MWException( __METHOD__ . ': unexpected DB connection error' );
260 LBFactory::setInstance( new LBFactory_Single( array(
261 'connection' => $status->value ) ) );
265 * Perform database upgrades
267 * @return Boolean
269 public function doUpgrade() {
270 $this->setupSchemaVars();
271 $this->enableLB();
273 $ret = true;
274 ob_start( array( $this, 'outputHandler' ) );
275 $up = DatabaseUpdater::newForDB( $this->db );
276 try {
277 $up->doUpdates();
278 } catch ( MWException $e ) {
279 echo "\nAn error occurred:\n";
280 echo $e->getText();
281 $ret = false;
283 $up->purgeCache();
284 ob_end_flush();
286 return $ret;
290 * Allow DB installers a chance to make last-minute changes before installation
291 * occurs. This happens before setupDatabase() or createTables() is called, but
292 * long after the constructor. Helpful for things like modifying setup steps :)
294 public function preInstall() {
298 * Allow DB installers a chance to make checks before upgrade.
300 public function preUpgrade() {
304 * Get an array of MW configuration globals that will be configured by this class.
305 * @return array
307 public function getGlobalNames() {
308 return $this->globalNames;
312 * Construct and initialise parent.
313 * This is typically only called from Installer::getDBInstaller()
314 * @param $parent
316 public function __construct( $parent ) {
317 $this->parent = $parent;
321 * Convenience function.
322 * Check if a named extension is present.
324 * @param $name
325 * @return bool
327 protected static function checkExtension( $name ) {
328 return extension_loaded( $name );
332 * Get the internationalised name for this DBMS.
333 * @return String
335 public function getReadableName() {
336 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
337 // config-type-oracle
338 return wfMessage( 'config-type-' . $this->getName() )->text();
342 * Get a name=>value map of MW configuration globals that overrides.
343 * DefaultSettings.php
344 * @return array
346 public function getGlobalDefaults() {
347 return array();
351 * Get a name=>value map of internal variables used during installation.
352 * @return array
354 public function getInternalDefaults() {
355 return $this->internalDefaults;
359 * Get a variable, taking local defaults into account.
360 * @param $var string
361 * @param $default null
362 * @return mixed
364 public function getVar( $var, $default = null ) {
365 $defaults = $this->getGlobalDefaults();
366 $internal = $this->getInternalDefaults();
367 if ( isset( $defaults[$var] ) ) {
368 $default = $defaults[$var];
369 } elseif ( isset( $internal[$var] ) ) {
370 $default = $internal[$var];
373 return $this->parent->getVar( $var, $default );
377 * Convenience alias for $this->parent->setVar()
378 * @param $name string
379 * @param $value mixed
381 public function setVar( $name, $value ) {
382 $this->parent->setVar( $name, $value );
386 * Get a labelled text box to configure a local variable.
388 * @param $var string
389 * @param $label string
390 * @param $attribs array
391 * @param $helpData string
392 * @return string
394 public function getTextBox( $var, $label, $attribs = array(), $helpData = "" ) {
395 $name = $this->getName() . '_' . $var;
396 $value = $this->getVar( $var );
397 if ( !isset( $attribs ) ) {
398 $attribs = array();
401 return $this->parent->getTextBox( array(
402 'var' => $var,
403 'label' => $label,
404 'attribs' => $attribs,
405 'controlName' => $name,
406 'value' => $value,
407 'help' => $helpData
408 ) );
412 * Get a labelled password box to configure a local variable.
413 * Implements password hiding.
415 * @param $var string
416 * @param $label string
417 * @param $attribs array
418 * @param $helpData string
419 * @return string
421 public function getPasswordBox( $var, $label, $attribs = array(), $helpData = "" ) {
422 $name = $this->getName() . '_' . $var;
423 $value = $this->getVar( $var );
424 if ( !isset( $attribs ) ) {
425 $attribs = array();
428 return $this->parent->getPasswordBox( array(
429 'var' => $var,
430 'label' => $label,
431 'attribs' => $attribs,
432 'controlName' => $name,
433 'value' => $value,
434 'help' => $helpData
435 ) );
439 * Get a labelled checkbox to configure a local boolean variable.
441 * @return string
443 public function getCheckBox( $var, $label, $attribs = array(), $helpData = "" ) {
444 $name = $this->getName() . '_' . $var;
445 $value = $this->getVar( $var );
447 return $this->parent->getCheckBox( array(
448 'var' => $var,
449 'label' => $label,
450 'attribs' => $attribs,
451 'controlName' => $name,
452 'value' => $value,
453 'help' => $helpData
454 ) );
458 * Get a set of labelled radio buttons.
460 * @param $params Array:
461 * Parameters are:
462 * var: The variable to be configured (required)
463 * label: The message name for the label (required)
464 * itemLabelPrefix: The message name prefix for the item labels (required)
465 * values: List of allowed values (required)
466 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
468 * @return string
470 public function getRadioSet( $params ) {
471 $params['controlName'] = $this->getName() . '_' . $params['var'];
472 $params['value'] = $this->getVar( $params['var'] );
474 return $this->parent->getRadioSet( $params );
478 * Convenience function to set variables based on form data.
479 * Assumes that variables containing "password" in the name are (potentially
480 * fake) passwords.
481 * @param $varNames Array
482 * @return array
484 public function setVarsFromRequest( $varNames ) {
485 return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
489 * Determine whether an existing installation of MediaWiki is present in
490 * the configured administrative connection. Returns true if there is
491 * such a wiki, false if the database doesn't exist.
493 * Traditionally, this is done by testing for the existence of either
494 * the revision table or the cur table.
496 * @return Boolean
498 public function needsUpgrade() {
499 $status = $this->getConnection();
500 if ( !$status->isOK() ) {
501 return false;
504 if ( !$this->db->selectDB( $this->getVar( 'wgDBname' ) ) ) {
505 return false;
508 return $this->db->tableExists( 'cur', __METHOD__ ) ||
509 $this->db->tableExists( 'revision', __METHOD__ );
513 * Get a standard install-user fieldset.
515 * @return String
517 public function getInstallUserBox() {
518 return Html::openElement( 'fieldset' ) .
519 Html::element( 'legend', array(), wfMessage( 'config-db-install-account' )->text() ) .
520 $this->getTextBox(
521 '_InstallUser',
522 'config-db-username',
523 array( 'dir' => 'ltr' ),
524 $this->parent->getHelpBox( 'config-db-install-username' )
526 $this->getPasswordBox(
527 '_InstallPassword',
528 'config-db-password',
529 array( 'dir' => 'ltr' ),
530 $this->parent->getHelpBox( 'config-db-install-password' )
532 Html::closeElement( 'fieldset' );
536 * Submit a standard install user fieldset.
537 * @return Status
539 public function submitInstallUserBox() {
540 $this->setVarsFromRequest( array( '_InstallUser', '_InstallPassword' ) );
542 return Status::newGood();
546 * Get a standard web-user fieldset
547 * @param string $noCreateMsg Message to display instead of the creation checkbox.
548 * Set this to false to show a creation checkbox.
550 * @return String
552 public function getWebUserBox( $noCreateMsg = false ) {
553 $wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
554 $s = Html::openElement( 'fieldset' ) .
555 Html::element( 'legend', array(), wfMessage( 'config-db-web-account' )->text() ) .
556 $this->getCheckBox(
557 '_SameAccount', 'config-db-web-account-same',
558 array( 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' )
560 Html::openElement( 'div', array( 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ) ) .
561 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
562 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
563 $this->parent->getHelpBox( 'config-db-web-help' );
564 if ( $noCreateMsg ) {
565 $s .= $this->parent->getWarningBox( wfMessage( $noCreateMsg )->plain() );
566 } else {
567 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
569 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
571 return $s;
575 * Submit the form from getWebUserBox().
577 * @return Status
579 public function submitWebUserBox() {
580 $this->setVarsFromRequest(
581 array( 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' )
584 if ( $this->getVar( '_SameAccount' ) ) {
585 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
586 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
589 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
590 return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
593 return Status::newGood();
597 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
599 * @return Status
601 public function populateInterwikiTable() {
602 $status = $this->getConnection();
603 if ( !$status->isOK() ) {
604 return $status;
606 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
608 if ( $this->db->selectRow( 'interwiki', '*', array(), __METHOD__ ) ) {
609 $status->warning( 'config-install-interwiki-exists' );
611 return $status;
613 global $IP;
614 wfSuppressWarnings();
615 $rows = file( "$IP/maintenance/interwiki.list",
616 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
617 wfRestoreWarnings();
618 $interwikis = array();
619 if ( !$rows ) {
620 return Status::newFatal( 'config-install-interwiki-list' );
622 foreach ( $rows as $row ) {
623 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
624 if ( $row == "" ) {
625 continue;
627 $row .= "||";
628 $interwikis[] = array_combine(
629 array( 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ),
630 explode( '|', $row )
633 $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
635 return Status::newGood();
638 public function outputHandler( $string ) {
639 return htmlspecialchars( $string );