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