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