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