Merge "Revert "Convert mediawiki.toc and mediawiki.user to using mw.cookie""
[mediawiki.git] / includes / installer / PostgresInstaller.php
blobb18fe944873aa81570da3fced9018a260227b5fa
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 public $minimumVersion = '8.3';
46 public $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(
60 'wgDBserver',
61 'config-db-host',
62 array(),
63 $this->parent->getHelpBox( 'config-db-host-help' )
64 ) .
65 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
66 Html::openElement( 'fieldset' ) .
67 Html::element( 'legend', array(), wfMessage( 'config-db-wiki-settings' )->text() ) .
68 $this->getTextBox(
69 'wgDBname',
70 'config-db-name',
71 array(),
72 $this->parent->getHelpBox( 'config-db-name-help' )
73 ) .
74 $this->getTextBox(
75 'wgDBmwschema',
76 'config-db-schema',
77 array(),
78 $this->parent->getHelpBox( 'config-db-schema-help' )
79 ) .
80 Html::closeElement( 'fieldset' ) .
81 $this->getInstallUserBox();
84 function submitConnectForm() {
85 // Get variables from the request
86 $newValues = $this->setVarsFromRequest( array(
87 'wgDBserver', 'wgDBport', 'wgDBname', 'wgDBmwschema',
88 '_InstallUser', '_InstallPassword'
89 ) );
91 // Validate them
92 $status = Status::newGood();
93 if ( !strlen( $newValues['wgDBname'] ) ) {
94 $status->fatal( 'config-missing-db-name' );
95 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
96 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
98 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
99 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
101 if ( !strlen( $newValues['_InstallUser'] ) ) {
102 $status->fatal( 'config-db-username-empty' );
104 if ( !strlen( $newValues['_InstallPassword'] ) ) {
105 $status->fatal( 'config-db-password-empty', $newValues['_InstallUser'] );
108 // Submit user box
109 if ( $status->isOK() ) {
110 $status->merge( $this->submitInstallUserBox() );
112 if ( !$status->isOK() ) {
113 return $status;
116 $status = $this->getPgConnection( 'create-db' );
117 if ( !$status->isOK() ) {
118 return $status;
121 * @var $conn DatabaseBase
123 $conn = $status->value;
125 // Check version
126 $version = $conn->getServerVersion();
127 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
128 return Status::newFatal( 'config-postgres-old', $this->minimumVersion, $version );
131 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
132 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
134 return Status::newGood();
137 public function getConnection() {
138 $status = $this->getPgConnection( 'create-tables' );
139 if ( $status->isOK() ) {
140 $this->db = $status->value;
143 return $status;
146 public function openConnection() {
147 return $this->openPgConnection( 'create-tables' );
151 * Open a PG connection with given parameters
152 * @param string $user User name
153 * @param string $password Password
154 * @param string $dbName Database name
155 * @param string $schema Database schema
156 * @return Status
158 protected function openConnectionWithParams( $user, $password, $dbName, $schema ) {
159 $status = Status::newGood();
160 try {
161 $db = DatabaseBase::factory( 'postgres', array(
162 'host' => $this->getVar( 'wgDBserver' ),
163 'user' => $user,
164 'password' => $password,
165 'dbname' => $dbName,
166 'schema' => $schema ) );
167 $status->value = $db;
168 } catch ( DBConnectionError $e ) {
169 $status->fatal( 'config-connection-error', $e->getMessage() );
172 return $status;
176 * Get a special type of connection
177 * @param string $type See openPgConnection() for details.
178 * @return Status
180 protected function getPgConnection( $type ) {
181 if ( isset( $this->pgConns[$type] ) ) {
182 return Status::newGood( $this->pgConns[$type] );
184 $status = $this->openPgConnection( $type );
186 if ( $status->isOK() ) {
188 * @var $conn DatabaseBase
190 $conn = $status->value;
191 $conn->clearFlag( DBO_TRX );
192 $conn->commit( __METHOD__ );
193 $this->pgConns[$type] = $conn;
196 return $status;
200 * Get a connection of a specific PostgreSQL-specific type. Connections
201 * of a given type are cached.
203 * PostgreSQL lacks cross-database operations, so after the new database is
204 * created, you need to make a separate connection to connect to that
205 * database and add tables to it.
207 * New tables are owned by the user that creates them, and MediaWiki's
208 * PostgreSQL support has always assumed that the table owner will be
209 * $wgDBuser. So before we create new tables, we either need to either
210 * connect as the other user or to execute a SET ROLE command. Using a
211 * separate connection for this allows us to avoid accidental cross-module
212 * dependencies.
214 * @param string $type The type of connection to get:
215 * - create-db: A connection for creating DBs, suitable for pre-
216 * installation.
217 * - create-schema: A connection to the new DB, for creating schemas and
218 * other similar objects in the new DB.
219 * - create-tables: A connection with a role suitable for creating tables.
221 * @throws MWException
222 * @return Status On success, a connection object will be in the value member.
224 protected function openPgConnection( $type ) {
225 switch ( $type ) {
226 case 'create-db':
227 return $this->openConnectionToAnyDB(
228 $this->getVar( '_InstallUser' ),
229 $this->getVar( '_InstallPassword' ) );
230 case 'create-schema':
231 return $this->openConnectionWithParams(
232 $this->getVar( '_InstallUser' ),
233 $this->getVar( '_InstallPassword' ),
234 $this->getVar( 'wgDBname' ),
235 $this->getVar( 'wgDBmwschema' ) );
236 case 'create-tables':
237 $status = $this->openPgConnection( 'create-schema' );
238 if ( $status->isOK() ) {
240 * @var $conn DatabaseBase
242 $conn = $status->value;
243 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
244 $conn->query( "SET ROLE $safeRole" );
247 return $status;
248 default:
249 throw new MWException( "Invalid special connection type: \"$type\"" );
253 public function openConnectionToAnyDB( $user, $password ) {
254 $dbs = array(
255 'template1',
256 'postgres',
258 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
259 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
261 $conn = false;
262 $status = Status::newGood();
263 foreach ( $dbs as $db ) {
264 try {
265 $p = array(
266 'host' => $this->getVar( 'wgDBserver' ),
267 'user' => $user,
268 'password' => $password,
269 'dbname' => $db
271 $conn = DatabaseBase::factory( 'postgres', $p );
272 } catch ( DBConnectionError $error ) {
273 $conn = false;
274 $status->fatal( 'config-pg-test-error', $db,
275 $error->getMessage() );
277 if ( $conn !== false ) {
278 break;
281 if ( $conn !== false ) {
282 return Status::newGood( $conn );
283 } else {
284 return $status;
288 protected function getInstallUserPermissions() {
289 $status = $this->getPgConnection( 'create-db' );
290 if ( !$status->isOK() ) {
291 return false;
294 * @var $conn DatabaseBase
296 $conn = $status->value;
297 $superuser = $this->getVar( '_InstallUser' );
299 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
300 array( 'rolname' => $superuser ), __METHOD__ );
302 return $row;
305 protected function canCreateAccounts() {
306 $perms = $this->getInstallUserPermissions();
307 if ( !$perms ) {
308 return false;
311 return $perms->rolsuper === 't' || $perms->rolcreaterole === 't';
314 protected function isSuperUser() {
315 $perms = $this->getInstallUserPermissions();
316 if ( !$perms ) {
317 return false;
320 return $perms->rolsuper === 't';
323 public function getSettingsForm() {
324 if ( $this->canCreateAccounts() ) {
325 $noCreateMsg = false;
326 } else {
327 $noCreateMsg = 'config-db-web-no-create-privs';
329 $s = $this->getWebUserBox( $noCreateMsg );
331 return $s;
334 public function submitSettingsForm() {
335 $status = $this->submitWebUserBox();
336 if ( !$status->isOK() ) {
337 return $status;
340 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
342 if ( $same ) {
343 $exists = true;
344 } else {
345 // Check if the web user exists
346 // Connect to the database with the install user
347 $status = $this->getPgConnection( 'create-db' );
348 if ( !$status->isOK() ) {
349 return $status;
351 $exists = $status->value->roleExists( $this->getVar( 'wgDBuser' ) );
354 // Validate the create checkbox
355 if ( $this->canCreateAccounts() && !$same && !$exists ) {
356 $create = $this->getVar( '_CreateDBAccount' );
357 } else {
358 $this->setVar( '_CreateDBAccount', false );
359 $create = false;
362 if ( !$create && !$exists ) {
363 if ( $this->canCreateAccounts() ) {
364 $msg = 'config-install-user-missing-create';
365 } else {
366 $msg = 'config-install-user-missing';
369 return Status::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
372 if ( !$exists ) {
373 // No more checks to do
374 return Status::newGood();
377 // Existing web account. Test the connection.
378 $status = $this->openConnectionToAnyDB(
379 $this->getVar( 'wgDBuser' ),
380 $this->getVar( 'wgDBpassword' ) );
381 if ( !$status->isOK() ) {
382 return $status;
385 // The web user is conventionally the table owner in PostgreSQL
386 // installations. Make sure the install user is able to create
387 // objects on behalf of the web user.
388 if ( $same || $this->canCreateObjectsForWebUser() ) {
389 return Status::newGood();
390 } else {
391 return Status::newFatal( 'config-pg-not-in-role' );
396 * Returns true if the install user is able to create objects owned
397 * by the web user, false otherwise.
398 * @return bool
400 protected function canCreateObjectsForWebUser() {
401 if ( $this->isSuperUser() ) {
402 return true;
405 $status = $this->getPgConnection( 'create-db' );
406 if ( !$status->isOK() ) {
407 return false;
409 $conn = $status->value;
410 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
411 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__ );
412 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
413 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__ );
415 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
419 * Recursive helper for canCreateObjectsForWebUser().
420 * @param DatabaseBase $conn
421 * @param int $targetMember Role ID of the member to look for
422 * @param int $group Role ID of the group to look for
423 * @param int $maxDepth Maximum recursive search depth
424 * @return bool
426 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
427 if ( $targetMember === $group ) {
428 // A role is always a member of itself
429 return true;
431 // Get all members of the given group
432 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
433 array( 'roleid' => $group ), __METHOD__ );
434 foreach ( $res as $row ) {
435 if ( $row->member == $targetMember ) {
436 // Found target member
437 return true;
439 // Recursively search each member of the group to see if the target
440 // is a member of it, up to the given maximum depth.
441 if ( $maxDepth > 0 ) {
442 if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) {
443 // Found member of member
444 return true;
449 return false;
452 public function preInstall() {
453 $createDbAccount = array(
454 'name' => 'user',
455 'callback' => array( $this, 'setupUser' ),
457 $commitCB = array(
458 'name' => 'pg-commit',
459 'callback' => array( $this, 'commitChanges' ),
461 $plpgCB = array(
462 'name' => 'pg-plpgsql',
463 'callback' => array( $this, 'setupPLpgSQL' ),
465 $schemaCB = array(
466 'name' => 'schema',
467 'callback' => array( $this, 'setupSchema' )
470 if ( $this->getVar( '_CreateDBAccount' ) ) {
471 $this->parent->addInstallStep( $createDbAccount, 'database' );
473 $this->parent->addInstallStep( $commitCB, 'interwiki' );
474 $this->parent->addInstallStep( $plpgCB, 'database' );
475 $this->parent->addInstallStep( $schemaCB, 'database' );
478 function setupDatabase() {
479 $status = $this->getPgConnection( 'create-db' );
480 if ( !$status->isOK() ) {
481 return $status;
483 $conn = $status->value;
485 $dbName = $this->getVar( 'wgDBname' );
487 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
488 array( 'datname' => $dbName ), __METHOD__ );
489 if ( !$exists ) {
490 $safedb = $conn->addIdentifierQuotes( $dbName );
491 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
494 return Status::newGood();
497 function setupSchema() {
498 // Get a connection to the target database
499 $status = $this->getPgConnection( 'create-schema' );
500 if ( !$status->isOK() ) {
501 return $status;
503 $conn = $status->value;
505 // Create the schema if necessary
506 $schema = $this->getVar( 'wgDBmwschema' );
507 $safeschema = $conn->addIdentifierQuotes( $schema );
508 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
509 if ( !$conn->schemaExists( $schema ) ) {
510 try {
511 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
512 } catch ( DBQueryError $e ) {
513 return Status::newFatal( 'config-install-pg-schema-failed',
514 $this->getVar( '_InstallUser' ), $schema );
518 // Select the new schema in the current connection
519 $conn->determineCoreSchema( $schema );
521 return Status::newGood();
524 function commitChanges() {
525 $this->db->commit( __METHOD__ );
527 return Status::newGood();
530 function setupUser() {
531 if ( !$this->getVar( '_CreateDBAccount' ) ) {
532 return Status::newGood();
535 $status = $this->getPgConnection( 'create-db' );
536 if ( !$status->isOK() ) {
537 return $status;
539 $conn = $status->value;
541 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
542 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
544 // Check if the user already exists
545 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
546 if ( !$userExists ) {
547 // Create the user
548 try {
549 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
551 // If the install user is not a superuser, we need to make the install
552 // user a member of the new user's group, so that the install user will
553 // be able to create a schema and other objects on behalf of the new user.
554 if ( !$this->isSuperUser() ) {
555 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
558 $conn->query( $sql, __METHOD__ );
559 } catch ( DBQueryError $e ) {
560 return Status::newFatal( 'config-install-user-create-failed',
561 $this->getVar( 'wgDBuser' ), $e->getMessage() );
565 return Status::newGood();
568 function getLocalSettings() {
569 $port = $this->getVar( 'wgDBport' );
570 $schema = $this->getVar( 'wgDBmwschema' );
572 return "# Postgres specific settings
573 \$wgDBport = \"{$port}\";
574 \$wgDBmwschema = \"{$schema}\";";
577 public function preUpgrade() {
578 global $wgDBuser, $wgDBpassword;
580 # Normal user and password are selected after this step, so for now
581 # just copy these two
582 $wgDBuser = $this->getVar( '_InstallUser' );
583 $wgDBpassword = $this->getVar( '_InstallPassword' );
586 public function createTables() {
587 $schema = $this->getVar( 'wgDBmwschema' );
589 $status = $this->getConnection();
590 if ( !$status->isOK() ) {
591 return $status;
595 * @var $conn DatabaseBase
597 $conn = $status->value;
599 if ( $conn->tableExists( 'archive' ) ) {
600 $status->warning( 'config-install-tables-exist' );
601 $this->enableLB();
603 return $status;
606 $conn->begin( __METHOD__ );
608 if ( !$conn->schemaExists( $schema ) ) {
609 $status->fatal( 'config-install-pg-schema-not-exist' );
611 return $status;
613 $error = $conn->sourceFile( $conn->getSchemaPath() );
614 if ( $error !== true ) {
615 $conn->reportQueryError( $error, 0, '', __METHOD__ );
616 $conn->rollback( __METHOD__ );
617 $status->fatal( 'config-install-tables-failed', $error );
618 } else {
619 $conn->commit( __METHOD__ );
621 // Resume normal operations
622 if ( $status->isOk() ) {
623 $this->enableLB();
626 return $status;
629 public function getGlobalDefaults() {
630 // The default $wgDBmwschema is null, which breaks Postgres and other DBMSes that require
631 // the use of a schema, so we need to set it here
632 return array_merge( parent::getGlobalDefaults(), array(
633 'wgDBmwschema' => 'mediawiki',
634 ) );
637 public function setupPLpgSQL() {
638 // Connect as the install user, since it owns the database and so is
639 // the user that needs to run "CREATE LANGAUGE"
640 $status = $this->getPgConnection( 'create-schema' );
641 if ( !$status->isOK() ) {
642 return $status;
645 * @var $conn DatabaseBase
647 $conn = $status->value;
649 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
650 array( 'lanname' => 'plpgsql' ), __METHOD__ );
651 if ( $exists ) {
652 // Already exists, nothing to do
653 return Status::newGood();
656 // plpgsql is not installed, but if we have a pg_pltemplate table, we
657 // should be able to create it
658 $exists = $conn->selectField(
659 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
661 array(
662 'pg_namespace.oid=relnamespace',
663 'nspname' => 'pg_catalog',
664 'relname' => 'pg_pltemplate',
666 __METHOD__ );
667 if ( $exists ) {
668 try {
669 $conn->query( 'CREATE LANGUAGE plpgsql' );
670 } catch ( DBQueryError $e ) {
671 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
673 } else {
674 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
677 return Status::newGood();