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