]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/installer/DatabaseInstaller.php
MediaWiki 1.17.0
[autoinstalls/mediawiki.git] / includes / installer / DatabaseInstaller.php
1 <?php
2 /**
3  * DBMS-specific installation helper.
4  *
5  * @file
6  * @ingroup Deployment
7  */
8
9 /**
10  * Base class for DBMS-specific installation helper classes.
11  *
12  * @ingroup Deployment
13  * @since 1.17
14  */
15 abstract class DatabaseInstaller {
16
17         /**
18          * The Installer object.
19          *
20          * TODO: naming this parent is confusing, 'installer' would be clearer.
21          *
22          * @var WebInstaller
23          */
24         public $parent;
25
26         /**
27          * The database connection.
28          *
29          * @var DatabaseBase
30          */
31         public $db = null;
32
33         /**
34          * Internal variables for installation.
35          *
36          * @var array
37          */
38         protected $internalDefaults = array();
39
40         /**
41          * Array of MW configuration globals this class uses.
42          *
43          * @var array
44          */
45         protected $globalNames = array();
46
47         /**
48          * Return the internal name, e.g. 'mysql', or 'sqlite'.
49          */
50         public abstract function getName();
51
52         /**
53          * @return true if the client library is compiled in.
54          */
55         public abstract function isCompiled();
56
57         /**
58          * Get HTML for a web form that configures this database. Configuration
59          * at this time should be the minimum needed to connect and test
60          * whether install or upgrade is required.
61          *
62          * If this is called, $this->parent can be assumed to be a WebInstaller.
63          */
64         public abstract function getConnectForm();
65
66         /**
67          * Set variables based on the request array, assuming it was submitted
68          * via the form returned by getConnectForm(). Validate the connection
69          * settings by attempting to connect with them.
70          *
71          * If this is called, $this->parent can be assumed to be a WebInstaller.
72          *
73          * @return Status
74          */
75         public abstract function submitConnectForm();
76
77         /**
78          * Get HTML for a web form that retrieves settings used for installation.
79          * $this->parent can be assumed to be a WebInstaller.
80          * If the DB type has no settings beyond those already configured with
81          * getConnectForm(), this should return false.
82          */
83         public function getSettingsForm() {
84                 return false;
85         }
86
87         /**
88          * Set variables based on the request array, assuming it was submitted via
89          * the form return by getSettingsForm().
90          *
91          * @return Status
92          */
93         public function submitSettingsForm() {
94                 return Status::newGood();
95         }
96
97         /**
98          * Open a connection to the database using the administrative user/password
99          * currently defined in the session, without any caching. Returns a status
100          * object. On success, the status object will contain a Database object in
101          * its value member.
102          *
103          * @return Status
104          */
105         public abstract function openConnection();
106
107         /**
108          * Create the database and return a Status object indicating success or
109          * failure.
110          *
111          * @return Status
112          */
113         public abstract function setupDatabase();
114
115         /**
116          * Connect to the database using the administrative user/password currently
117          * defined in the session. Returns a status object. On success, the status
118          * object will contain a Database object in its value member.
119          *
120          * This will return a cached connection if one is available.
121          *
122          * @return Status
123          */
124         public function getConnection() {
125                 if ( $this->db ) {
126                         return Status::newGood( $this->db );
127                 }
128
129                 $status = $this->openConnection();
130                 if ( $status->isOK() ) {
131                         $this->db = $status->value;
132                         // Enable autocommit
133                         $this->db->clearFlag( DBO_TRX );
134                         $this->db->commit();
135                 }
136                 return $status;
137         }
138
139         /**
140          * Create database tables from scratch.
141          *
142          * @return Status
143          */
144         public function createTables() {
145                 $status = $this->getConnection();
146                 if ( !$status->isOK() ) {
147                         return $status;
148                 }
149                 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
150
151                 if( $this->db->tableExists( 'user' ) ) {
152                         $status->warning( 'config-install-tables-exist' );
153                         $this->enableLB();
154                         return $status;
155                 }
156
157                 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
158                 $this->db->begin( __METHOD__ );
159
160                 $error = $this->db->sourceFile( $this->db->getSchema() );
161                 if( $error !== true ) {
162                         $this->db->reportQueryError( $error, 0, '', __METHOD__ );
163                         $this->db->rollback( __METHOD__ );
164                         $status->fatal( 'config-install-tables-failed', $error );
165                 } else {
166                         $this->db->commit( __METHOD__ );
167                 }
168                 // Resume normal operations
169                 if( $status->isOk() ) {
170                         $this->enableLB();
171                 }
172                 return $status;
173         }
174
175         /**
176          * Create the tables for each extension the user enabled
177          * @return Status
178          */
179         public function createExtensionTables() {
180                 $status = $this->getConnection();
181                 if ( !$status->isOK() ) {
182                         return $status;
183                 }
184                 $updater = DatabaseUpdater::newForDB( $this->db );
185                 $extensionUpdates = $updater->getNewExtensions();
186
187                 $ourExtensions = array_map( 'strtolower', $this->getVar( '_Extensions' ) );
188
189                 foreach( $ourExtensions as $ext ) {
190                         if( isset( $extensionUpdates[$ext] ) ) {
191                                 $this->db->begin( __METHOD__ );
192                                 $error = $this->db->sourceFile( $extensionUpdates[$ext] );
193                                 if( $error !== true ) {
194                                         $this->db->rollback( __METHOD__ );
195                                         $status->warning( 'config-install-tables-failed', $error );
196                                 } else {
197                                         $this->db->commit( __METHOD__ );
198                                 }
199                         }
200                 }
201
202                 // Now run updates to create tables for old extensions
203                 $updater->doUpdates( array( 'extensions' ) );
204
205                 return $status;
206         }
207
208         /**
209          * Get the DBMS-specific options for LocalSettings.php generation.
210          *
211          * @return String
212          */
213         public abstract function getLocalSettings();
214
215         /**
216          * Override this to provide DBMS-specific schema variables, to be
217          * substituted into tables.sql and other schema files.
218          */
219         public function getSchemaVars() {
220                 return array();
221         }
222
223         /**
224          * Set appropriate schema variables in the current database connection.
225          *
226          * This should be called after any request data has been imported, but before
227          * any write operations to the database.
228          */
229         public function setupSchemaVars() {
230                 $status = $this->getConnection();
231                 if ( $status->isOK() ) {
232                         $status->value->setSchemaVars( $this->getSchemaVars() );
233                 } else {
234                         throw new MWException( __METHOD__.': unexpected DB connection error' );
235                 }
236         }
237
238         /**
239          * Set up LBFactory so that wfGetDB() etc. works.
240          * We set up a special LBFactory instance which returns the current
241          * installer connection.
242          */
243         public function enableLB() {
244                 $status = $this->getConnection();
245                 if ( !$status->isOK() ) {
246                         throw new MWException( __METHOD__.': unexpected DB connection error' );
247                 }
248                 LBFactory::setInstance( new LBFactory_Single( array(
249                         'connection' => $status->value ) ) );
250         }
251
252         /**
253          * Perform database upgrades
254          *
255          * @return Boolean
256          */
257         public function doUpgrade() {
258                 $this->setupSchemaVars();
259                 $this->enableLB();
260
261                 $ret = true;
262                 ob_start( array( $this, 'outputHandler' ) );
263                 try {
264                         $up = DatabaseUpdater::newForDB( $this->db );
265                         $up->doUpdates();
266                 } catch ( MWException $e ) {
267                         echo "\nAn error occured:\n";
268                         echo $e->getText();
269                         $ret = false;
270                 }
271                 ob_end_flush();
272                 return $ret;
273         }
274
275         /**
276          * Allow DB installers a chance to make last-minute changes before installation
277          * occurs. This happens before setupDatabase() or createTables() is called, but
278          * long after the constructor. Helpful for things like modifying setup steps :)
279          */
280         public function preInstall() {
281
282         }
283
284         /**
285          * Allow DB installers a chance to make checks before upgrade.
286          */
287         public function preUpgrade() {
288
289         }
290
291         /**
292          * Get an array of MW configuration globals that will be configured by this class.
293          */
294         public function getGlobalNames() {
295                 return $this->globalNames;
296         }
297
298         /**
299          * Construct and initialise parent.
300          * This is typically only called from Installer::getDBInstaller()
301          */
302         public function __construct( $parent ) {
303                 $this->parent = $parent;
304         }
305
306         /**
307          * Convenience function.
308          * Check if a named extension is present.
309          *
310          * @see wfDl
311          */
312         protected static function checkExtension( $name ) {
313                 wfSuppressWarnings();
314                 $compiled = wfDl( $name );
315                 wfRestoreWarnings();
316                 return $compiled;
317         }
318
319         /**
320          * Get the internationalised name for this DBMS.
321          */
322         public function getReadableName() {
323                 return wfMsg( 'config-type-' . $this->getName() );
324         }
325
326         /**
327          * Get a name=>value map of MW configuration globals that overrides.
328          * DefaultSettings.php
329          */
330         public function getGlobalDefaults() {
331                 return array();
332         }
333
334         /**
335          * Get a name=>value map of internal variables used during installation.
336          */
337         public function getInternalDefaults() {
338                 return $this->internalDefaults;
339         }
340
341         /**
342          * Get a variable, taking local defaults into account.
343          */
344         public function getVar( $var, $default = null ) {
345                 $defaults = $this->getGlobalDefaults();
346                 $internal = $this->getInternalDefaults();
347                 if ( isset( $defaults[$var] ) ) {
348                         $default = $defaults[$var];
349                 } elseif ( isset( $internal[$var] ) ) {
350                         $default = $internal[$var];
351                 }
352                 return $this->parent->getVar( $var, $default );
353         }
354
355         /**
356          * Convenience alias for $this->parent->setVar()
357          */
358         public function setVar( $name, $value ) {
359                 $this->parent->setVar( $name, $value );
360         }
361
362         /**
363          * Get a labelled text box to configure a local variable.
364          */
365         public function getTextBox( $var, $label, $attribs = array(), $helpData = "" ) {
366                 $name = $this->getName() . '_' . $var;
367                 $value = $this->getVar( $var );
368                 if ( !isset( $attribs ) ) {
369                         $attribs = array();
370                 }
371                 return $this->parent->getTextBox( array(
372                         'var' => $var,
373                         'label' => $label,
374                         'attribs' => $attribs,
375                         'controlName' => $name,
376                         'value' => $value,
377                         'help' => $helpData
378                 ) );
379         }
380
381         /**
382          * Get a labelled password box to configure a local variable.
383          * Implements password hiding.
384          */
385         public function getPasswordBox( $var, $label, $attribs = array(), $helpData = "" ) {
386                 $name = $this->getName() . '_' . $var;
387                 $value = $this->getVar( $var );
388                 if ( !isset( $attribs ) ) {
389                         $attribs = array();
390                 }
391                 return $this->parent->getPasswordBox( array(
392                         'var' => $var,
393                         'label' => $label,
394                         'attribs' => $attribs,
395                         'controlName' => $name,
396                         'value' => $value,
397                         'help' => $helpData
398                 ) );
399         }
400
401         /**
402          * Get a labelled checkbox to configure a local boolean variable.
403          */
404         public function getCheckBox( $var, $label, $attribs = array(), $helpData = "" ) {
405                 $name = $this->getName() . '_' . $var;
406                 $value = $this->getVar( $var );
407                 return $this->parent->getCheckBox( array(
408                         'var' => $var,
409                         'label' => $label,
410                         'attribs' => $attribs,
411                         'controlName' => $name,
412                         'value' => $value,
413                         'help' => $helpData
414                 ));
415         }
416
417         /**
418          * Get a set of labelled radio buttons.
419          *
420          * @param $params Array:
421          *    Parameters are:
422          *      var:            The variable to be configured (required)
423          *      label:          The message name for the label (required)
424          *      itemLabelPrefix: The message name prefix for the item labels (required)
425          *      values:         List of allowed values (required)
426          *      itemAttribs     Array of attribute arrays, outer key is the value name (optional)
427          *
428          */
429         public function getRadioSet( $params ) {
430                 $params['controlName'] = $this->getName() . '_' . $params['var'];
431                 $params['value'] = $this->getVar( $params['var'] );
432                 return $this->parent->getRadioSet( $params );
433         }
434
435         /**
436          * Convenience function to set variables based on form data.
437          * Assumes that variables containing "password" in the name are (potentially
438          * fake) passwords.
439          * @param $varNames Array
440          */
441         public function setVarsFromRequest( $varNames ) {
442                 return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
443         }
444
445         /**
446          * Determine whether an existing installation of MediaWiki is present in
447          * the configured administrative connection. Returns true if there is
448          * such a wiki, false if the database doesn't exist.
449          *
450          * Traditionally, this is done by testing for the existence of either
451          * the revision table or the cur table.
452          *
453          * @return Boolean
454          */
455         public function needsUpgrade() {
456                 $status = $this->getConnection();
457                 if ( !$status->isOK() ) {
458                         return false;
459                 }
460
461                 if ( !$this->db->selectDB( $this->getVar( 'wgDBname' ) ) ) {
462                         return false;
463                 }
464                 return $this->db->tableExists( 'cur' ) || $this->db->tableExists( 'revision' );
465         }
466
467         /**
468          * Get a standard install-user fieldset.
469          *
470          * @return String
471          */
472         public function getInstallUserBox() {
473                 return
474                         Html::openElement( 'fieldset' ) .
475                         Html::element( 'legend', array(), wfMsg( 'config-db-install-account' ) ) .
476                         $this->getTextBox( '_InstallUser', 'config-db-username', array(), $this->parent->getHelpBox( 'config-db-install-username' ) ) .
477                         $this->getPasswordBox( '_InstallPassword', 'config-db-password', array(), $this->parent->getHelpBox( 'config-db-install-password' ) ) .
478                         Html::closeElement( 'fieldset' );
479         }
480
481         /**
482          * Submit a standard install user fieldset.
483          */
484         public function submitInstallUserBox() {
485                 $this->setVarsFromRequest( array( '_InstallUser', '_InstallPassword' ) );
486                 return Status::newGood();
487         }
488
489         /**
490          * Get a standard web-user fieldset
491          * @param $noCreateMsg String: Message to display instead of the creation checkbox.
492          *   Set this to false to show a creation checkbox.
493          *
494          * @return String
495          */
496         public function getWebUserBox( $noCreateMsg = false ) {
497                 $wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
498                 $s = Html::openElement( 'fieldset' ) .
499                         Html::element( 'legend', array(), wfMsg( 'config-db-web-account' ) ) .
500                         $this->getCheckBox(
501                                 '_SameAccount', 'config-db-web-account-same',
502                                 array( 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' )
503                         ) .
504                         Html::openElement( 'div', array( 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ) ) .
505                         $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
506                         $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
507                         $this->parent->getHelpBox( 'config-db-web-help' );
508                 if ( $noCreateMsg ) {
509                         $s .= $this->parent->getWarningBox( wfMsgNoTrans( $noCreateMsg ) );
510                 } else {
511                         $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
512                 }
513                 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
514                 return $s;
515         }
516
517         /**
518          * Submit the form from getWebUserBox().
519          *
520          * @return Status
521          */
522         public function submitWebUserBox() {
523                 $this->setVarsFromRequest(
524                         array( 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' )
525                 );
526
527                 if ( $this->getVar( '_SameAccount' ) ) {
528                         $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
529                         $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
530                 }
531
532                 if( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
533                         return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
534                 }
535
536                 return Status::newGood();
537         }
538
539         /**
540          * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
541          *
542          * @return Status
543          */
544         public function populateInterwikiTable() {
545                 $status = $this->getConnection();
546                 if ( !$status->isOK() ) {
547                         return $status;
548                 }
549                 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
550
551                 if( $this->db->selectRow( 'interwiki', '*', array(), __METHOD__ ) ) {
552                         $status->warning( 'config-install-interwiki-exists' );
553                         return $status;
554                 }
555                 global $IP;
556                 wfSuppressWarnings();
557                 $rows = file( "$IP/maintenance/interwiki.list",
558                         FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
559                 wfRestoreWarnings();
560                 $interwikis = array();
561                 if ( !$rows ) {
562                         return Status::newFatal( 'config-install-interwiki-list' );
563                 }
564                 foreach( $rows as $row ) {
565                         $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
566                         if ( $row == "" ) continue;
567                         $row .= "||";
568                         $interwikis[] = array_combine(
569                                 array( 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ),
570                                 explode( '|', $row )
571                         );
572                 }
573                 $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
574                 return Status::newGood();
575         }
576
577         public function outputHandler( $string ) {
578                 return htmlspecialchars( $string );
579         }
580 }