62acebf3820efc7af0faa586f96dacf02fa10068
[lhc/web/wiklou.git] / includes / installer / DatabaseInstaller.php
1 <?php
2 /**
3 * DBMS-specific installation helper.
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 use Wikimedia\Rdbms\LBFactorySingle;
24 use Wikimedia\Rdbms\Database;
25 use Wikimedia\Rdbms\IDatabase;
26
27 /**
28 * Base class for DBMS-specific installation helper classes.
29 *
30 * @ingroup Deployment
31 * @since 1.17
32 */
33 abstract class DatabaseInstaller {
34
35 /**
36 * The Installer object.
37 *
38 * @todo Naming this parent is confusing, 'installer' would be clearer.
39 *
40 * @var WebInstaller
41 */
42 public $parent;
43
44 /**
45 * @var string Set by subclasses
46 */
47 public static $minimumVersion;
48
49 /**
50 * @var string Set by subclasses
51 */
52 protected static $notMiniumumVerisonMessage;
53
54 /**
55 * The database connection.
56 *
57 * @var Database
58 */
59 public $db = null;
60
61 /**
62 * Internal variables for installation.
63 *
64 * @var array
65 */
66 protected $internalDefaults = [];
67
68 /**
69 * Array of MW configuration globals this class uses.
70 *
71 * @var array
72 */
73 protected $globalNames = [];
74
75 /**
76 * Whether the provided version meets the necessary requirements for this type
77 *
78 * @param string $serverVersion Output of Database::getServerVersion()
79 * @return Status
80 * @since 1.30
81 */
82 public static function meetsMinimumRequirement( $serverVersion ) {
83 if ( version_compare( $serverVersion, static::$minimumVersion ) < 0 ) {
84 return Status::newFatal(
85 static::$notMiniumumVerisonMessage, static::$minimumVersion, $serverVersion
86 );
87 }
88
89 return Status::newGood();
90 }
91
92 /**
93 * Return the internal name, e.g. 'mysql', or 'sqlite'.
94 */
95 abstract public function getName();
96
97 /**
98 * @return bool Returns true if the client library is compiled in.
99 */
100 abstract public function isCompiled();
101
102 /**
103 * Checks for installation prerequisites other than those checked by isCompiled()
104 * @since 1.19
105 * @return Status
106 */
107 public function checkPrerequisites() {
108 return Status::newGood();
109 }
110
111 /**
112 * Get HTML for a web form that configures this database. Configuration
113 * at this time should be the minimum needed to connect and test
114 * whether install or upgrade is required.
115 *
116 * If this is called, $this->parent can be assumed to be a WebInstaller.
117 */
118 abstract public function getConnectForm();
119
120 /**
121 * Set variables based on the request array, assuming it was submitted
122 * via the form returned by getConnectForm(). Validate the connection
123 * settings by attempting to connect with them.
124 *
125 * If this is called, $this->parent can be assumed to be a WebInstaller.
126 *
127 * @return Status
128 */
129 abstract public function submitConnectForm();
130
131 /**
132 * Get HTML for a web form that retrieves settings used for installation.
133 * $this->parent can be assumed to be a WebInstaller.
134 * If the DB type has no settings beyond those already configured with
135 * getConnectForm(), this should return false.
136 * @return bool
137 */
138 public function getSettingsForm() {
139 return false;
140 }
141
142 /**
143 * Set variables based on the request array, assuming it was submitted via
144 * the form return by getSettingsForm().
145 *
146 * @return Status
147 */
148 public function submitSettingsForm() {
149 return Status::newGood();
150 }
151
152 /**
153 * Open a connection to the database using the administrative user/password
154 * currently defined in the session, without any caching. Returns a status
155 * object. On success, the status object will contain a Database object in
156 * its value member.
157 *
158 * @return Status
159 */
160 abstract public function openConnection();
161
162 /**
163 * Create the database and return a Status object indicating success or
164 * failure.
165 *
166 * @return Status
167 */
168 abstract public function setupDatabase();
169
170 /**
171 * Connect to the database using the administrative user/password currently
172 * defined in the session. Returns a status object. On success, the status
173 * object will contain a Database object in its value member.
174 *
175 * This will return a cached connection if one is available.
176 *
177 * @return Status
178 */
179 public function getConnection() {
180 if ( $this->db ) {
181 return Status::newGood( $this->db );
182 }
183
184 $status = $this->openConnection();
185 if ( $status->isOK() ) {
186 $this->db = $status->value;
187 // Enable autocommit
188 $this->db->clearFlag( DBO_TRX );
189 $this->db->commit( __METHOD__ );
190 }
191
192 return $status;
193 }
194
195 /**
196 * Apply a SQL source file to the database as part of running an installation step.
197 *
198 * @param string $sourceFileMethod
199 * @param string $stepName
200 * @param bool $archiveTableMustNotExist
201 * @return Status
202 */
203 private function stepApplySourceFile(
204 $sourceFileMethod,
205 $stepName,
206 $archiveTableMustNotExist = false
207 ) {
208 $status = $this->getConnection();
209 if ( !$status->isOK() ) {
210 return $status;
211 }
212 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
213
214 if ( $archiveTableMustNotExist && $this->db->tableExists( 'archive', __METHOD__ ) ) {
215 $status->warning( "config-$stepName-tables-exist" );
216 $this->enableLB();
217
218 return $status;
219 }
220
221 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
222 $this->db->begin( __METHOD__ );
223
224 $error = $this->db->sourceFile(
225 call_user_func( [ $this, $sourceFileMethod ], $this->db )
226 );
227 if ( $error !== true ) {
228 $this->db->reportQueryError( $error, 0, '', __METHOD__ );
229 $this->db->rollback( __METHOD__ );
230 $status->fatal( "config-$stepName-tables-failed", $error );
231 } else {
232 $this->db->commit( __METHOD__ );
233 }
234 // Resume normal operations
235 if ( $status->isOK() ) {
236 $this->enableLB();
237 }
238
239 return $status;
240 }
241
242 /**
243 * Create database tables from scratch.
244 *
245 * @return Status
246 */
247 public function createTables() {
248 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
249 }
250
251 /**
252 * Insert update keys into table to prevent running unneded updates.
253 *
254 * @return Status
255 */
256 public function insertUpdateKeys() {
257 return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
258 }
259
260 /**
261 * Return a path to the DBMS-specific SQL file if it exists,
262 * otherwise default SQL file
263 *
264 * @param IDatabase $db
265 * @param string $filename
266 * @return string
267 */
268 private function getSqlFilePath( $db, $filename ) {
269 global $IP;
270
271 $dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
272 if ( file_exists( $dbmsSpecificFilePath ) ) {
273 return $dbmsSpecificFilePath;
274 } else {
275 return "$IP/maintenance/$filename";
276 }
277 }
278
279 /**
280 * Return a path to the DBMS-specific schema file,
281 * otherwise default to tables.sql
282 *
283 * @param IDatabase $db
284 * @return string
285 */
286 public function getSchemaPath( $db ) {
287 return $this->getSqlFilePath( $db, 'tables.sql' );
288 }
289
290 /**
291 * Return a path to the DBMS-specific update key file,
292 * otherwise default to update-keys.sql
293 *
294 * @param IDatabase $db
295 * @return string
296 */
297 public function getUpdateKeysPath( $db ) {
298 return $this->getSqlFilePath( $db, 'update-keys.sql' );
299 }
300
301 /**
302 * Create the tables for each extension the user enabled
303 * @return Status
304 */
305 public function createExtensionTables() {
306 $status = $this->getConnection();
307 if ( !$status->isOK() ) {
308 return $status;
309 }
310
311 // Now run updates to create tables for old extensions
312 DatabaseUpdater::newForDB( $this->db )->doUpdates( [ 'extensions' ] );
313
314 return $status;
315 }
316
317 /**
318 * Get the DBMS-specific options for LocalSettings.php generation.
319 *
320 * @return string
321 */
322 abstract public function getLocalSettings();
323
324 /**
325 * Override this to provide DBMS-specific schema variables, to be
326 * substituted into tables.sql and other schema files.
327 * @return array
328 */
329 public function getSchemaVars() {
330 return [];
331 }
332
333 /**
334 * Set appropriate schema variables in the current database connection.
335 *
336 * This should be called after any request data has been imported, but before
337 * any write operations to the database.
338 */
339 public function setupSchemaVars() {
340 $status = $this->getConnection();
341 if ( $status->isOK() ) {
342 $status->value->setSchemaVars( $this->getSchemaVars() );
343 } else {
344 $msg = __METHOD__ . ': unexpected error while establishing'
345 . ' a database connection with message: '
346 . $status->getMessage()->plain();
347 throw new MWException( $msg );
348 }
349 }
350
351 /**
352 * Set up LBFactory so that wfGetDB() etc. works.
353 * We set up a special LBFactory instance which returns the current
354 * installer connection.
355 */
356 public function enableLB() {
357 $status = $this->getConnection();
358 if ( !$status->isOK() ) {
359 throw new MWException( __METHOD__ . ': unexpected DB connection error' );
360 }
361
362 \MediaWiki\MediaWikiServices::resetGlobalInstance();
363 $services = \MediaWiki\MediaWikiServices::getInstance();
364
365 $connection = $status->value;
366 $services->redefineService( 'DBLoadBalancerFactory', function () use ( $connection ) {
367 return LBFactorySingle::newFromConnection( $connection );
368 } );
369 }
370
371 /**
372 * Perform database upgrades
373 *
374 * @return bool
375 */
376 public function doUpgrade() {
377 $this->setupSchemaVars();
378 $this->enableLB();
379
380 $ret = true;
381 ob_start( [ $this, 'outputHandler' ] );
382 $up = DatabaseUpdater::newForDB( $this->db );
383 try {
384 $up->doUpdates();
385 } catch ( MWException $e ) {
386 echo "\nAn error occurred:\n";
387 echo $e->getText();
388 $ret = false;
389 } catch ( Exception $e ) {
390 echo "\nAn error occurred:\n";
391 echo $e->getMessage();
392 $ret = false;
393 }
394 $up->purgeCache();
395 ob_end_flush();
396
397 return $ret;
398 }
399
400 /**
401 * Allow DB installers a chance to make last-minute changes before installation
402 * occurs. This happens before setupDatabase() or createTables() is called, but
403 * long after the constructor. Helpful for things like modifying setup steps :)
404 */
405 public function preInstall() {
406 }
407
408 /**
409 * Allow DB installers a chance to make checks before upgrade.
410 */
411 public function preUpgrade() {
412 }
413
414 /**
415 * Get an array of MW configuration globals that will be configured by this class.
416 * @return array
417 */
418 public function getGlobalNames() {
419 return $this->globalNames;
420 }
421
422 /**
423 * Construct and initialise parent.
424 * This is typically only called from Installer::getDBInstaller()
425 * @param WebInstaller $parent
426 */
427 public function __construct( $parent ) {
428 $this->parent = $parent;
429 }
430
431 /**
432 * Convenience function.
433 * Check if a named extension is present.
434 *
435 * @param string $name
436 * @return bool
437 */
438 protected static function checkExtension( $name ) {
439 return extension_loaded( $name );
440 }
441
442 /**
443 * Get the internationalised name for this DBMS.
444 * @return string
445 */
446 public function getReadableName() {
447 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
448 // config-type-oracle
449 return wfMessage( 'config-type-' . $this->getName() )->text();
450 }
451
452 /**
453 * Get a name=>value map of MW configuration globals for the default values.
454 * @return array
455 */
456 public function getGlobalDefaults() {
457 $defaults = [];
458 foreach ( $this->getGlobalNames() as $var ) {
459 if ( isset( $GLOBALS[$var] ) ) {
460 $defaults[$var] = $GLOBALS[$var];
461 }
462 }
463 return $defaults;
464 }
465
466 /**
467 * Get a name=>value map of internal variables used during installation.
468 * @return array
469 */
470 public function getInternalDefaults() {
471 return $this->internalDefaults;
472 }
473
474 /**
475 * Get a variable, taking local defaults into account.
476 * @param string $var
477 * @param mixed|null $default
478 * @return mixed
479 */
480 public function getVar( $var, $default = null ) {
481 $defaults = $this->getGlobalDefaults();
482 $internal = $this->getInternalDefaults();
483 if ( isset( $defaults[$var] ) ) {
484 $default = $defaults[$var];
485 } elseif ( isset( $internal[$var] ) ) {
486 $default = $internal[$var];
487 }
488
489 return $this->parent->getVar( $var, $default );
490 }
491
492 /**
493 * Convenience alias for $this->parent->setVar()
494 * @param string $name
495 * @param mixed $value
496 */
497 public function setVar( $name, $value ) {
498 $this->parent->setVar( $name, $value );
499 }
500
501 /**
502 * Get a labelled text box to configure a local variable.
503 *
504 * @param string $var
505 * @param string $label
506 * @param array $attribs
507 * @param string $helpData
508 * @return string
509 */
510 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
511 $name = $this->getName() . '_' . $var;
512 $value = $this->getVar( $var );
513 if ( !isset( $attribs ) ) {
514 $attribs = [];
515 }
516
517 return $this->parent->getTextBox( [
518 'var' => $var,
519 'label' => $label,
520 'attribs' => $attribs,
521 'controlName' => $name,
522 'value' => $value,
523 'help' => $helpData
524 ] );
525 }
526
527 /**
528 * Get a labelled password box to configure a local variable.
529 * Implements password hiding.
530 *
531 * @param string $var
532 * @param string $label
533 * @param array $attribs
534 * @param string $helpData
535 * @return string
536 */
537 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
538 $name = $this->getName() . '_' . $var;
539 $value = $this->getVar( $var );
540 if ( !isset( $attribs ) ) {
541 $attribs = [];
542 }
543
544 return $this->parent->getPasswordBox( [
545 'var' => $var,
546 'label' => $label,
547 'attribs' => $attribs,
548 'controlName' => $name,
549 'value' => $value,
550 'help' => $helpData
551 ] );
552 }
553
554 /**
555 * Get a labelled checkbox to configure a local boolean variable.
556 *
557 * @param string $var
558 * @param string $label
559 * @param array $attribs Optional.
560 * @param string $helpData Optional.
561 * @return string
562 */
563 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
564 $name = $this->getName() . '_' . $var;
565 $value = $this->getVar( $var );
566
567 return $this->parent->getCheckBox( [
568 'var' => $var,
569 'label' => $label,
570 'attribs' => $attribs,
571 'controlName' => $name,
572 'value' => $value,
573 'help' => $helpData
574 ] );
575 }
576
577 /**
578 * Get a set of labelled radio buttons.
579 *
580 * @param array $params Parameters are:
581 * var: The variable to be configured (required)
582 * label: The message name for the label (required)
583 * itemLabelPrefix: The message name prefix for the item labels (required)
584 * values: List of allowed values (required)
585 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
586 *
587 * @return string
588 */
589 public function getRadioSet( $params ) {
590 $params['controlName'] = $this->getName() . '_' . $params['var'];
591 $params['value'] = $this->getVar( $params['var'] );
592
593 return $this->parent->getRadioSet( $params );
594 }
595
596 /**
597 * Convenience function to set variables based on form data.
598 * Assumes that variables containing "password" in the name are (potentially
599 * fake) passwords.
600 * @param array $varNames
601 * @return array
602 */
603 public function setVarsFromRequest( $varNames ) {
604 return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
605 }
606
607 /**
608 * Determine whether an existing installation of MediaWiki is present in
609 * the configured administrative connection. Returns true if there is
610 * such a wiki, false if the database doesn't exist.
611 *
612 * Traditionally, this is done by testing for the existence of either
613 * the revision table or the cur table.
614 *
615 * @return bool
616 */
617 public function needsUpgrade() {
618 $status = $this->getConnection();
619 if ( !$status->isOK() ) {
620 return false;
621 }
622
623 if ( !$this->db->selectDB( $this->getVar( 'wgDBname' ) ) ) {
624 return false;
625 }
626
627 return $this->db->tableExists( 'cur', __METHOD__ ) ||
628 $this->db->tableExists( 'revision', __METHOD__ );
629 }
630
631 /**
632 * Get a standard install-user fieldset.
633 *
634 * @return string
635 */
636 public function getInstallUserBox() {
637 return Html::openElement( 'fieldset' ) .
638 Html::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
639 $this->getTextBox(
640 '_InstallUser',
641 'config-db-username',
642 [ 'dir' => 'ltr' ],
643 $this->parent->getHelpBox( 'config-db-install-username' )
644 ) .
645 $this->getPasswordBox(
646 '_InstallPassword',
647 'config-db-password',
648 [ 'dir' => 'ltr' ],
649 $this->parent->getHelpBox( 'config-db-install-password' )
650 ) .
651 Html::closeElement( 'fieldset' );
652 }
653
654 /**
655 * Submit a standard install user fieldset.
656 * @return Status
657 */
658 public function submitInstallUserBox() {
659 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
660
661 return Status::newGood();
662 }
663
664 /**
665 * Get a standard web-user fieldset
666 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
667 * Set this to false to show a creation checkbox (default).
668 *
669 * @return string
670 */
671 public function getWebUserBox( $noCreateMsg = false ) {
672 $wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
673 $s = Html::openElement( 'fieldset' ) .
674 Html::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
675 $this->getCheckBox(
676 '_SameAccount', 'config-db-web-account-same',
677 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
678 ) .
679 Html::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
680 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
681 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
682 $this->parent->getHelpBox( 'config-db-web-help' );
683 if ( $noCreateMsg ) {
684 $s .= $this->parent->getWarningBox( wfMessage( $noCreateMsg )->plain() );
685 } else {
686 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
687 }
688 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
689
690 return $s;
691 }
692
693 /**
694 * Submit the form from getWebUserBox().
695 *
696 * @return Status
697 */
698 public function submitWebUserBox() {
699 $this->setVarsFromRequest(
700 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
701 );
702
703 if ( $this->getVar( '_SameAccount' ) ) {
704 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
705 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
706 }
707
708 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
709 return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
710 }
711
712 return Status::newGood();
713 }
714
715 /**
716 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
717 *
718 * @return Status
719 */
720 public function populateInterwikiTable() {
721 $status = $this->getConnection();
722 if ( !$status->isOK() ) {
723 return $status;
724 }
725 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
726
727 if ( $this->db->selectRow( 'interwiki', '1', [], __METHOD__ ) ) {
728 $status->warning( 'config-install-interwiki-exists' );
729
730 return $status;
731 }
732 global $IP;
733 MediaWiki\suppressWarnings();
734 $rows = file( "$IP/maintenance/interwiki.list",
735 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
736 MediaWiki\restoreWarnings();
737 $interwikis = [];
738 if ( !$rows ) {
739 return Status::newFatal( 'config-install-interwiki-list' );
740 }
741 foreach ( $rows as $row ) {
742 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
743 if ( $row == "" ) {
744 continue;
745 }
746 $row .= "|";
747 $interwikis[] = array_combine(
748 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
749 explode( '|', $row )
750 );
751 }
752 $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
753
754 return Status::newGood();
755 }
756
757 public function outputHandler( $string ) {
758 return htmlspecialchars( $string );
759 }
760 }