Fix for r89821, r89839: we can skip certain tests if the web user is the same as...
[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 if ( $same ) {
280 $exists = true;
281 } else {
282 // Check if the web user exists
283 // Connect to the database with the install user
284 $status = $this->getPgConnection( 'create-db' );
285 if ( !$status->isOK() ) {
286 return $status;
287 }
288 $exists = $status->value->roleExists( $this->getVar( 'wgDBuser' ) );
289 }
290
291 // Validate the create checkbox
292 if ( $this->canCreateAccounts() && !$same && !$exists ) {
293 $create = $this->getVar( '_CreateDBAccount' );
294 } else {
295 $this->setVar( '_CreateDBAccount', false );
296 $create = false;
297 }
298
299 if ( !$create && !$exists ) {
300 if ( $this->canCreateAccounts() ) {
301 $msg = 'config-install-user-missing-create';
302 } else {
303 $msg = 'config-install-user-missing';
304 }
305 return Status::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
306 }
307
308 if ( !$exists ) {
309 // No more checks to do
310 return Status::newGood();
311 }
312
313 // Existing web account. Test the connection.
314 $status = $this->openConnectionToAnyDB(
315 $this->getVar( 'wgDBuser' ),
316 $this->getVar( 'wgDBpassword' ) );
317 if ( !$status->isOK() ) {
318 return $status;
319 }
320
321 // The web user is conventionally the table owner in PostgreSQL
322 // installations. Make sure the install user is able to create
323 // objects on behalf of the web user.
324 if ( $same || $this->canCreateObjectsForWebUser() ) {
325 return Status::newGood();
326 } else {
327 return Status::newFatal( 'config-pg-not-in-role' );
328 }
329 }
330
331 /**
332 * Returns true if the install user is able to create objects owned
333 * by the web user, false otherwise.
334 */
335 protected function canCreateObjectsForWebUser() {
336 if ( $this->isSuperUser() ) {
337 return true;
338 }
339
340 $status = $this->getPgConnection( 'create-db' );
341 if ( !$status->isOK() ) {
342 return false;
343 }
344 $conn = $status->value;
345 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
346 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__ );
347 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
348 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__ );
349
350 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
351 }
352
353 /**
354 * Recursive helper for canCreateObjectsForWebUser().
355 * @param $conn Database object
356 * @param $targetMember Role ID of the member to look for
357 * @param $group Role ID of the group to look for
358 * @param $maxDepth Maximum recursive search depth
359 */
360 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
361 if ( $targetMember === $group ) {
362 // A role is always a member of itself
363 return true;
364 }
365 // Get all members of the given group
366 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
367 array( 'roleid' => $group ), __METHOD__ );
368 foreach ( $res as $row ) {
369 if ( $row->member == $targetMember ) {
370 // Found target member
371 return true;
372 }
373 // Recursively search each member of the group to see if the target
374 // is a member of it, up to the given maximum depth.
375 if ( $maxDepth > 0 ) {
376 if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) {
377 // Found member of member
378 return true;
379 }
380 }
381 }
382 return false;
383 }
384
385 public function preInstall() {
386 $commitCB = array(
387 'name' => 'pg-commit',
388 'callback' => array( $this, 'commitChanges' ),
389 );
390 $plpgCB = array(
391 'name' => 'pg-plpgsql',
392 'callback' => array( $this, 'setupPLpgSQL' ),
393 );
394 $schemaCB = array(
395 'name' => 'schema',
396 'callback' => array( $this, 'setupSchema' )
397 );
398 $this->parent->addInstallStep( $commitCB, 'interwiki' );
399 $this->parent->addInstallStep( $plpgCB, 'database' );
400 $this->parent->addInstallStep( $schemaCB, 'database' );
401 if( $this->getVar( '_CreateDBAccount' ) ) {
402 $this->parent->addInstallStep( array(
403 'name' => 'user',
404 'callback' => array( $this, 'setupUser' ),
405 ) );
406 }
407 }
408
409 function setupDatabase() {
410 $status = $this->getPgConnection( 'create-db' );
411 if ( !$status->isOK() ) {
412 return $status;
413 }
414 $conn = $status->value;
415
416 $dbName = $this->getVar( 'wgDBname' );
417 $schema = $this->getVar( 'wgDBmwschema' );
418 $user = $this->getVar( 'wgDBuser' );
419 $safeschema = $conn->addIdentifierQuotes( $schema );
420 $safeuser = $conn->addIdentifierQuotes( $user );
421
422 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
423 array( 'datname' => $dbName ), __METHOD__ );
424 if ( !$exists ) {
425 $safedb = $conn->addIdentifierQuotes( $dbName );
426 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
427 }
428 return Status::newGood();
429 }
430
431 function setupSchema() {
432 // Get a connection to the target database
433 $status = $this->getPgConnection( 'create-schema' );
434 if ( !$status->isOK() ) {
435 return $status;
436 }
437 $conn = $status->value;
438
439 // Create the schema if necessary
440 $schema = $this->getVar( 'wgDBmwschema' );
441 $safeschema = $conn->addIdentifierQuotes( $schema );
442 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
443 if( !$conn->schemaExists( $schema ) ) {
444 try {
445 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
446 } catch ( DBQueryError $e ) {
447 return Status::newFatal( 'config-install-pg-schema-failed',
448 $this->getVar( '_InstallUser' ), $schema );
449 }
450 }
451
452 // If we created a user, alter it now to search the new schema by default
453 if ( $this->getVar( '_CreateDBAccount' ) ) {
454 $conn->query( "ALTER ROLE $safeuser SET search_path = $safeschema, public",
455 __METHOD__ );
456 }
457
458 // Select the new schema in the current connection
459 $conn->query( "SET search_path = $safeschema" );
460 return Status::newGood();
461 }
462
463 function commitChanges() {
464 $this->db->query( 'COMMIT' );
465 return Status::newGood();
466 }
467
468 function setupUser() {
469 if ( !$this->getVar( '_CreateDBAccount' ) ) {
470 return Status::newGood();
471 }
472
473 $status = $this->getPgConnection( 'create-db' );
474 if ( !$status->isOK() ) {
475 return $status;
476 }
477 $conn = $status->value;
478
479 $schema = $this->getVar( 'wgDBmwschema' );
480 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
481 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
482 $safeschema = $conn->addIdentifierQuotes( $schema );
483
484 // Check if the user already exists
485 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
486 if ( !$userExists ) {
487 // Create the user
488 try {
489 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
490
491 // If the install user is not a superuser, we need to make the install
492 // user a member of the new user's group, so that the install user will
493 // be able to create a schema and other objects on behalf of the new user.
494 if ( !$this->isSuperUser() ) {
495 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
496 }
497
498 $conn->query( $sql, __METHOD__ );
499 } catch ( DBQueryError $e ) {
500 return Status::newFatal( 'config-install-user-create-failed',
501 $this->getVar( 'wgDBuser' ), $e->getMessage() );
502 }
503 }
504
505 return Status::newGood();
506 }
507
508 function getLocalSettings() {
509 $port = $this->getVar( 'wgDBport' );
510 $schema = $this->getVar( 'wgDBmwschema' );
511 return
512 "# Postgres specific settings
513 \$wgDBport = \"{$port}\";
514 \$wgDBmwschema = \"{$schema}\";";
515 }
516
517 public function preUpgrade() {
518 global $wgDBuser, $wgDBpassword;
519
520 # Normal user and password are selected after this step, so for now
521 # just copy these two
522 $wgDBuser = $this->getVar( '_InstallUser' );
523 $wgDBpassword = $this->getVar( '_InstallPassword' );
524 }
525
526 public function createTables() {
527 $schema = $this->getVar( 'wgDBmwschema' );
528
529 $status = $this->getConnection();
530 if ( !$status->isOK() ) {
531 return $status;
532 }
533 $conn = $status->value;
534
535 if( $conn->tableExists( 'user' ) ) {
536 $status->warning( 'config-install-tables-exist' );
537 return $status;
538 }
539
540 $conn->begin( __METHOD__ );
541
542 if( !$conn->schemaExists( $schema ) ) {
543 $status->fatal( 'config-install-pg-schema-not-exist' );
544 return $status;
545 }
546 $error = $conn->sourceFile( $conn->getSchema() );
547 if( $error !== true ) {
548 $conn->reportQueryError( $error, 0, '', __METHOD__ );
549 $conn->rollback( __METHOD__ );
550 $status->fatal( 'config-install-tables-failed', $error );
551 } else {
552 $conn->commit( __METHOD__ );
553 }
554 // Resume normal operations
555 if( $status->isOk() ) {
556 $this->enableLB();
557 }
558 return $status;
559 }
560
561 public function setupPLpgSQL() {
562 // Connect as the install user, since it owns the database and so is
563 // the user that needs to run "CREATE LANGAUGE"
564 $status = $this->getPgConnection( 'create-schema' );
565 if ( !$status->isOK() ) {
566 return $status;
567 }
568 $conn = $status->value;
569
570 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
571 array( 'lanname' => 'plpgsql' ), __METHOD__ );
572 if ( $exists ) {
573 // Already exists, nothing to do
574 return Status::newGood();
575 }
576
577 // plpgsql is not installed, but if we have a pg_pltemplate table, we
578 // should be able to create it
579 $exists = $conn->selectField(
580 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
581 1,
582 array(
583 'pg_namespace.oid=relnamespace',
584 'nspname' => 'pg_catalog',
585 'relname' => 'pg_pltemplate',
586 ),
587 __METHOD__ );
588 if ( $exists ) {
589 try {
590 $conn->query( 'CREATE LANGUAGE plpgsql' );
591 } catch ( DBQueryError $e ) {
592 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
593 }
594 } else {
595 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
596 }
597 return Status::newGood();
598 }
599 }