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