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