Merge "Deleting a page and then immediately create-protecting it caused a PHP Fatal...
[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',
87 'wgDBname', 'wgDBmwschema' ) );
88
89 // Validate them
90 $status = Status::newGood();
91 if ( !strlen( $newValues['wgDBname'] ) ) {
92 $status->fatal( 'config-missing-db-name' );
93 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
94 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
95 }
96 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
97 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
98 }
99
100 // Submit user box
101 if ( $status->isOK() ) {
102 $status->merge( $this->submitInstallUserBox() );
103 }
104 if ( !$status->isOK() ) {
105 return $status;
106 }
107
108 $status = $this->getPgConnection( 'create-db' );
109 if ( !$status->isOK() ) {
110 return $status;
111 }
112 /**
113 * @var $conn DatabaseBase
114 */
115 $conn = $status->value;
116
117 // Check version
118 $version = $conn->getServerVersion();
119 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
120 return Status::newFatal( 'config-postgres-old', $this->minimumVersion, $version );
121 }
122
123 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
124 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
125
126 return Status::newGood();
127 }
128
129 public function getConnection() {
130 $status = $this->getPgConnection( 'create-tables' );
131 if ( $status->isOK() ) {
132 $this->db = $status->value;
133 }
134
135 return $status;
136 }
137
138 public function openConnection() {
139 return $this->openPgConnection( 'create-tables' );
140 }
141
142 /**
143 * Open a PG connection with given parameters
144 * @param string $user User name
145 * @param string $password Password
146 * @param string $dbName Database name
147 * @return Status
148 */
149 protected function openConnectionWithParams( $user, $password, $dbName ) {
150 $status = Status::newGood();
151 try {
152 $db = new DatabasePostgres(
153 $this->getVar( 'wgDBserver' ),
154 $user,
155 $password,
156 $dbName
157 );
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 object. On success, a connection object will be in the
214 * value member.
215 */
216 protected function openPgConnection( $type ) {
217 switch ( $type ) {
218 case 'create-db':
219 return $this->openConnectionToAnyDB(
220 $this->getVar( '_InstallUser' ),
221 $this->getVar( '_InstallPassword' ) );
222 case 'create-schema':
223 return $this->openConnectionWithParams(
224 $this->getVar( '_InstallUser' ),
225 $this->getVar( '_InstallPassword' ),
226 $this->getVar( 'wgDBname' ) );
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 $conn = new DatabasePostgres(
257 $this->getVar( 'wgDBserver' ),
258 $user,
259 $password,
260 $db );
261 } catch ( DBConnectionError $error ) {
262 $conn = false;
263 $status->fatal( 'config-pg-test-error', $db,
264 $error->getMessage() );
265 }
266 if ( $conn !== false ) {
267 break;
268 }
269 }
270 if ( $conn !== false ) {
271 return Status::newGood( $conn );
272 } else {
273 return $status;
274 }
275 }
276
277 protected function getInstallUserPermissions() {
278 $status = $this->getPgConnection( 'create-db' );
279 if ( !$status->isOK() ) {
280 return false;
281 }
282 /**
283 * @var $conn DatabaseBase
284 */
285 $conn = $status->value;
286 $superuser = $this->getVar( '_InstallUser' );
287
288 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
289 array( 'rolname' => $superuser ), __METHOD__ );
290
291 return $row;
292 }
293
294 protected function canCreateAccounts() {
295 $perms = $this->getInstallUserPermissions();
296 if ( !$perms ) {
297 return false;
298 }
299
300 return $perms->rolsuper === 't' || $perms->rolcreaterole === 't';
301 }
302
303 protected function isSuperUser() {
304 $perms = $this->getInstallUserPermissions();
305 if ( !$perms ) {
306 return false;
307 }
308
309 return $perms->rolsuper === 't';
310 }
311
312 public function getSettingsForm() {
313 if ( $this->canCreateAccounts() ) {
314 $noCreateMsg = false;
315 } else {
316 $noCreateMsg = 'config-db-web-no-create-privs';
317 }
318 $s = $this->getWebUserBox( $noCreateMsg );
319
320 return $s;
321 }
322
323 public function submitSettingsForm() {
324 $status = $this->submitWebUserBox();
325 if ( !$status->isOK() ) {
326 return $status;
327 }
328
329 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
330
331 if ( $same ) {
332 $exists = true;
333 } else {
334 // Check if the web user exists
335 // Connect to the database with the install user
336 $status = $this->getPgConnection( 'create-db' );
337 if ( !$status->isOK() ) {
338 return $status;
339 }
340 $exists = $status->value->roleExists( $this->getVar( 'wgDBuser' ) );
341 }
342
343 // Validate the create checkbox
344 if ( $this->canCreateAccounts() && !$same && !$exists ) {
345 $create = $this->getVar( '_CreateDBAccount' );
346 } else {
347 $this->setVar( '_CreateDBAccount', false );
348 $create = false;
349 }
350
351 if ( !$create && !$exists ) {
352 if ( $this->canCreateAccounts() ) {
353 $msg = 'config-install-user-missing-create';
354 } else {
355 $msg = 'config-install-user-missing';
356 }
357
358 return Status::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
359 }
360
361 if ( !$exists ) {
362 // No more checks to do
363 return Status::newGood();
364 }
365
366 // Existing web account. Test the connection.
367 $status = $this->openConnectionToAnyDB(
368 $this->getVar( 'wgDBuser' ),
369 $this->getVar( 'wgDBpassword' ) );
370 if ( !$status->isOK() ) {
371 return $status;
372 }
373
374 // The web user is conventionally the table owner in PostgreSQL
375 // installations. Make sure the install user is able to create
376 // objects on behalf of the web user.
377 if ( $same || $this->canCreateObjectsForWebUser() ) {
378 return Status::newGood();
379 } else {
380 return Status::newFatal( 'config-pg-not-in-role' );
381 }
382 }
383
384 /**
385 * Returns true if the install user is able to create objects owned
386 * by the web user, false otherwise.
387 * @return bool
388 */
389 protected function canCreateObjectsForWebUser() {
390 if ( $this->isSuperUser() ) {
391 return true;
392 }
393
394 $status = $this->getPgConnection( 'create-db' );
395 if ( !$status->isOK() ) {
396 return false;
397 }
398 $conn = $status->value;
399 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
400 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__ );
401 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
402 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__ );
403
404 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
405 }
406
407 /**
408 * Recursive helper for canCreateObjectsForWebUser().
409 * @param $conn DatabaseBase object
410 * @param int $targetMember Role ID of the member to look for
411 * @param int $group Role ID of the group to look for
412 * @param int $maxDepth Maximum recursive search depth
413 * @return bool
414 */
415 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
416 if ( $targetMember === $group ) {
417 // A role is always a member of itself
418 return true;
419 }
420 // Get all members of the given group
421 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
422 array( 'roleid' => $group ), __METHOD__ );
423 foreach ( $res as $row ) {
424 if ( $row->member == $targetMember ) {
425 // Found target member
426 return true;
427 }
428 // Recursively search each member of the group to see if the target
429 // is a member of it, up to the given maximum depth.
430 if ( $maxDepth > 0 ) {
431 if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) {
432 // Found member of member
433 return true;
434 }
435 }
436 }
437
438 return false;
439 }
440
441 public function preInstall() {
442 $createDbAccount = array(
443 'name' => 'user',
444 'callback' => array( $this, 'setupUser' ),
445 );
446 $commitCB = array(
447 'name' => 'pg-commit',
448 'callback' => array( $this, 'commitChanges' ),
449 );
450 $plpgCB = array(
451 'name' => 'pg-plpgsql',
452 'callback' => array( $this, 'setupPLpgSQL' ),
453 );
454 $schemaCB = array(
455 'name' => 'schema',
456 'callback' => array( $this, 'setupSchema' )
457 );
458
459 if ( $this->getVar( '_CreateDBAccount' ) ) {
460 $this->parent->addInstallStep( $createDbAccount, 'database' );
461 }
462 $this->parent->addInstallStep( $commitCB, 'interwiki' );
463 $this->parent->addInstallStep( $plpgCB, 'database' );
464 $this->parent->addInstallStep( $schemaCB, 'database' );
465 }
466
467 function setupDatabase() {
468 $status = $this->getPgConnection( 'create-db' );
469 if ( !$status->isOK() ) {
470 return $status;
471 }
472 $conn = $status->value;
473
474 $dbName = $this->getVar( 'wgDBname' );
475
476 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
477 array( 'datname' => $dbName ), __METHOD__ );
478 if ( !$exists ) {
479 $safedb = $conn->addIdentifierQuotes( $dbName );
480 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
481 }
482
483 return Status::newGood();
484 }
485
486 function setupSchema() {
487 // Get a connection to the target database
488 $status = $this->getPgConnection( 'create-schema' );
489 if ( !$status->isOK() ) {
490 return $status;
491 }
492 $conn = $status->value;
493
494 // Create the schema if necessary
495 $schema = $this->getVar( 'wgDBmwschema' );
496 $safeschema = $conn->addIdentifierQuotes( $schema );
497 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
498 if ( !$conn->schemaExists( $schema ) ) {
499 try {
500 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
501 } catch ( DBQueryError $e ) {
502 return Status::newFatal( 'config-install-pg-schema-failed',
503 $this->getVar( '_InstallUser' ), $schema );
504 }
505 }
506
507 // Select the new schema in the current connection
508 $conn->determineCoreSchema( $schema );
509
510 return Status::newGood();
511 }
512
513 function commitChanges() {
514 $this->db->commit( __METHOD__ );
515
516 return Status::newGood();
517 }
518
519 function setupUser() {
520 if ( !$this->getVar( '_CreateDBAccount' ) ) {
521 return Status::newGood();
522 }
523
524 $status = $this->getPgConnection( 'create-db' );
525 if ( !$status->isOK() ) {
526 return $status;
527 }
528 $conn = $status->value;
529
530 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
531 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
532
533 // Check if the user already exists
534 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
535 if ( !$userExists ) {
536 // Create the user
537 try {
538 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
539
540 // If the install user is not a superuser, we need to make the install
541 // user a member of the new user's group, so that the install user will
542 // be able to create a schema and other objects on behalf of the new user.
543 if ( !$this->isSuperUser() ) {
544 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
545 }
546
547 $conn->query( $sql, __METHOD__ );
548 } catch ( DBQueryError $e ) {
549 return Status::newFatal( 'config-install-user-create-failed',
550 $this->getVar( 'wgDBuser' ), $e->getMessage() );
551 }
552 }
553
554 return Status::newGood();
555 }
556
557 function getLocalSettings() {
558 $port = $this->getVar( 'wgDBport' );
559 $schema = $this->getVar( 'wgDBmwschema' );
560
561 return "# Postgres specific settings
562 \$wgDBport = \"{$port}\";
563 \$wgDBmwschema = \"{$schema}\";";
564 }
565
566 public function preUpgrade() {
567 global $wgDBuser, $wgDBpassword;
568
569 # Normal user and password are selected after this step, so for now
570 # just copy these two
571 $wgDBuser = $this->getVar( '_InstallUser' );
572 $wgDBpassword = $this->getVar( '_InstallPassword' );
573 }
574
575 public function createTables() {
576 $schema = $this->getVar( 'wgDBmwschema' );
577
578 $status = $this->getConnection();
579 if ( !$status->isOK() ) {
580 return $status;
581 }
582
583 /**
584 * @var $conn DatabaseBase
585 */
586 $conn = $status->value;
587
588 if ( $conn->tableExists( 'archive' ) ) {
589 $status->warning( 'config-install-tables-exist' );
590 $this->enableLB();
591
592 return $status;
593 }
594
595 $conn->begin( __METHOD__ );
596
597 if ( !$conn->schemaExists( $schema ) ) {
598 $status->fatal( 'config-install-pg-schema-not-exist' );
599
600 return $status;
601 }
602 $error = $conn->sourceFile( $conn->getSchemaPath() );
603 if ( $error !== true ) {
604 $conn->reportQueryError( $error, 0, '', __METHOD__ );
605 $conn->rollback( __METHOD__ );
606 $status->fatal( 'config-install-tables-failed', $error );
607 } else {
608 $conn->commit( __METHOD__ );
609 }
610 // Resume normal operations
611 if ( $status->isOk() ) {
612 $this->enableLB();
613 }
614
615 return $status;
616 }
617
618 public function setupPLpgSQL() {
619 // Connect as the install user, since it owns the database and so is
620 // the user that needs to run "CREATE LANGAUGE"
621 $status = $this->getPgConnection( 'create-schema' );
622 if ( !$status->isOK() ) {
623 return $status;
624 }
625 /**
626 * @var $conn DatabaseBase
627 */
628 $conn = $status->value;
629
630 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
631 array( 'lanname' => 'plpgsql' ), __METHOD__ );
632 if ( $exists ) {
633 // Already exists, nothing to do
634 return Status::newGood();
635 }
636
637 // plpgsql is not installed, but if we have a pg_pltemplate table, we
638 // should be able to create it
639 $exists = $conn->selectField(
640 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
641 1,
642 array(
643 'pg_namespace.oid=relnamespace',
644 'nspname' => 'pg_catalog',
645 'relname' => 'pg_pltemplate',
646 ),
647 __METHOD__ );
648 if ( $exists ) {
649 try {
650 $conn->query( 'CREATE LANGUAGE plpgsql' );
651 } catch ( DBQueryError $e ) {
652 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
653 }
654 } else {
655 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
656 }
657
658 return Status::newGood();
659 }
660 }