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