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