Merge "(bug 26909) follow up r102947: fix the navigation with 'dir' and 'continue...
[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 string User name
114 * @param $password string Password
115 * @param $dbName string 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( __METHOD__ );
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 string 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 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 * @return bool
348 */
349 protected function canCreateObjectsForWebUser() {
350 if ( $this->isSuperUser() ) {
351 return true;
352 }
353
354 $status = $this->getPgConnection( 'create-db' );
355 if ( !$status->isOK() ) {
356 return false;
357 }
358 $conn = $status->value;
359 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
360 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__ );
361 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
362 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__ );
363
364 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
365 }
366
367 /**
368 * Recursive helper for canCreateObjectsForWebUser().
369 * @param $conn DatabaseBase object
370 * @param $targetMember int Role ID of the member to look for
371 * @param $group int Role ID of the group to look for
372 * @param $maxDepth int Maximum recursive search depth
373 * @return bool
374 */
375 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
376 if ( $targetMember === $group ) {
377 // A role is always a member of itself
378 return true;
379 }
380 // Get all members of the given group
381 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
382 array( 'roleid' => $group ), __METHOD__ );
383 foreach ( $res as $row ) {
384 if ( $row->member == $targetMember ) {
385 // Found target member
386 return true;
387 }
388 // Recursively search each member of the group to see if the target
389 // is a member of it, up to the given maximum depth.
390 if ( $maxDepth > 0 ) {
391 if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) {
392 // Found member of member
393 return true;
394 }
395 }
396 }
397 return false;
398 }
399
400 public function preInstall() {
401 $createDbAccount = array(
402 'name' => 'user',
403 'callback' => array( $this, 'setupUser' ),
404 );
405 $commitCB = array(
406 'name' => 'pg-commit',
407 'callback' => array( $this, 'commitChanges' ),
408 );
409 $plpgCB = array(
410 'name' => 'pg-plpgsql',
411 'callback' => array( $this, 'setupPLpgSQL' ),
412 );
413 $schemaCB = array(
414 'name' => 'schema',
415 'callback' => array( $this, 'setupSchema' )
416 );
417
418 if( $this->getVar( '_CreateDBAccount' ) ) {
419 $this->parent->addInstallStep( $createDbAccount, 'database' );
420 }
421 $this->parent->addInstallStep( $commitCB, 'interwiki' );
422 $this->parent->addInstallStep( $plpgCB, 'database' );
423 $this->parent->addInstallStep( $schemaCB, 'database' );
424 }
425
426 function setupDatabase() {
427 $status = $this->getPgConnection( 'create-db' );
428 if ( !$status->isOK() ) {
429 return $status;
430 }
431 $conn = $status->value;
432
433 $dbName = $this->getVar( 'wgDBname' );
434
435 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
436 array( 'datname' => $dbName ), __METHOD__ );
437 if ( !$exists ) {
438 $safedb = $conn->addIdentifierQuotes( $dbName );
439 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
440 }
441 return Status::newGood();
442 }
443
444 function setupSchema() {
445 // Get a connection to the target database
446 $status = $this->getPgConnection( 'create-schema' );
447 if ( !$status->isOK() ) {
448 return $status;
449 }
450 $conn = $status->value;
451
452 // Create the schema if necessary
453 $schema = $this->getVar( 'wgDBmwschema' );
454 $safeschema = $conn->addIdentifierQuotes( $schema );
455 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
456 if( !$conn->schemaExists( $schema ) ) {
457 try {
458 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
459 } catch ( DBQueryError $e ) {
460 return Status::newFatal( 'config-install-pg-schema-failed',
461 $this->getVar( '_InstallUser' ), $schema );
462 }
463 }
464
465 // Select the new schema in the current connection
466 $conn->determineCoreSchema( $schema );
467 return Status::newGood();
468 }
469
470 function commitChanges() {
471 $this->db->commit( __METHOD__ );
472 return Status::newGood();
473 }
474
475 function setupUser() {
476 if ( !$this->getVar( '_CreateDBAccount' ) ) {
477 return Status::newGood();
478 }
479
480 $status = $this->getPgConnection( 'create-db' );
481 if ( !$status->isOK() ) {
482 return $status;
483 }
484 $conn = $status->value;
485
486 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
487 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
488
489 // Check if the user already exists
490 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
491 if ( !$userExists ) {
492 // Create the user
493 try {
494 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
495
496 // If the install user is not a superuser, we need to make the install
497 // user a member of the new user's group, so that the install user will
498 // be able to create a schema and other objects on behalf of the new user.
499 if ( !$this->isSuperUser() ) {
500 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
501 }
502
503 $conn->query( $sql, __METHOD__ );
504 } catch ( DBQueryError $e ) {
505 return Status::newFatal( 'config-install-user-create-failed',
506 $this->getVar( 'wgDBuser' ), $e->getMessage() );
507 }
508 }
509
510 return Status::newGood();
511 }
512
513 function getLocalSettings() {
514 $port = $this->getVar( 'wgDBport' );
515 $schema = $this->getVar( 'wgDBmwschema' );
516 return
517 "# Postgres specific settings
518 \$wgDBport = \"{$port}\";
519 \$wgDBmwschema = \"{$schema}\";";
520 }
521
522 public function preUpgrade() {
523 global $wgDBuser, $wgDBpassword;
524
525 # Normal user and password are selected after this step, so for now
526 # just copy these two
527 $wgDBuser = $this->getVar( '_InstallUser' );
528 $wgDBpassword = $this->getVar( '_InstallPassword' );
529 }
530
531 public function createTables() {
532 $schema = $this->getVar( 'wgDBmwschema' );
533
534 $status = $this->getConnection();
535 if ( !$status->isOK() ) {
536 return $status;
537 }
538
539 /**
540 * @var $conn DatabaseBase
541 */
542 $conn = $status->value;
543
544 if( $conn->tableExists( 'archive' ) ) {
545 $status->warning( 'config-install-tables-exist' );
546 $this->enableLB();
547 return $status;
548 }
549
550 $conn->begin( __METHOD__ );
551
552 if( !$conn->schemaExists( $schema ) ) {
553 $status->fatal( 'config-install-pg-schema-not-exist' );
554 return $status;
555 }
556 $error = $conn->sourceFile( $conn->getSchemaPath() );
557 if( $error !== true ) {
558 $conn->reportQueryError( $error, 0, '', __METHOD__ );
559 $conn->rollback( __METHOD__ );
560 $status->fatal( 'config-install-tables-failed', $error );
561 } else {
562 $conn->commit( __METHOD__ );
563 }
564 // Resume normal operations
565 if( $status->isOk() ) {
566 $this->enableLB();
567 }
568 return $status;
569 }
570
571 public function setupPLpgSQL() {
572 // Connect as the install user, since it owns the database and so is
573 // the user that needs to run "CREATE LANGAUGE"
574 $status = $this->getPgConnection( 'create-schema' );
575 if ( !$status->isOK() ) {
576 return $status;
577 }
578 /**
579 * @var $conn DatabaseBase
580 */
581 $conn = $status->value;
582
583 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
584 array( 'lanname' => 'plpgsql' ), __METHOD__ );
585 if ( $exists ) {
586 // Already exists, nothing to do
587 return Status::newGood();
588 }
589
590 // plpgsql is not installed, but if we have a pg_pltemplate table, we
591 // should be able to create it
592 $exists = $conn->selectField(
593 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
594 1,
595 array(
596 'pg_namespace.oid=relnamespace',
597 'nspname' => 'pg_catalog',
598 'relname' => 'pg_pltemplate',
599 ),
600 __METHOD__ );
601 if ( $exists ) {
602 try {
603 $conn->query( 'CREATE LANGUAGE plpgsql' );
604 } catch ( DBQueryError $e ) {
605 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
606 }
607 } else {
608 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
609 }
610 return Status::newGood();
611 }
612 }