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