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