MediaWiki  master
DatabaseInstaller.php
Go to the documentation of this file.
1 <?php
30 abstract class DatabaseInstaller {
31 
39  public $parent;
40 
46  public $db = null;
47 
53  protected $internalDefaults = [];
54 
60  protected $globalNames = [];
61 
65  abstract public function getName();
66 
70  abstract public function isCompiled();
71 
77  public function checkPrerequisites() {
78  return Status::newGood();
79  }
80 
88  abstract public function getConnectForm();
89 
99  abstract public function submitConnectForm();
100 
108  public function getSettingsForm() {
109  return false;
110  }
111 
118  public function submitSettingsForm() {
119  return Status::newGood();
120  }
121 
130  abstract public function openConnection();
131 
138  abstract public function setupDatabase();
139 
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 
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->db, $sourceFileMethod ] )
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 
217  public function createTables() {
218  return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
219  }
220 
226  public function insertUpdateKeys() {
227  return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
228  }
229 
234  public function createExtensionTables() {
235  $status = $this->getConnection();
236  if ( !$status->isOK() ) {
237  return $status;
238  }
239 
240  // Now run updates to create tables for old extensions
241  DatabaseUpdater::newForDB( $this->db )->doUpdates( [ 'extensions' ] );
242 
243  return $status;
244  }
245 
251  abstract public function getLocalSettings();
252 
258  public function getSchemaVars() {
259  return [];
260  }
261 
268  public function setupSchemaVars() {
269  $status = $this->getConnection();
270  if ( $status->isOK() ) {
271  $status->value->setSchemaVars( $this->getSchemaVars() );
272  } else {
273  $msg = __METHOD__ . ': unexpected error while establishing'
274  . ' a database connection with message: '
275  . $status->getMessage()->plain();
276  throw new MWException( $msg );
277  }
278  }
279 
285  public function enableLB() {
286  $status = $this->getConnection();
287  if ( !$status->isOK() ) {
288  throw new MWException( __METHOD__ . ': unexpected DB connection error' );
289  }
290 
291  \MediaWiki\MediaWikiServices::resetGlobalInstance();
292  $services = \MediaWiki\MediaWikiServices::getInstance();
293 
294  $connection = $status->value;
295  $services->redefineService( 'DBLoadBalancerFactory', function() use ( $connection ) {
296  return new LBFactorySingle( [
297  'connection' => $connection ] );
298  } );
299 
300  }
301 
307  public function doUpgrade() {
308  $this->setupSchemaVars();
309  $this->enableLB();
310 
311  $ret = true;
312  ob_start( [ $this, 'outputHandler' ] );
313  $up = DatabaseUpdater::newForDB( $this->db );
314  try {
315  $up->doUpdates();
316  } catch ( Exception $e ) {
317  echo "\nAn error occurred:\n";
318  echo $e->getText();
319  $ret = false;
320  }
321  $up->purgeCache();
322  ob_end_flush();
323 
324  return $ret;
325  }
326 
332  public function preInstall() {
333  }
334 
338  public function preUpgrade() {
339  }
340 
345  public function getGlobalNames() {
346  return $this->globalNames;
347  }
348 
354  public function __construct( $parent ) {
355  $this->parent = $parent;
356  }
357 
365  protected static function checkExtension( $name ) {
366  return extension_loaded( $name );
367  }
368 
373  public function getReadableName() {
374  // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
375  // config-type-oracle
376  return wfMessage( 'config-type-' . $this->getName() )->text();
377  }
378 
383  public function getGlobalDefaults() {
384  $defaults = [];
385  foreach ( $this->getGlobalNames() as $var ) {
386  if ( isset( $GLOBALS[$var] ) ) {
387  $defaults[$var] = $GLOBALS[$var];
388  }
389  }
390  return $defaults;
391  }
392 
397  public function getInternalDefaults() {
399  }
400 
407  public function getVar( $var, $default = null ) {
408  $defaults = $this->getGlobalDefaults();
409  $internal = $this->getInternalDefaults();
410  if ( isset( $defaults[$var] ) ) {
411  $default = $defaults[$var];
412  } elseif ( isset( $internal[$var] ) ) {
413  $default = $internal[$var];
414  }
415 
416  return $this->parent->getVar( $var, $default );
417  }
418 
424  public function setVar( $name, $value ) {
425  $this->parent->setVar( $name, $value );
426  }
427 
437  public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
438  $name = $this->getName() . '_' . $var;
439  $value = $this->getVar( $var );
440  if ( !isset( $attribs ) ) {
441  $attribs = [];
442  }
443 
444  return $this->parent->getTextBox( [
445  'var' => $var,
446  'label' => $label,
447  'attribs' => $attribs,
448  'controlName' => $name,
449  'value' => $value,
450  'help' => $helpData
451  ] );
452  }
453 
464  public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
465  $name = $this->getName() . '_' . $var;
466  $value = $this->getVar( $var );
467  if ( !isset( $attribs ) ) {
468  $attribs = [];
469  }
470 
471  return $this->parent->getPasswordBox( [
472  'var' => $var,
473  'label' => $label,
474  'attribs' => $attribs,
475  'controlName' => $name,
476  'value' => $value,
477  'help' => $helpData
478  ] );
479  }
480 
490  public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
491  $name = $this->getName() . '_' . $var;
492  $value = $this->getVar( $var );
493 
494  return $this->parent->getCheckBox( [
495  'var' => $var,
496  'label' => $label,
497  'attribs' => $attribs,
498  'controlName' => $name,
499  'value' => $value,
500  'help' => $helpData
501  ] );
502  }
503 
516  public function getRadioSet( $params ) {
517  $params['controlName'] = $this->getName() . '_' . $params['var'];
518  $params['value'] = $this->getVar( $params['var'] );
519 
520  return $this->parent->getRadioSet( $params );
521  }
522 
530  public function setVarsFromRequest( $varNames ) {
531  return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
532  }
533 
544  public function needsUpgrade() {
545  $status = $this->getConnection();
546  if ( !$status->isOK() ) {
547  return false;
548  }
549 
550  if ( !$this->db->selectDB( $this->getVar( 'wgDBname' ) ) ) {
551  return false;
552  }
553 
554  return $this->db->tableExists( 'cur', __METHOD__ ) ||
555  $this->db->tableExists( 'revision', __METHOD__ );
556  }
557 
563  public function getInstallUserBox() {
564  return Html::openElement( 'fieldset' ) .
565  Html::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
566  $this->getTextBox(
567  '_InstallUser',
568  'config-db-username',
569  [ 'dir' => 'ltr' ],
570  $this->parent->getHelpBox( 'config-db-install-username' )
571  ) .
572  $this->getPasswordBox(
573  '_InstallPassword',
574  'config-db-password',
575  [ 'dir' => 'ltr' ],
576  $this->parent->getHelpBox( 'config-db-install-password' )
577  ) .
578  Html::closeElement( 'fieldset' );
579  }
580 
585  public function submitInstallUserBox() {
586  $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
587 
588  return Status::newGood();
589  }
590 
598  public function getWebUserBox( $noCreateMsg = false ) {
599  $wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
600  $s = Html::openElement( 'fieldset' ) .
601  Html::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
602  $this->getCheckBox(
603  '_SameAccount', 'config-db-web-account-same',
604  [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
605  ) .
606  Html::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
607  $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
608  $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
609  $this->parent->getHelpBox( 'config-db-web-help' );
610  if ( $noCreateMsg ) {
611  $s .= $this->parent->getWarningBox( wfMessage( $noCreateMsg )->plain() );
612  } else {
613  $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
614  }
615  $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
616 
617  return $s;
618  }
619 
625  public function submitWebUserBox() {
626  $this->setVarsFromRequest(
627  [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
628  );
629 
630  if ( $this->getVar( '_SameAccount' ) ) {
631  $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
632  $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
633  }
634 
635  if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
636  return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
637  }
638 
639  return Status::newGood();
640  }
641 
647  public function populateInterwikiTable() {
648  $status = $this->getConnection();
649  if ( !$status->isOK() ) {
650  return $status;
651  }
652  $this->db->selectDB( $this->getVar( 'wgDBname' ) );
653 
654  if ( $this->db->selectRow( 'interwiki', '*', [], __METHOD__ ) ) {
655  $status->warning( 'config-install-interwiki-exists' );
656 
657  return $status;
658  }
659  global $IP;
660  MediaWiki\suppressWarnings();
661  $rows = file( "$IP/maintenance/interwiki.list",
662  FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
663  MediaWiki\restoreWarnings();
664  $interwikis = [];
665  if ( !$rows ) {
666  return Status::newFatal( 'config-install-interwiki-list' );
667  }
668  foreach ( $rows as $row ) {
669  $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
670  if ( $row == "" ) {
671  continue;
672  }
673  $row .= "|";
674  $interwikis[] = array_combine(
675  [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
676  explode( '|', $row )
677  );
678  }
679  $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
680 
681  return Status::newGood();
682  }
683 
684  public function outputHandler( $string ) {
685  return htmlspecialchars( $string );
686  }
687 }
static closeElement($element)
Returns "</$element>".
Definition: Html.php:306
An LBFactory class that always returns a single database object.
$IP
Definition: WebStart.php:58
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
preUpgrade()
Allow DB installers a chance to make checks before upgrade.
preInstall()
Allow DB installers a chance to make last-minute changes before installation occurs.
__construct($parent)
Construct and initialise parent.
needsUpgrade()
Determine whether an existing installation of MediaWiki is present in the configured administrative c...
submitSettingsForm()
Set variables based on the request array, assuming it was submitted via the form return by getSetting...
getLocalSettings()
Get the DBMS-specific options for LocalSettings.php generation.
array $globalNames
Array of MW configuration globals this class uses.
$value
const DBO_TRX
Definition: Defines.php:33
doUpgrade()
Perform database upgrades.
getVar($var, $default=null)
Get a variable, taking local defaults into account.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
createTables()
Create database tables from scratch.
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
getConnection()
Connect to the database using the administrative user/password currently defined in the session...
stepApplySourceFile($sourceFileMethod, $stepName, $archiveTableMustNotExist=false)
Apply a SQL source file to the database as part of running an installation step.
getSchemaVars()
Override this to provide DBMS-specific schema variables, to be substituted into tables.sql and other schema files.
checkPrerequisites()
Checks for installation prerequisites other than those checked by isCompiled()
static openElement($element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:248
submitWebUserBox()
Submit the form from getWebUserBox().
getName()
Return the internal name, e.g.
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
Definition: hooks.txt:93
setupSchemaVars()
Set appropriate schema variables in the current database connection.
$GLOBALS['IP']
getConnectForm()
Get HTML for a web form that configures this database.
getReadableName()
Get the internationalised name for this DBMS.
createExtensionTables()
Create the tables for each extension the user enabled.
MediaWiki exception.
Definition: MWException.php:26
getInternalDefaults()
Get a name=>value map of internal variables used during installation.
$params
DatabaseBase $db
The database connection.
getWebUserBox($noCreateMsg=false)
Get a standard web-user fieldset.
getGlobalDefaults()
Get a name=>value map of MW configuration globals for the default values.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
submitConnectForm()
Set variables based on the request array, assuming it was submitted via the form returned by getConne...
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2044
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1816
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
submitInstallUserBox()
Submit a standard install user fieldset.
getPasswordBox($var, $label, $attribs=[], $helpData="")
Get a labelled password box to configure a local variable.
setVarsFromRequest($varNames)
Convenience function to set variables based on form data.
getInstallUserBox()
Get a standard install-user fieldset.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
const DBO_DDLMODE
Definition: Defines.php:37
setupDatabase()
Create the database and return a Status object indicating success or failure.
static checkExtension($name)
Convenience function.
getTextBox($var, $label, $attribs=[], $helpData="")
Get a labelled text box to configure a local variable.
Base class for DBMS-specific installation helper classes.
getCheckBox($var, $label, $attribs=[], $helpData="")
Get a labelled checkbox to configure a local boolean variable.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1020
openConnection()
Open a connection to the database using the administrative user/password currently defined in the ses...
setVar($name, $value)
Convenience alias for $this->parent->setVar()
insertUpdateKeys()
Insert update keys into table to prevent running unneded updates.
populateInterwikiTable()
Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:1816
static newForDB(&$db, $shared=false, $maintenance=null)
WebInstaller $parent
The Installer object.
getGlobalNames()
Get an array of MW configuration globals that will be configured by this class.
getRadioSet($params)
Get a set of labelled radio buttons.
getSettingsForm()
Get HTML for a web form that retrieves settings used for installation.
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:230
enableLB()
Set up LBFactory so that wfGetDB() etc.
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
array $internalDefaults
Internal variables for installation.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310