Merge "Typo fix"
[mediawiki.git] / includes / installer / PostgresInstaller.php
blob37471890b44406ef70dd577d932f2af0cc94b070
1 <?php
2 /**
3 * PostgreSQL-specific installer.
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.
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.
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
20 * @file
21 * @ingroup Deployment
24 /**
25 * Class for setting up the MediaWiki database using Postgres.
27 * @ingroup Deployment
28 * @since 1.17
30 class PostgresInstaller extends DatabaseInstaller {
32 protected $globalNames = array(
33 'wgDBserver',
34 'wgDBport',
35 'wgDBname',
36 'wgDBuser',
37 'wgDBpassword',
38 'wgDBmwschema',
41 protected $internalDefaults = array(
42 '_InstallUser' => 'postgres',
45 var $minimumVersion = '8.3';
46 var $maxRoleSearchDepth = 5;
48 protected $pgConns = array();
50 function getName() {
51 return 'postgres';
54 public function isCompiled() {
55 return self::checkExtension( 'pgsql' );
58 function getConnectForm() {
59 return $this->getTextBox( 'wgDBserver', 'config-db-host', array(), $this->parent->getHelpBox( 'config-db-host-help' ) ) .
60 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
61 Html::openElement( 'fieldset' ) .
62 Html::element( 'legend', array(), wfMessage( 'config-db-wiki-settings' )->text() ) .
63 $this->getTextBox( 'wgDBname', 'config-db-name', array(), $this->parent->getHelpBox( 'config-db-name-help' ) ) .
64 $this->getTextBox( 'wgDBmwschema', 'config-db-schema', array(), $this->parent->getHelpBox( 'config-db-schema-help' ) ) .
65 Html::closeElement( 'fieldset' ) .
66 $this->getInstallUserBox();
69 function submitConnectForm() {
70 // Get variables from the request
71 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBport',
72 'wgDBname', 'wgDBmwschema' ) );
74 // Validate them
75 $status = Status::newGood();
76 if ( !strlen( $newValues['wgDBname'] ) ) {
77 $status->fatal( 'config-missing-db-name' );
78 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
79 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
81 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
82 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
85 // Submit user box
86 if ( $status->isOK() ) {
87 $status->merge( $this->submitInstallUserBox() );
89 if ( !$status->isOK() ) {
90 return $status;
93 $status = $this->getPgConnection( 'create-db' );
94 if ( !$status->isOK() ) {
95 return $status;
97 /**
98 * @var $conn DatabaseBase
100 $conn = $status->value;
102 // Check version
103 $version = $conn->getServerVersion();
104 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
105 return Status::newFatal( 'config-postgres-old', $this->minimumVersion, $version );
108 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
109 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
110 return Status::newGood();
113 public function getConnection() {
114 $status = $this->getPgConnection( 'create-tables' );
115 if ( $status->isOK() ) {
116 $this->db = $status->value;
118 return $status;
121 public function openConnection() {
122 return $this->openPgConnection( 'create-tables' );
126 * Open a PG connection with given parameters
127 * @param string $user User name
128 * @param string $password Password
129 * @param string $dbName Database name
130 * @return Status
132 protected function openConnectionWithParams( $user, $password, $dbName ) {
133 $status = Status::newGood();
134 try {
135 $db = new DatabasePostgres(
136 $this->getVar( 'wgDBserver' ),
137 $user,
138 $password,
139 $dbName
141 $status->value = $db;
142 } catch ( DBConnectionError $e ) {
143 $status->fatal( 'config-connection-error', $e->getMessage() );
145 return $status;
149 * Get a special type of connection
150 * @param string $type See openPgConnection() for details.
151 * @return Status
153 protected function getPgConnection( $type ) {
154 if ( isset( $this->pgConns[$type] ) ) {
155 return Status::newGood( $this->pgConns[$type] );
157 $status = $this->openPgConnection( $type );
159 if ( $status->isOK() ) {
161 * @var $conn DatabaseBase
163 $conn = $status->value;
164 $conn->clearFlag( DBO_TRX );
165 $conn->commit( __METHOD__ );
166 $this->pgConns[$type] = $conn;
168 return $status;
172 * Get a connection of a specific PostgreSQL-specific type. Connections
173 * of a given type are cached.
175 * PostgreSQL lacks cross-database operations, so after the new database is
176 * created, you need to make a separate connection to connect to that
177 * database and add tables to it.
179 * New tables are owned by the user that creates them, and MediaWiki's
180 * PostgreSQL support has always assumed that the table owner will be
181 * $wgDBuser. So before we create new tables, we either need to either
182 * connect as the other user or to execute a SET ROLE command. Using a
183 * separate connection for this allows us to avoid accidental cross-module
184 * dependencies.
186 * @param string $type The type of connection to get:
187 * - create-db: A connection for creating DBs, suitable for pre-
188 * installation.
189 * - create-schema: A connection to the new DB, for creating schemas and
190 * other similar objects in the new DB.
191 * - create-tables: A connection with a role suitable for creating tables.
193 * @throws MWException
194 * @return Status object. On success, a connection object will be in the
195 * value member.
197 protected function openPgConnection( $type ) {
198 switch ( $type ) {
199 case 'create-db':
200 return $this->openConnectionToAnyDB(
201 $this->getVar( '_InstallUser' ),
202 $this->getVar( '_InstallPassword' ) );
203 case 'create-schema':
204 return $this->openConnectionWithParams(
205 $this->getVar( '_InstallUser' ),
206 $this->getVar( '_InstallPassword' ),
207 $this->getVar( 'wgDBname' ) );
208 case 'create-tables':
209 $status = $this->openPgConnection( 'create-schema' );
210 if ( $status->isOK() ) {
212 * @var $conn DatabaseBase
214 $conn = $status->value;
215 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
216 $conn->query( "SET ROLE $safeRole" );
218 return $status;
219 default:
220 throw new MWException( "Invalid special connection type: \"$type\"" );
224 public function openConnectionToAnyDB( $user, $password ) {
225 $dbs = array(
226 'template1',
227 'postgres',
229 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
230 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
232 $conn = false;
233 $status = Status::newGood();
234 foreach ( $dbs as $db ) {
235 try {
236 $conn = new DatabasePostgres(
237 $this->getVar( 'wgDBserver' ),
238 $user,
239 $password,
240 $db );
241 } catch ( DBConnectionError $error ) {
242 $conn = false;
243 $status->fatal( 'config-pg-test-error', $db,
244 $error->getMessage() );
246 if ( $conn !== false ) {
247 break;
250 if ( $conn !== false ) {
251 return Status::newGood( $conn );
252 } else {
253 return $status;
257 protected function getInstallUserPermissions() {
258 $status = $this->getPgConnection( 'create-db' );
259 if ( !$status->isOK() ) {
260 return false;
263 * @var $conn DatabaseBase
265 $conn = $status->value;
266 $superuser = $this->getVar( '_InstallUser' );
268 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
269 array( 'rolname' => $superuser ), __METHOD__ );
270 return $row;
273 protected function canCreateAccounts() {
274 $perms = $this->getInstallUserPermissions();
275 if ( !$perms ) {
276 return false;
278 return $perms->rolsuper === 't' || $perms->rolcreaterole === 't';
281 protected function isSuperUser() {
282 $perms = $this->getInstallUserPermissions();
283 if ( !$perms ) {
284 return false;
286 return $perms->rolsuper === 't';
289 public function getSettingsForm() {
290 if ( $this->canCreateAccounts() ) {
291 $noCreateMsg = false;
292 } else {
293 $noCreateMsg = 'config-db-web-no-create-privs';
295 $s = $this->getWebUserBox( $noCreateMsg );
297 return $s;
300 public function submitSettingsForm() {
301 $status = $this->submitWebUserBox();
302 if ( !$status->isOK() ) {
303 return $status;
306 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
308 if ( $same ) {
309 $exists = true;
310 } else {
311 // Check if the web user exists
312 // Connect to the database with the install user
313 $status = $this->getPgConnection( 'create-db' );
314 if ( !$status->isOK() ) {
315 return $status;
317 $exists = $status->value->roleExists( $this->getVar( 'wgDBuser' ) );
320 // Validate the create checkbox
321 if ( $this->canCreateAccounts() && !$same && !$exists ) {
322 $create = $this->getVar( '_CreateDBAccount' );
323 } else {
324 $this->setVar( '_CreateDBAccount', false );
325 $create = false;
328 if ( !$create && !$exists ) {
329 if ( $this->canCreateAccounts() ) {
330 $msg = 'config-install-user-missing-create';
331 } else {
332 $msg = 'config-install-user-missing';
334 return Status::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
337 if ( !$exists ) {
338 // No more checks to do
339 return Status::newGood();
342 // Existing web account. Test the connection.
343 $status = $this->openConnectionToAnyDB(
344 $this->getVar( 'wgDBuser' ),
345 $this->getVar( 'wgDBpassword' ) );
346 if ( !$status->isOK() ) {
347 return $status;
350 // The web user is conventionally the table owner in PostgreSQL
351 // installations. Make sure the install user is able to create
352 // objects on behalf of the web user.
353 if ( $same || $this->canCreateObjectsForWebUser() ) {
354 return Status::newGood();
355 } else {
356 return Status::newFatal( 'config-pg-not-in-role' );
361 * Returns true if the install user is able to create objects owned
362 * by the web user, false otherwise.
363 * @return bool
365 protected function canCreateObjectsForWebUser() {
366 if ( $this->isSuperUser() ) {
367 return true;
370 $status = $this->getPgConnection( 'create-db' );
371 if ( !$status->isOK() ) {
372 return false;
374 $conn = $status->value;
375 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
376 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__ );
377 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
378 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__ );
380 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
384 * Recursive helper for canCreateObjectsForWebUser().
385 * @param $conn DatabaseBase object
386 * @param int $targetMember Role ID of the member to look for
387 * @param int $group Role ID of the group to look for
388 * @param int $maxDepth Maximum recursive search depth
389 * @return bool
391 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
392 if ( $targetMember === $group ) {
393 // A role is always a member of itself
394 return true;
396 // Get all members of the given group
397 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
398 array( 'roleid' => $group ), __METHOD__ );
399 foreach ( $res as $row ) {
400 if ( $row->member == $targetMember ) {
401 // Found target member
402 return true;
404 // Recursively search each member of the group to see if the target
405 // is a member of it, up to the given maximum depth.
406 if ( $maxDepth > 0 ) {
407 if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) {
408 // Found member of member
409 return true;
413 return false;
416 public function preInstall() {
417 $createDbAccount = array(
418 'name' => 'user',
419 'callback' => array( $this, 'setupUser' ),
421 $commitCB = array(
422 'name' => 'pg-commit',
423 'callback' => array( $this, 'commitChanges' ),
425 $plpgCB = array(
426 'name' => 'pg-plpgsql',
427 'callback' => array( $this, 'setupPLpgSQL' ),
429 $schemaCB = array(
430 'name' => 'schema',
431 'callback' => array( $this, 'setupSchema' )
434 if ( $this->getVar( '_CreateDBAccount' ) ) {
435 $this->parent->addInstallStep( $createDbAccount, 'database' );
437 $this->parent->addInstallStep( $commitCB, 'interwiki' );
438 $this->parent->addInstallStep( $plpgCB, 'database' );
439 $this->parent->addInstallStep( $schemaCB, 'database' );
442 function setupDatabase() {
443 $status = $this->getPgConnection( 'create-db' );
444 if ( !$status->isOK() ) {
445 return $status;
447 $conn = $status->value;
449 $dbName = $this->getVar( 'wgDBname' );
451 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
452 array( 'datname' => $dbName ), __METHOD__ );
453 if ( !$exists ) {
454 $safedb = $conn->addIdentifierQuotes( $dbName );
455 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
457 return Status::newGood();
460 function setupSchema() {
461 // Get a connection to the target database
462 $status = $this->getPgConnection( 'create-schema' );
463 if ( !$status->isOK() ) {
464 return $status;
466 $conn = $status->value;
468 // Create the schema if necessary
469 $schema = $this->getVar( 'wgDBmwschema' );
470 $safeschema = $conn->addIdentifierQuotes( $schema );
471 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
472 if ( !$conn->schemaExists( $schema ) ) {
473 try {
474 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
475 } catch ( DBQueryError $e ) {
476 return Status::newFatal( 'config-install-pg-schema-failed',
477 $this->getVar( '_InstallUser' ), $schema );
481 // Select the new schema in the current connection
482 $conn->determineCoreSchema( $schema );
483 return Status::newGood();
486 function commitChanges() {
487 $this->db->commit( __METHOD__ );
488 return Status::newGood();
491 function setupUser() {
492 if ( !$this->getVar( '_CreateDBAccount' ) ) {
493 return Status::newGood();
496 $status = $this->getPgConnection( 'create-db' );
497 if ( !$status->isOK() ) {
498 return $status;
500 $conn = $status->value;
502 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
503 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
505 // Check if the user already exists
506 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
507 if ( !$userExists ) {
508 // Create the user
509 try {
510 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
512 // If the install user is not a superuser, we need to make the install
513 // user a member of the new user's group, so that the install user will
514 // be able to create a schema and other objects on behalf of the new user.
515 if ( !$this->isSuperUser() ) {
516 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
519 $conn->query( $sql, __METHOD__ );
520 } catch ( DBQueryError $e ) {
521 return Status::newFatal( 'config-install-user-create-failed',
522 $this->getVar( 'wgDBuser' ), $e->getMessage() );
526 return Status::newGood();
529 function getLocalSettings() {
530 $port = $this->getVar( 'wgDBport' );
531 $schema = $this->getVar( 'wgDBmwschema' );
532 return
533 "# Postgres specific settings
534 \$wgDBport = \"{$port}\";
535 \$wgDBmwschema = \"{$schema}\";";
538 public function preUpgrade() {
539 global $wgDBuser, $wgDBpassword;
541 # Normal user and password are selected after this step, so for now
542 # just copy these two
543 $wgDBuser = $this->getVar( '_InstallUser' );
544 $wgDBpassword = $this->getVar( '_InstallPassword' );
547 public function createTables() {
548 $schema = $this->getVar( 'wgDBmwschema' );
550 $status = $this->getConnection();
551 if ( !$status->isOK() ) {
552 return $status;
556 * @var $conn DatabaseBase
558 $conn = $status->value;
560 if ( $conn->tableExists( 'archive' ) ) {
561 $status->warning( 'config-install-tables-exist' );
562 $this->enableLB();
563 return $status;
566 $conn->begin( __METHOD__ );
568 if ( !$conn->schemaExists( $schema ) ) {
569 $status->fatal( 'config-install-pg-schema-not-exist' );
570 return $status;
572 $error = $conn->sourceFile( $conn->getSchemaPath() );
573 if ( $error !== true ) {
574 $conn->reportQueryError( $error, 0, '', __METHOD__ );
575 $conn->rollback( __METHOD__ );
576 $status->fatal( 'config-install-tables-failed', $error );
577 } else {
578 $conn->commit( __METHOD__ );
580 // Resume normal operations
581 if ( $status->isOk() ) {
582 $this->enableLB();
584 return $status;
587 public function setupPLpgSQL() {
588 // Connect as the install user, since it owns the database and so is
589 // the user that needs to run "CREATE LANGAUGE"
590 $status = $this->getPgConnection( 'create-schema' );
591 if ( !$status->isOK() ) {
592 return $status;
595 * @var $conn DatabaseBase
597 $conn = $status->value;
599 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
600 array( 'lanname' => 'plpgsql' ), __METHOD__ );
601 if ( $exists ) {
602 // Already exists, nothing to do
603 return Status::newGood();
606 // plpgsql is not installed, but if we have a pg_pltemplate table, we
607 // should be able to create it
608 $exists = $conn->selectField(
609 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
611 array(
612 'pg_namespace.oid=relnamespace',
613 'nspname' => 'pg_catalog',
614 'relname' => 'pg_pltemplate',
616 __METHOD__ );
617 if ( $exists ) {
618 try {
619 $conn->query( 'CREATE LANGUAGE plpgsql' );
620 } catch ( DBQueryError $e ) {
621 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
623 } else {
624 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
626 return Status::newGood();