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