Make Pg installer work in the “common” case: follow up r89821 so that $exists can...
[lhc/web/wiklou.git] / includes / installer / PostgresInstaller.php
1 <?php
2 /**
3 * PostgreSQL-specific installer.
4 *
5 * @file
6 * @ingroup Deployment
7 */
8
9 /**
10 * Class for setting up the MediaWiki database using Postgres.
11 *
12 * @ingroup Deployment
13 * @since 1.17
14 */
15 class PostgresInstaller extends DatabaseInstaller {
16
17 protected $globalNames = array(
18 'wgDBserver',
19 'wgDBport',
20 'wgDBname',
21 'wgDBuser',
22 'wgDBpassword',
23 'wgDBmwschema',
24 );
25
26 protected $internalDefaults = array(
27 '_InstallUser' => 'postgres',
28 );
29
30 var $minimumVersion = '8.3';
31 var $maxRoleSearchDepth = 5;
32
33 protected $pgConns = array();
34
35 function getName() {
36 return 'postgres';
37 }
38
39 public function isCompiled() {
40 return self::checkExtension( 'pgsql' );
41 }
42
43 function getConnectForm() {
44 return
45 $this->getTextBox( 'wgDBserver', 'config-db-host', array(), $this->parent->getHelpBox( 'config-db-host-help' ) ) .
46 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
47 Html::openElement( 'fieldset' ) .
48 Html::element( 'legend', array(), wfMsg( 'config-db-wiki-settings' ) ) .
49 $this->getTextBox( 'wgDBname', 'config-db-name', array(), $this->parent->getHelpBox( 'config-db-name-help' ) ) .
50 $this->getTextBox( 'wgDBmwschema', 'config-db-schema', array(), $this->parent->getHelpBox( 'config-db-schema-help' ) ) .
51 Html::closeElement( 'fieldset' ) .
52 $this->getInstallUserBox();
53 }
54
55 function submitConnectForm() {
56 // Get variables from the request
57 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBport',
58 'wgDBname', 'wgDBmwschema' ) );
59
60 // Validate them
61 $status = Status::newGood();
62 if ( !strlen( $newValues['wgDBname'] ) ) {
63 $status->fatal( 'config-missing-db-name' );
64 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
65 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
66 }
67 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
68 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
69 }
70
71 // Submit user box
72 if ( $status->isOK() ) {
73 $status->merge( $this->submitInstallUserBox() );
74 }
75 if ( !$status->isOK() ) {
76 return $status;
77 }
78
79 $status = $this->getPgConnection( 'create-db' );
80 if ( !$status->isOK() ) {
81 return $status;
82 }
83 $conn = $status->value;
84
85 // Check version
86 $version = $conn->getServerVersion();
87 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
88 return Status::newFatal( 'config-postgres-old', $this->minimumVersion, $version );
89 }
90
91 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
92 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
93 return Status::newGood();
94 }
95
96 public function getConnection() {
97 $status = $this->getPgConnection( 'create-tables' );
98 if ( $status->isOK() ) {
99 $this->db = $status->value;
100 }
101 return $status;
102 }
103
104 public function openConnection() {
105 return $this->openPgConnection( 'create-tables' );
106 }
107
108 /**
109 * Open a PG connection with given parameters
110 * @param $user User name
111 * @param $password Password
112 * @param $dbName Database name
113 * @return Status
114 */
115 protected function openConnectionWithParams( $user, $password, $dbName ) {
116 $status = Status::newGood();
117 try {
118 $db = new DatabasePostgres(
119 $this->getVar( 'wgDBserver' ),
120 $user,
121 $password,
122 $dbName);
123 $status->value = $db;
124 } catch ( DBConnectionError $e ) {
125 $status->fatal( 'config-connection-error', $e->getMessage() );
126 }
127 return $status;
128 }
129
130 /**
131 * Get a special type of connection
132 * @param $type See openPgConnection() for details.
133 * @return Status
134 */
135 protected function getPgConnection( $type ) {
136 if ( isset( $this->pgConns[$type] ) ) {
137 return Status::newGood( $this->pgConns[$type] );
138 }
139 $status = $this->openPgConnection( $type );
140
141 if ( $status->isOK() ) {
142 $conn = $status->value;
143 $conn->clearFlag( DBO_TRX );
144 $conn->commit();
145 $this->pgConns[$type] = $conn;
146 }
147 return $status;
148 }
149
150 /**
151 * Get a connection of a specific PostgreSQL-specific type. Connections
152 * of a given type are cached.
153 *
154 * PostgreSQL lacks cross-database operations, so after the new database is
155 * created, you need to make a separate connection to connect to that
156 * database and add tables to it.
157 *
158 * New tables are owned by the user that creates them, and MediaWiki's
159 * PostgreSQL support has always assumed that the table owner will be
160 * $wgDBuser. So before we create new tables, we either need to either
161 * connect as the other user or to execute a SET ROLE command. Using a
162 * separate connection for this allows us to avoid accidental cross-module
163 * dependencies.
164 *
165 * @param $type The type of connection to get:
166 * - create-db: A connection for creating DBs, suitable for pre-
167 * installation.
168 * - create-schema: A connection to the new DB, for creating schemas and
169 * other similar objects in the new DB.
170 * - create-tables: A connection with a role suitable for creating tables.
171 *
172 * @return A Status object. On success, a connection object will be in the
173 * value member.
174 */
175 protected function openPgConnection( $type ) {
176 switch ( $type ) {
177 case 'create-db':
178 return $this->openConnectionToAnyDB(
179 $this->getVar( '_InstallUser' ),
180 $this->getVar( '_InstallPassword' ) );
181 case 'create-schema':
182 return $this->openConnectionWithParams(
183 $this->getVar( '_InstallUser' ),
184 $this->getVar( '_InstallPassword' ),
185 $this->getVar( 'wgDBname' ) );
186 case 'create-tables':
187 $status = $this->openPgConnection( 'create-schema' );
188 if ( $status->isOK() ) {
189 $conn = $status->value;
190 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
191 $conn->query( "SET ROLE $safeRole" );
192 }
193 return $status;
194 default:
195 throw new MWException( "Invalid special connection type: \"$type\"" );
196 }
197 }
198
199 public function openConnectionToAnyDB( $user, $password ) {
200 $dbs = array(
201 'template1',
202 'postgres',
203 );
204 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
205 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
206 }
207 $status = Status::newGood();
208 foreach ( $dbs as $db ) {
209 try {
210 $conn = new DatabasePostgres(
211 $this->getVar( 'wgDBserver' ),
212 $user,
213 $password,
214 $db );
215 } catch ( DBConnectionError $error ) {
216 $conn = false;
217 $status->fatal( 'config-pg-test-error', $db,
218 $error->getMessage() );
219 }
220 if ( $conn !== false ) {
221 break;
222 }
223 }
224 if ( $conn !== false ) {
225 return Status::newGood( $conn );
226 } else {
227 return $status;
228 }
229 }
230
231 protected function getInstallUserPermissions() {
232 $status = $this->getPgConnection( 'create-db' );
233 if ( !$status->isOK() ) {
234 return false;
235 }
236 $conn = $status->value;
237 $superuser = $this->getVar( '_InstallUser' );
238
239 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
240 array( 'rolname' => $superuser ), __METHOD__ );
241 return $row;
242 }
243
244 protected function canCreateAccounts() {
245 $perms = $this->getInstallUserPermissions();
246 if ( !$perms ) {
247 return false;
248 }
249 return $perms->rolsuper === 't' || $perms->rolcreaterole === 't';
250 }
251
252 protected function isSuperUser() {
253 $perms = $this->getInstallUserPermissions();
254 if ( !$perms ) {
255 return false;
256 }
257 return $perms->rolsuper === 't';
258 }
259
260 public function getSettingsForm() {
261 if ( $this->canCreateAccounts() ) {
262 $noCreateMsg = false;
263 } else {
264 $noCreateMsg = 'config-db-web-no-create-privs';
265 }
266 $s = $this->getWebUserBox( $noCreateMsg );
267
268 return $s;
269 }
270
271 public function submitSettingsForm() {
272 $status = $this->submitWebUserBox();
273 if ( !$status->isOK() ) {
274 return $status;
275 }
276
277 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
278
279 // Check if the web user exists
280 // Connect to the database with the install user
281 $status = $this->getPgConnection( 'create-db' );
282 if ( !$status->isOK() ) {
283 return $status;
284 }
285 $exists = $status->value->roleExists( $this->getVar( 'wgDBuser' ) );
286
287 // Validate the create checkbox
288 if ( $this->canCreateAccounts() && !$same && !$exists ) {
289 $create = $this->getVar( '_CreateDBAccount' );
290 } else {
291 $this->setVar( '_CreateDBAccount', false );
292 $create = false;
293 }
294
295 if ( !$create && !$exists ) {
296 if ( $this->canCreateAccounts() ) {
297 $msg = 'config-install-user-missing-create';
298 } else {
299 $msg = 'config-install-user-missing';
300 }
301 return Status::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
302 }
303
304 if ( !$exists ) {
305 // No more checks to do
306 return Status::newGood();
307 }
308
309 // Existing web account. Test the connection.
310 $status = $this->openConnectionToAnyDB(
311 $this->getVar( 'wgDBuser' ),
312 $this->getVar( 'wgDBpassword' ) );
313 if ( !$status->isOK() ) {
314 return $status;
315 }
316
317 // The web user is conventionally the table owner in PostgreSQL
318 // installations. Make sure the install user is able to create
319 // objects on behalf of the web user.
320 if ( $this->canCreateObjectsForWebUser() ) {
321 return Status::newGood();
322 } else {
323 return Status::newFatal( 'config-pg-not-in-role' );
324 }
325 }
326
327 /**
328 * Returns true if the install user is able to create objects owned
329 * by the web user, false otherwise.
330 */
331 protected function canCreateObjectsForWebUser() {
332 if ( $this->isSuperUser() ) {
333 return true;
334 }
335
336 $status = $this->getPgConnection( 'create-db' );
337 if ( !$status->isOK() ) {
338 return false;
339 }
340 $conn = $status->value;
341 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
342 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__ );
343 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
344 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__ );
345
346 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
347 }
348
349 /**
350 * Recursive helper for canCreateObjectsForWebUser().
351 * @param $conn Database object
352 * @param $targetMember Role ID of the member to look for
353 * @param $group Role ID of the group to look for
354 * @param $maxDepth Maximum recursive search depth
355 */
356 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
357 if ( $targetMember === $group ) {
358 // A role is always a member of itself
359 return true;
360 }
361 // Get all members of the given group
362 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
363 array( 'roleid' => $group ), __METHOD__ );
364 foreach ( $res as $row ) {
365 if ( $row->member == $targetMember ) {
366 // Found target member
367 return true;
368 }
369 // Recursively search each member of the group to see if the target
370 // is a member of it, up to the given maximum depth.
371 if ( $maxDepth > 0 ) {
372 if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) {
373 // Found member of member
374 return true;
375 }
376 }
377 }
378 return false;
379 }
380
381 public function preInstall() {
382 $commitCB = array(
383 'name' => 'pg-commit',
384 'callback' => array( $this, 'commitChanges' ),
385 );
386 $plpgCB = array(
387 'name' => 'pg-plpgsql',
388 'callback' => array( $this, 'setupPLpgSQL' ),
389 );
390 $schemaCB = array(
391 'name' => 'schema',
392 'callback' => array( $this, 'setupSchema' )
393 );
394 $this->parent->addInstallStep( $commitCB, 'interwiki' );
395 $this->parent->addInstallStep( $plpgCB, 'database' );
396 $this->parent->addInstallStep( $schemaCB, 'database' );
397 if( $this->getVar( '_CreateDBAccount' ) ) {
398 $this->parent->addInstallStep( array(
399 'name' => 'user',
400 'callback' => array( $this, 'setupUser' ),
401 ) );
402 }
403 }
404
405 function setupDatabase() {
406 $status = $this->getPgConnection( 'create-db' );
407 if ( !$status->isOK() ) {
408 return $status;
409 }
410 $conn = $status->value;
411
412 $dbName = $this->getVar( 'wgDBname' );
413 $schema = $this->getVar( 'wgDBmwschema' );
414 $user = $this->getVar( 'wgDBuser' );
415 $safeschema = $conn->addIdentifierQuotes( $schema );
416 $safeuser = $conn->addIdentifierQuotes( $user );
417
418 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
419 array( 'datname' => $dbName ), __METHOD__ );
420 if ( !$exists ) {
421 $safedb = $conn->addIdentifierQuotes( $dbName );
422 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
423 }
424 return Status::newGood();
425 }
426
427 function setupSchema() {
428 // Get a connection to the target database
429 $status = $this->getPgConnection( 'create-schema' );
430 if ( !$status->isOK() ) {
431 return $status;
432 }
433 $conn = $status->value;
434
435 // Create the schema if necessary
436 $schema = $this->getVar( 'wgDBmwschema' );
437 $safeschema = $conn->addIdentifierQuotes( $schema );
438 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
439 if( !$conn->schemaExists( $schema ) ) {
440 try {
441 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
442 } catch ( DBQueryError $e ) {
443 return Status::newFatal( 'config-install-pg-schema-failed',
444 $this->getVar( '_InstallUser' ), $schema );
445 }
446 }
447
448 // If we created a user, alter it now to search the new schema by default
449 if ( $this->getVar( '_CreateDBAccount' ) ) {
450 $conn->query( "ALTER ROLE $safeuser SET search_path = $safeschema, public",
451 __METHOD__ );
452 }
453
454 // Select the new schema in the current connection
455 $conn->query( "SET search_path = $safeschema" );
456 return Status::newGood();
457 }
458
459 function commitChanges() {
460 $this->db->query( 'COMMIT' );
461 return Status::newGood();
462 }
463
464 function setupUser() {
465 if ( !$this->getVar( '_CreateDBAccount' ) ) {
466 return Status::newGood();
467 }
468
469 $status = $this->getPgConnection( 'create-db' );
470 if ( !$status->isOK() ) {
471 return $status;
472 }
473 $conn = $status->value;
474
475 $schema = $this->getVar( 'wgDBmwschema' );
476 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
477 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
478 $safeschema = $conn->addIdentifierQuotes( $schema );
479
480 // Check if the user already exists
481 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
482 if ( !$userExists ) {
483 // Create the user
484 try {
485 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
486
487 // If the install user is not a superuser, we need to make the install
488 // user a member of the new user's group, so that the install user will
489 // be able to create a schema and other objects on behalf of the new user.
490 if ( !$this->isSuperUser() ) {
491 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
492 }
493
494 $conn->query( $sql, __METHOD__ );
495 } catch ( DBQueryError $e ) {
496 return Status::newFatal( 'config-install-user-create-failed',
497 $this->getVar( 'wgDBuser' ), $e->getMessage() );
498 }
499 }
500
501 return Status::newGood();
502 }
503
504 function getLocalSettings() {
505 $port = $this->getVar( 'wgDBport' );
506 $schema = $this->getVar( 'wgDBmwschema' );
507 return
508 "# Postgres specific settings
509 \$wgDBport = \"{$port}\";
510 \$wgDBmwschema = \"{$schema}\";";
511 }
512
513 public function preUpgrade() {
514 global $wgDBuser, $wgDBpassword;
515
516 # Normal user and password are selected after this step, so for now
517 # just copy these two
518 $wgDBuser = $this->getVar( '_InstallUser' );
519 $wgDBpassword = $this->getVar( '_InstallPassword' );
520 }
521
522 public function createTables() {
523 $schema = $this->getVar( 'wgDBmwschema' );
524
525 $status = $this->getConnection();
526 if ( !$status->isOK() ) {
527 return $status;
528 }
529 $conn = $status->value;
530
531 if( $conn->tableExists( 'user' ) ) {
532 $status->warning( 'config-install-tables-exist' );
533 return $status;
534 }
535
536 $conn->begin( __METHOD__ );
537
538 if( !$conn->schemaExists( $schema ) ) {
539 $status->fatal( 'config-install-pg-schema-not-exist' );
540 return $status;
541 }
542 $error = $conn->sourceFile( $conn->getSchema() );
543 if( $error !== true ) {
544 $conn->reportQueryError( $error, 0, '', __METHOD__ );
545 $conn->rollback( __METHOD__ );
546 $status->fatal( 'config-install-tables-failed', $error );
547 } else {
548 $conn->commit( __METHOD__ );
549 }
550 // Resume normal operations
551 if( $status->isOk() ) {
552 $this->enableLB();
553 }
554 return $status;
555 }
556
557 public function setupPLpgSQL() {
558 // Connect as the install user, since it owns the database and so is
559 // the user that needs to run "CREATE LANGAUGE"
560 $status = $this->getPgConnection( 'create-schema' );
561 if ( !$status->isOK() ) {
562 return $status;
563 }
564 $conn = $status->value;
565
566 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
567 array( 'lanname' => 'plpgsql' ), __METHOD__ );
568 if ( $exists ) {
569 // Already exists, nothing to do
570 return Status::newGood();
571 }
572
573 // plpgsql is not installed, but if we have a pg_pltemplate table, we
574 // should be able to create it
575 $exists = $conn->selectField(
576 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
577 1,
578 array(
579 'pg_namespace.oid=relnamespace',
580 'nspname' => 'pg_catalog',
581 'relname' => 'pg_pltemplate',
582 ),
583 __METHOD__ );
584 if ( $exists ) {
585 try {
586 $conn->query( 'CREATE LANGUAGE plpgsql' );
587 } catch ( DBQueryError $e ) {
588 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
589 }
590 } else {
591 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
592 }
593 return Status::newGood();
594 }
595 }