fix some spacing
[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 * @throws MWException
194 * @return Status object. On success, a connection object will be in the
195 * value member.
196 */
197 protected function openPgConnection( $type ) {
198 switch ( $type ) {
199 case 'create-db':
200 return $this->openConnectionToAnyDB(
201 $this->getVar( '_InstallUser' ),
202 $this->getVar( '_InstallPassword' ) );
203 case 'create-schema':
204 return $this->openConnectionWithParams(
205 $this->getVar( '_InstallUser' ),
206 $this->getVar( '_InstallPassword' ),
207 $this->getVar( 'wgDBname' ) );
208 case 'create-tables':
209 $status = $this->openPgConnection( 'create-schema' );
210 if ( $status->isOK() ) {
211 /**
212 * @var $conn DatabaseBase
213 */
214 $conn = $status->value;
215 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
216 $conn->query( "SET ROLE $safeRole" );
217 }
218 return $status;
219 default:
220 throw new MWException( "Invalid special connection type: \"$type\"" );
221 }
222 }
223
224 public function openConnectionToAnyDB( $user, $password ) {
225 $dbs = array(
226 'template1',
227 'postgres',
228 );
229 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
230 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
231 }
232 $conn = false;
233 $status = Status::newGood();
234 foreach ( $dbs as $db ) {
235 try {
236 $conn = new DatabasePostgres(
237 $this->getVar( 'wgDBserver' ),
238 $user,
239 $password,
240 $db );
241 } catch ( DBConnectionError $error ) {
242 $conn = false;
243 $status->fatal( 'config-pg-test-error', $db,
244 $error->getMessage() );
245 }
246 if ( $conn !== false ) {
247 break;
248 }
249 }
250 if ( $conn !== false ) {
251 return Status::newGood( $conn );
252 } else {
253 return $status;
254 }
255 }
256
257 protected function getInstallUserPermissions() {
258 $status = $this->getPgConnection( 'create-db' );
259 if ( !$status->isOK() ) {
260 return false;
261 }
262 /**
263 * @var $conn DatabaseBase
264 */
265 $conn = $status->value;
266 $superuser = $this->getVar( '_InstallUser' );
267
268 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
269 array( 'rolname' => $superuser ), __METHOD__ );
270 return $row;
271 }
272
273 protected function canCreateAccounts() {
274 $perms = $this->getInstallUserPermissions();
275 if ( !$perms ) {
276 return false;
277 }
278 return $perms->rolsuper === 't' || $perms->rolcreaterole === 't';
279 }
280
281 protected function isSuperUser() {
282 $perms = $this->getInstallUserPermissions();
283 if ( !$perms ) {
284 return false;
285 }
286 return $perms->rolsuper === 't';
287 }
288
289 public function getSettingsForm() {
290 if ( $this->canCreateAccounts() ) {
291 $noCreateMsg = false;
292 } else {
293 $noCreateMsg = 'config-db-web-no-create-privs';
294 }
295 $s = $this->getWebUserBox( $noCreateMsg );
296
297 return $s;
298 }
299
300 public function submitSettingsForm() {
301 $status = $this->submitWebUserBox();
302 if ( !$status->isOK() ) {
303 return $status;
304 }
305
306 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
307
308 if ( $same ) {
309 $exists = true;
310 } else {
311 // Check if the web user exists
312 // Connect to the database with the install user
313 $status = $this->getPgConnection( 'create-db' );
314 if ( !$status->isOK() ) {
315 return $status;
316 }
317 $exists = $status->value->roleExists( $this->getVar( 'wgDBuser' ) );
318 }
319
320 // Validate the create checkbox
321 if ( $this->canCreateAccounts() && !$same && !$exists ) {
322 $create = $this->getVar( '_CreateDBAccount' );
323 } else {
324 $this->setVar( '_CreateDBAccount', false );
325 $create = false;
326 }
327
328 if ( !$create && !$exists ) {
329 if ( $this->canCreateAccounts() ) {
330 $msg = 'config-install-user-missing-create';
331 } else {
332 $msg = 'config-install-user-missing';
333 }
334 return Status::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
335 }
336
337 if ( !$exists ) {
338 // No more checks to do
339 return Status::newGood();
340 }
341
342 // Existing web account. Test the connection.
343 $status = $this->openConnectionToAnyDB(
344 $this->getVar( 'wgDBuser' ),
345 $this->getVar( 'wgDBpassword' ) );
346 if ( !$status->isOK() ) {
347 return $status;
348 }
349
350 // The web user is conventionally the table owner in PostgreSQL
351 // installations. Make sure the install user is able to create
352 // objects on behalf of the web user.
353 if ( $same || $this->canCreateObjectsForWebUser() ) {
354 return Status::newGood();
355 } else {
356 return Status::newFatal( 'config-pg-not-in-role' );
357 }
358 }
359
360 /**
361 * Returns true if the install user is able to create objects owned
362 * by the web user, false otherwise.
363 * @return bool
364 */
365 protected function canCreateObjectsForWebUser() {
366 if ( $this->isSuperUser() ) {
367 return true;
368 }
369
370 $status = $this->getPgConnection( 'create-db' );
371 if ( !$status->isOK() ) {
372 return false;
373 }
374 $conn = $status->value;
375 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
376 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__ );
377 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
378 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__ );
379
380 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
381 }
382
383 /**
384 * Recursive helper for canCreateObjectsForWebUser().
385 * @param $conn DatabaseBase object
386 * @param $targetMember int Role ID of the member to look for
387 * @param $group int Role ID of the group to look for
388 * @param $maxDepth int Maximum recursive search depth
389 * @return bool
390 */
391 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
392 if ( $targetMember === $group ) {
393 // A role is always a member of itself
394 return true;
395 }
396 // Get all members of the given group
397 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
398 array( 'roleid' => $group ), __METHOD__ );
399 foreach ( $res as $row ) {
400 if ( $row->member == $targetMember ) {
401 // Found target member
402 return true;
403 }
404 // Recursively search each member of the group to see if the target
405 // is a member of it, up to the given maximum depth.
406 if ( $maxDepth > 0 ) {
407 if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) {
408 // Found member of member
409 return true;
410 }
411 }
412 }
413 return false;
414 }
415
416 public function preInstall() {
417 $createDbAccount = array(
418 'name' => 'user',
419 'callback' => array( $this, 'setupUser' ),
420 );
421 $commitCB = array(
422 'name' => 'pg-commit',
423 'callback' => array( $this, 'commitChanges' ),
424 );
425 $plpgCB = array(
426 'name' => 'pg-plpgsql',
427 'callback' => array( $this, 'setupPLpgSQL' ),
428 );
429 $schemaCB = array(
430 'name' => 'schema',
431 'callback' => array( $this, 'setupSchema' )
432 );
433
434 if( $this->getVar( '_CreateDBAccount' ) ) {
435 $this->parent->addInstallStep( $createDbAccount, 'database' );
436 }
437 $this->parent->addInstallStep( $commitCB, 'interwiki' );
438 $this->parent->addInstallStep( $plpgCB, 'database' );
439 $this->parent->addInstallStep( $schemaCB, 'database' );
440 }
441
442 function setupDatabase() {
443 $status = $this->getPgConnection( 'create-db' );
444 if ( !$status->isOK() ) {
445 return $status;
446 }
447 $conn = $status->value;
448
449 $dbName = $this->getVar( 'wgDBname' );
450
451 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
452 array( 'datname' => $dbName ), __METHOD__ );
453 if ( !$exists ) {
454 $safedb = $conn->addIdentifierQuotes( $dbName );
455 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
456 }
457 return Status::newGood();
458 }
459
460 function setupSchema() {
461 // Get a connection to the target database
462 $status = $this->getPgConnection( 'create-schema' );
463 if ( !$status->isOK() ) {
464 return $status;
465 }
466 $conn = $status->value;
467
468 // Create the schema if necessary
469 $schema = $this->getVar( 'wgDBmwschema' );
470 $safeschema = $conn->addIdentifierQuotes( $schema );
471 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
472 if( !$conn->schemaExists( $schema ) ) {
473 try {
474 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
475 } catch ( DBQueryError $e ) {
476 return Status::newFatal( 'config-install-pg-schema-failed',
477 $this->getVar( '_InstallUser' ), $schema );
478 }
479 }
480
481 // Select the new schema in the current connection
482 $conn->determineCoreSchema( $schema );
483 return Status::newGood();
484 }
485
486 function commitChanges() {
487 $this->db->commit( __METHOD__ );
488 return Status::newGood();
489 }
490
491 function setupUser() {
492 if ( !$this->getVar( '_CreateDBAccount' ) ) {
493 return Status::newGood();
494 }
495
496 $status = $this->getPgConnection( 'create-db' );
497 if ( !$status->isOK() ) {
498 return $status;
499 }
500 $conn = $status->value;
501
502 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
503 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
504
505 // Check if the user already exists
506 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
507 if ( !$userExists ) {
508 // Create the user
509 try {
510 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
511
512 // If the install user is not a superuser, we need to make the install
513 // user a member of the new user's group, so that the install user will
514 // be able to create a schema and other objects on behalf of the new user.
515 if ( !$this->isSuperUser() ) {
516 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
517 }
518
519 $conn->query( $sql, __METHOD__ );
520 } catch ( DBQueryError $e ) {
521 return Status::newFatal( 'config-install-user-create-failed',
522 $this->getVar( 'wgDBuser' ), $e->getMessage() );
523 }
524 }
525
526 return Status::newGood();
527 }
528
529 function getLocalSettings() {
530 $port = $this->getVar( 'wgDBport' );
531 $schema = $this->getVar( 'wgDBmwschema' );
532 return
533 "# Postgres specific settings
534 \$wgDBport = \"{$port}\";
535 \$wgDBmwschema = \"{$schema}\";";
536 }
537
538 public function preUpgrade() {
539 global $wgDBuser, $wgDBpassword;
540
541 # Normal user and password are selected after this step, so for now
542 # just copy these two
543 $wgDBuser = $this->getVar( '_InstallUser' );
544 $wgDBpassword = $this->getVar( '_InstallPassword' );
545 }
546
547 public function createTables() {
548 $schema = $this->getVar( 'wgDBmwschema' );
549
550 $status = $this->getConnection();
551 if ( !$status->isOK() ) {
552 return $status;
553 }
554
555 /**
556 * @var $conn DatabaseBase
557 */
558 $conn = $status->value;
559
560 if( $conn->tableExists( 'archive' ) ) {
561 $status->warning( 'config-install-tables-exist' );
562 $this->enableLB();
563 return $status;
564 }
565
566 $conn->begin( __METHOD__ );
567
568 if( !$conn->schemaExists( $schema ) ) {
569 $status->fatal( 'config-install-pg-schema-not-exist' );
570 return $status;
571 }
572 $error = $conn->sourceFile( $conn->getSchemaPath() );
573 if( $error !== true ) {
574 $conn->reportQueryError( $error, 0, '', __METHOD__ );
575 $conn->rollback( __METHOD__ );
576 $status->fatal( 'config-install-tables-failed', $error );
577 } else {
578 $conn->commit( __METHOD__ );
579 }
580 // Resume normal operations
581 if( $status->isOk() ) {
582 $this->enableLB();
583 }
584 return $status;
585 }
586
587 public function setupPLpgSQL() {
588 // Connect as the install user, since it owns the database and so is
589 // the user that needs to run "CREATE LANGAUGE"
590 $status = $this->getPgConnection( 'create-schema' );
591 if ( !$status->isOK() ) {
592 return $status;
593 }
594 /**
595 * @var $conn DatabaseBase
596 */
597 $conn = $status->value;
598
599 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
600 array( 'lanname' => 'plpgsql' ), __METHOD__ );
601 if ( $exists ) {
602 // Already exists, nothing to do
603 return Status::newGood();
604 }
605
606 // plpgsql is not installed, but if we have a pg_pltemplate table, we
607 // should be able to create it
608 $exists = $conn->selectField(
609 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
610 1,
611 array(
612 'pg_namespace.oid=relnamespace',
613 'nspname' => 'pg_catalog',
614 'relname' => 'pg_pltemplate',
615 ),
616 __METHOD__ );
617 if ( $exists ) {
618 try {
619 $conn->query( 'CREATE LANGUAGE plpgsql' );
620 } catch ( DBQueryError $e ) {
621 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
622 }
623 } else {
624 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
625 }
626 return Status::newGood();
627 }
628 }