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