Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[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 use Wikimedia\Rdbms\DBExpectedError;
27 use Wikimedia\Rdbms\DBConnectionError;
28
29 /**
30 * Base class for DBMS-specific installation helper classes.
31 *
32 * @ingroup Deployment
33 * @since 1.17
34 */
35 abstract class DatabaseInstaller {
36
37 /**
38 * The Installer object.
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 $notMinimumVersionMessage;
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::$notMinimumVersionMessage, 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 * @suppress SecurityCheck-XSS Escaping provided by $this->outputHandler
375 * @return bool
376 */
377 public function doUpgrade() {
378 $this->setupSchemaVars();
379 $this->enableLB();
380
381 $ret = true;
382 ob_start( [ $this, 'outputHandler' ] );
383 $up = DatabaseUpdater::newForDB( $this->db );
384 try {
385 $up->doUpdates();
386 $up->purgeCache();
387 } catch ( MWException $e ) {
388 echo "\nAn error occurred:\n";
389 echo $e->getText();
390 $ret = false;
391 } catch ( Exception $e ) {
392 echo "\nAn error occurred:\n";
393 echo $e->getMessage();
394 $ret = false;
395 }
396 ob_end_flush();
397
398 return $ret;
399 }
400
401 /**
402 * Allow DB installers a chance to make last-minute changes before installation
403 * occurs. This happens before setupDatabase() or createTables() is called, but
404 * long after the constructor. Helpful for things like modifying setup steps :)
405 */
406 public function preInstall() {
407 }
408
409 /**
410 * Allow DB installers a chance to make checks before upgrade.
411 */
412 public function preUpgrade() {
413 }
414
415 /**
416 * Get an array of MW configuration globals that will be configured by this class.
417 * @return array
418 */
419 public function getGlobalNames() {
420 return $this->globalNames;
421 }
422
423 /**
424 * Construct and initialise parent.
425 * This is typically only called from Installer::getDBInstaller()
426 * @param WebInstaller $parent
427 */
428 public function __construct( $parent ) {
429 $this->parent = $parent;
430 }
431
432 /**
433 * Convenience function.
434 * Check if a named extension is present.
435 *
436 * @param string $name
437 * @return bool
438 */
439 protected static function checkExtension( $name ) {
440 return extension_loaded( $name );
441 }
442
443 /**
444 * Get the internationalised name for this DBMS.
445 * @return string
446 */
447 public function getReadableName() {
448 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
449 // config-type-oracle
450 return wfMessage( 'config-type-' . $this->getName() )->text();
451 }
452
453 /**
454 * Get a name=>value map of MW configuration globals for the default values.
455 * @return array
456 */
457 public function getGlobalDefaults() {
458 $defaults = [];
459 foreach ( $this->getGlobalNames() as $var ) {
460 if ( isset( $GLOBALS[$var] ) ) {
461 $defaults[$var] = $GLOBALS[$var];
462 }
463 }
464 return $defaults;
465 }
466
467 /**
468 * Get a name=>value map of internal variables used during installation.
469 * @return array
470 */
471 public function getInternalDefaults() {
472 return $this->internalDefaults;
473 }
474
475 /**
476 * Get a variable, taking local defaults into account.
477 * @param string $var
478 * @param mixed|null $default
479 * @return mixed
480 */
481 public function getVar( $var, $default = null ) {
482 $defaults = $this->getGlobalDefaults();
483 $internal = $this->getInternalDefaults();
484 if ( isset( $defaults[$var] ) ) {
485 $default = $defaults[$var];
486 } elseif ( isset( $internal[$var] ) ) {
487 $default = $internal[$var];
488 }
489
490 return $this->parent->getVar( $var, $default );
491 }
492
493 /**
494 * Convenience alias for $this->parent->setVar()
495 * @param string $name
496 * @param mixed $value
497 */
498 public function setVar( $name, $value ) {
499 $this->parent->setVar( $name, $value );
500 }
501
502 /**
503 * Get a labelled text box to configure a local variable.
504 *
505 * @param string $var
506 * @param string $label
507 * @param array $attribs
508 * @param string $helpData
509 * @return string
510 */
511 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
512 $name = $this->getName() . '_' . $var;
513 $value = $this->getVar( $var );
514 if ( !isset( $attribs ) ) {
515 $attribs = [];
516 }
517
518 return $this->parent->getTextBox( [
519 'var' => $var,
520 'label' => $label,
521 'attribs' => $attribs,
522 'controlName' => $name,
523 'value' => $value,
524 'help' => $helpData
525 ] );
526 }
527
528 /**
529 * Get a labelled password box to configure a local variable.
530 * Implements password hiding.
531 *
532 * @param string $var
533 * @param string $label
534 * @param array $attribs
535 * @param string $helpData
536 * @return string
537 */
538 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
539 $name = $this->getName() . '_' . $var;
540 $value = $this->getVar( $var );
541 if ( !isset( $attribs ) ) {
542 $attribs = [];
543 }
544
545 return $this->parent->getPasswordBox( [
546 'var' => $var,
547 'label' => $label,
548 'attribs' => $attribs,
549 'controlName' => $name,
550 'value' => $value,
551 'help' => $helpData
552 ] );
553 }
554
555 /**
556 * Get a labelled checkbox to configure a local boolean variable.
557 *
558 * @param string $var
559 * @param string $label
560 * @param array $attribs Optional.
561 * @param string $helpData Optional.
562 * @return string
563 */
564 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
565 $name = $this->getName() . '_' . $var;
566 $value = $this->getVar( $var );
567
568 return $this->parent->getCheckBox( [
569 'var' => $var,
570 'label' => $label,
571 'attribs' => $attribs,
572 'controlName' => $name,
573 'value' => $value,
574 'help' => $helpData
575 ] );
576 }
577
578 /**
579 * Get a set of labelled radio buttons.
580 *
581 * @param array $params Parameters are:
582 * var: The variable to be configured (required)
583 * label: The message name for the label (required)
584 * itemLabelPrefix: The message name prefix for the item labels (required)
585 * values: List of allowed values (required)
586 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
587 *
588 * @return string
589 */
590 public function getRadioSet( $params ) {
591 $params['controlName'] = $this->getName() . '_' . $params['var'];
592 $params['value'] = $this->getVar( $params['var'] );
593
594 return $this->parent->getRadioSet( $params );
595 }
596
597 /**
598 * Convenience function to set variables based on form data.
599 * Assumes that variables containing "password" in the name are (potentially
600 * fake) passwords.
601 * @param array $varNames
602 * @return array
603 */
604 public function setVarsFromRequest( $varNames ) {
605 return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
606 }
607
608 /**
609 * Determine whether an existing installation of MediaWiki is present in
610 * the configured administrative connection. Returns true if there is
611 * such a wiki, false if the database doesn't exist.
612 *
613 * Traditionally, this is done by testing for the existence of either
614 * the revision table or the cur table.
615 *
616 * @return bool
617 */
618 public function needsUpgrade() {
619 $status = $this->getConnection();
620 if ( !$status->isOK() ) {
621 return false;
622 }
623
624 try {
625 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
626 } catch ( DBConnectionError $e ) {
627 // Don't catch DBConnectionError
628 throw $e;
629 } catch ( DBExpectedError $e ) {
630 return false;
631 }
632
633 return $this->db->tableExists( 'cur', __METHOD__ ) ||
634 $this->db->tableExists( 'revision', __METHOD__ );
635 }
636
637 /**
638 * Get a standard install-user fieldset.
639 *
640 * @return string
641 */
642 public function getInstallUserBox() {
643 return Html::openElement( 'fieldset' ) .
644 Html::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
645 $this->getTextBox(
646 '_InstallUser',
647 'config-db-username',
648 [ 'dir' => 'ltr' ],
649 $this->parent->getHelpBox( 'config-db-install-username' )
650 ) .
651 $this->getPasswordBox(
652 '_InstallPassword',
653 'config-db-password',
654 [ 'dir' => 'ltr' ],
655 $this->parent->getHelpBox( 'config-db-install-password' )
656 ) .
657 Html::closeElement( 'fieldset' );
658 }
659
660 /**
661 * Submit a standard install user fieldset.
662 * @return Status
663 */
664 public function submitInstallUserBox() {
665 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
666
667 return Status::newGood();
668 }
669
670 /**
671 * Get a standard web-user fieldset
672 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
673 * Set this to false to show a creation checkbox (default).
674 *
675 * @return string
676 */
677 public function getWebUserBox( $noCreateMsg = false ) {
678 $wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
679 $s = Html::openElement( 'fieldset' ) .
680 Html::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
681 $this->getCheckBox(
682 '_SameAccount', 'config-db-web-account-same',
683 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
684 ) .
685 Html::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
686 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
687 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
688 $this->parent->getHelpBox( 'config-db-web-help' );
689 if ( $noCreateMsg ) {
690 $s .= $this->parent->getWarningBox( wfMessage( $noCreateMsg )->plain() );
691 } else {
692 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
693 }
694 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
695
696 return $s;
697 }
698
699 /**
700 * Submit the form from getWebUserBox().
701 *
702 * @return Status
703 */
704 public function submitWebUserBox() {
705 $this->setVarsFromRequest(
706 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
707 );
708
709 if ( $this->getVar( '_SameAccount' ) ) {
710 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
711 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
712 }
713
714 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
715 return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
716 }
717
718 return Status::newGood();
719 }
720
721 /**
722 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
723 *
724 * @return Status
725 */
726 public function populateInterwikiTable() {
727 $status = $this->getConnection();
728 if ( !$status->isOK() ) {
729 return $status;
730 }
731 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
732
733 if ( $this->db->selectRow( 'interwiki', '1', [], __METHOD__ ) ) {
734 $status->warning( 'config-install-interwiki-exists' );
735
736 return $status;
737 }
738 global $IP;
739 Wikimedia\suppressWarnings();
740 $rows = file( "$IP/maintenance/interwiki.list",
741 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
742 Wikimedia\restoreWarnings();
743 $interwikis = [];
744 if ( !$rows ) {
745 return Status::newFatal( 'config-install-interwiki-list' );
746 }
747 foreach ( $rows as $row ) {
748 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
749 if ( $row == "" ) {
750 continue;
751 }
752 $row .= "|";
753 $interwikis[] = array_combine(
754 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
755 explode( '|', $row )
756 );
757 }
758 $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
759
760 return Status::newGood();
761 }
762
763 public function outputHandler( $string ) {
764 return htmlspecialchars( $string );
765 }
766 }