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