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