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