Debian Codegraph @

includes/installer/PostgresInstaller.php

raw symbols SCIP
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 Installer
22 */
23
24 namespace MediaWiki\Installer;
25
26 use InvalidArgumentException;
27 use MediaWiki\MediaWikiServices;
28 use MediaWiki\Status\Status;
29 use Wikimedia\Rdbms\Database;
30 use Wikimedia\Rdbms\DatabaseFactory;
31 use Wikimedia\Rdbms\DatabasePostgres;
32 use Wikimedia\Rdbms\DBConnectionError;
33 use Wikimedia\Rdbms\DBQueryError;
34
35 /**
36 * Class for setting up the MediaWiki database using Postgres.
37 *
38 * @ingroup Installer
39 * @since 1.17
40 */
41 class PostgresInstaller extends DatabaseInstaller {
42
43 /** @inheritDoc */
44 protected $globalNames = [
45 'wgDBserver',
46 'wgDBport',
47 'wgDBname',
48 'wgDBuser',
49 'wgDBpassword',
50 'wgDBssl',
51 'wgDBmwschema',
52 ];
53
54 /** @inheritDoc */
55 protected $internalDefaults = [
56 '_InstallUser' => 'postgres',
57 ];
58
59 /** @inheritDoc */
60 public static $minimumVersion = '10';
61 /** @inheritDoc */
62 protected static $notMinimumVersionMessage = 'config-postgres-old';
63 /** @var int */
64 public $maxRoleSearchDepth = 5;
65
66 public function getName() {
67 return 'postgres';
68 }
69
70 public function isCompiled() {
71 return self::checkExtension( 'pgsql' );
72 }
73
74 public function getConnectForm( WebInstaller $webInstaller ): DatabaseConnectForm {
75 return new PostgresConnectForm( $webInstaller, $this );
76 }
77
78 public function getSettingsForm( WebInstaller $webInstaller ): DatabaseSettingsForm {
79 return new PostgresSettingsForm( $webInstaller, $this );
80 }
81
82 /**
83 * Open a PG connection with given parameters
84 * @param string $user User name
85 * @param string $password
86 * @param string $dbName Database name
87 * @param string $schema Database schema
88 * @return ConnectionStatus
89 */
90 protected function openConnectionWithParams( $user, $password, $dbName, $schema ) {
91 $status = new ConnectionStatus;
92 try {
93 $db = MediaWikiServices::getInstance()->getDatabaseFactory()->create( 'postgres', [
94 'host' => $this->getVar( 'wgDBserver' ),
95 'port' => $this->getVar( 'wgDBport' ),
96 'user' => $user,
97 'password' => $password,
98 'ssl' => $this->getVar( 'wgDBssl' ),
99 'dbname' => $dbName,
100 'schema' => $schema,
101 ] );
102 $status->setDB( $db );
103 } catch ( DBConnectionError $e ) {
104 $status->fatal( 'config-connection-error', $e->getMessage() );
105 }
106
107 return $status;
108 }
109
110 /**
111 * Get a connection of a specific PostgreSQL-specific type. Connections
112 * of a given type are cached.
113 *
114 * PostgreSQL lacks cross-database operations, so after the new database is
115 * created, you need to make a separate connection to connect to that
116 * database and add tables to it.
117 *
118 * New tables are owned by the user that creates them, and MediaWiki's
119 * PostgreSQL support has always assumed that the table owner will be
120 * $wgDBuser. So before we create new tables, we either need to either
121 * connect as the other user or to execute a SET ROLE command. Using a
122 * separate connection for this allows us to avoid accidental cross-module
123 * dependencies.
124 *
125 * @param string $type The type of connection to get:
126 * - self::CONN_CREATE_DATABASE: A connection for creating DBs, suitable for pre-
127 * installation.
128 * - self::CONN_CREATE_SCHEMA: A connection to the new DB, for creating schemas and
129 * other similar objects in the new DB.
130 * - self::CONN_CREATE_TABLES: A connection with a role suitable for creating tables.
131 * @return ConnectionStatus On success, a connection object will be in the value member.
132 */
133 protected function openConnection( string $type ) {
134 switch ( $type ) {
135 case self::CONN_CREATE_DATABASE:
136 return $this->openConnectionToAnyDB(
137 $this->getVar( '_InstallUser' ),
138 $this->getVar( '_InstallPassword' ) );
139 case self::CONN_CREATE_SCHEMA:
140 return $this->openConnectionWithParams(
141 $this->getVar( '_InstallUser' ),
142 $this->getVar( '_InstallPassword' ),
143 $this->getVar( 'wgDBname' ),
144 $this->getVar( 'wgDBmwschema' ) );
145 case self::CONN_CREATE_TABLES:
146 $status = $this->openConnection( self::CONN_CREATE_SCHEMA );
147 if ( $status->isOK() ) {
148 $status->merge( $this->changeConnTypeFromSchemaToTables( $status->getDB() ) );
149 }
150
151 return $status;
152 default:
153 throw new InvalidArgumentException( "Invalid connection type: \"$type\"" );
154 }
155 }
156
157 protected function changeConnTypeFromSchemaToTables( Database $conn ) {
158 if ( !( $conn instanceof DatabasePostgres ) ) {
159 throw new InvalidArgumentException( 'Invalid connection type' );
160 }
161 $status = new ConnectionStatus( $conn );
162 $schema = $this->getVar( 'wgDBmwschema' );
163 if ( !$conn->schemaExists( $schema ) ) {
164 $status->fatal( 'config-install-pg-schema-not-exist' );
165 return $status;
166 }
167 $conn->determineCoreSchema( $schema );
168
169 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
170 $conn->query( "SET ROLE $safeRole", __METHOD__ );
171 return $status;
172 }
173
174 public function openConnectionToAnyDB( $user, $password ) {
175 $dbs = [
176 'template1',
177 'postgres',
178 ];
179 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
180 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
181 }
182 $conn = false;
183 $status = new ConnectionStatus;
184 foreach ( $dbs as $db ) {
185 try {
186 $p = [
187 'host' => $this->getVar( 'wgDBserver' ),
188 'port' => $this->getVar( 'wgDBport' ),
189 'user' => $user,
190 'password' => $password ?? '',
191 'ssl' => $this->getVar( 'wgDBssl' ),
192 'dbname' => $db
193 ];
194 $conn = ( new DatabaseFactory() )->create( 'postgres', $p );
195 } catch ( DBConnectionError $error ) {
196 $conn = false;
197 $status->fatal( 'config-pg-test-error', $db,
198 $error->getMessage() );
199 }
200 if ( $conn !== false ) {
201 break;
202 }
203 }
204 if ( $conn !== false ) {
205 return new ConnectionStatus( $conn );
206 } else {
207 return $status;
208 }
209 }
210
211 protected function getInstallUserPermissions() {
212 $status = $this->getConnection( self::CONN_CREATE_DATABASE );
213 if ( !$status->isOK() ) {
214 return false;
215 }
216 $conn = $status->getDB();
217 $superuser = $this->getVar( '_InstallUser' );
218
219 $row = $conn->selectRow( 'pg_catalog.pg_roles', '*',
220 [ 'rolname' => $superuser ], __METHOD__ );
221
222 return $row;
223 }
224
225 public function canCreateAccounts() {
226 $perms = $this->getInstallUserPermissions();
227 return ( $perms && $perms->rolsuper ) || $perms->rolcreaterole;
228 }
229
230 protected function isSuperUser() {
231 $perms = $this->getInstallUserPermissions();
232 return $perms && $perms->rolsuper;
233 }
234
235 /**
236 * Returns true if the install user is able to create objects owned
237 * by the web user, false otherwise.
238 * @return bool
239 */
240 public function canCreateObjectsForWebUser() {
241 if ( $this->isSuperUser() ) {
242 return true;
243 }
244
245 $status = $this->getConnection( self::CONN_CREATE_DATABASE );
246 if ( !$status->isOK() ) {
247 return false;
248 }
249 $conn = $status->getDB();
250 $installerId = $conn->selectField( 'pg_catalog.pg_roles', 'oid',
251 [ 'rolname' => $this->getVar( '_InstallUser' ) ], __METHOD__ );
252 $webId = $conn->selectField( 'pg_catalog.pg_roles', 'oid',
253 [ 'rolname' => $this->getVar( 'wgDBuser' ) ], __METHOD__ );
254
255 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
256 }
257
258 /**
259 * Recursive helper for canCreateObjectsForWebUser().
260 * @param Database $conn
261 * @param int $targetMember Role ID of the member to look for
262 * @param int $group Role ID of the group to look for
263 * @param int $maxDepth Maximum recursive search depth
264 * @return bool
265 */
266 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
267 if ( $targetMember === $group ) {
268 // A role is always a member of itself
269 return true;
270 }
271 // Get all members of the given group
272 $res = $conn->select( 'pg_catalog.pg_auth_members', [ 'member' ],
273 [ 'roleid' => $group ], __METHOD__ );
274 foreach ( $res as $row ) {
275 if ( $row->member == $targetMember ) {
276 // Found target member
277 return true;
278 }
279 // Recursively search each member of the group to see if the target
280 // is a member of it, up to the given maximum depth.
281 if ( $maxDepth > 0 &&
282 $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 )
283 ) {
284 // Found member of member
285 return true;
286 }
287 }
288
289 return false;
290 }
291
292 public function preInstall() {
293 $createDbAccount = [
294 'name' => 'user',
295 'callback' => [ $this, 'setupUser' ],
296 ];
297 $plpgCB = [
298 'name' => 'pg-plpgsql',
299 'callback' => [ $this, 'setupPLpgSQL' ],
300 ];
301 $schemaCB = [
302 'name' => 'schema',
303 'callback' => [ $this, 'setupSchema' ]
304 ];
305
306 if ( $this->getVar( '_CreateDBAccount' ) ) {
307 $this->parent->addInstallStep( $createDbAccount, 'database' );
308 }
309 $this->parent->addInstallStep( $plpgCB, 'database' );
310 $this->parent->addInstallStep( $schemaCB, 'database' );
311 }
312
313 public function setupDatabase() {
314 $status = $this->getConnection( self::CONN_CREATE_DATABASE );
315 if ( !$status->isOK() ) {
316 return $status;
317 }
318
319 $conn = $status->getDB();
320 $dbName = $this->getVar( 'wgDBname' );
321
322 $exists = (bool)$conn->selectField( 'pg_catalog.pg_database', '1',
323 [ 'datname' => $dbName ], __METHOD__ );
324 if ( !$exists ) {
325 $safedb = $conn->addIdentifierQuotes( $dbName );
326 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
327 }
328
329 return Status::newGood();
330 }
331
332 public function setupSchema() {
333 // Get a connection to the target database
334 $status = $this->getConnection( self::CONN_CREATE_SCHEMA );
335 if ( !$status->isOK() ) {
336 return $status;
337 }
338 $conn = $status->getDB();
339 '@phan-var DatabasePostgres $conn'; /** @var DatabasePostgres $conn */
340
341 // Create the schema if necessary
342 $schema = $this->getVar( 'wgDBmwschema' );
343 $safeschema = $conn->addIdentifierQuotes( $schema );
344 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
345 if ( !$conn->schemaExists( $schema ) ) {
346 try {
347 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser", __METHOD__ );
348 } catch ( DBQueryError $e ) {
349 return Status::newFatal( 'config-install-pg-schema-failed',
350 $this->getVar( '_InstallUser' ), $schema );
351 }
352 }
353
354 return Status::newGood();
355 }
356
357 public function setupUser() {
358 if ( !$this->getVar( '_CreateDBAccount' ) ) {
359 return Status::newGood();
360 }
361
362 $status = $this->getConnection( self::CONN_CREATE_DATABASE );
363 if ( !$status->isOK() ) {
364 return $status;
365 }
366 $conn = $status->getDB();
367 '@phan-var DatabasePostgres $conn'; /** @var DatabasePostgres $conn */
368
369 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
370 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
371
372 // Check if the user already exists
373 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
374 if ( !$userExists ) {
375 // Create the user
376 try {
377 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
378
379 // If the install user is not a superuser, we need to make the install
380 // user a member of the new user's group, so that the install user will
381 // be able to create a schema and other objects on behalf of the new user.
382 if ( !$this->isSuperUser() ) {
383 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
384 }
385
386 $conn->query( $sql, __METHOD__ );
387 } catch ( DBQueryError $e ) {
388 return Status::newFatal( 'config-install-user-create-failed',
389 $this->getVar( 'wgDBuser' ), $e->getMessage() );
390 }
391 }
392
393 return Status::newGood();
394 }
395
396 public function getLocalSettings() {
397 $port = $this->getVar( 'wgDBport' );
398 $useSsl = $this->getVar( 'wgDBssl' ) ? 'true' : 'false';
399 $schema = $this->getVar( 'wgDBmwschema' );
400
401 return "# Postgres specific settings
402 \$wgDBport = \"{$port}\";
403 \$wgDBssl = {$useSsl};
404 \$wgDBmwschema = \"{$schema}\";";
405 }
406
407 public function preUpgrade() {
408 global $wgDBuser, $wgDBpassword;
409
410 # Normal user and password are selected after this step, so for now
411 # just copy these two
412 $wgDBuser = $this->getVar( '_InstallUser' );
413 $wgDBpassword = $this->getVar( '_InstallPassword' );
414 }
415
416 public function getGlobalDefaults() {
417 // The default $wgDBmwschema is null, which breaks Postgres and other DBMSes that require
418 // the use of a schema, so we need to set it here
419 return array_merge( parent::getGlobalDefaults(), [
420 'wgDBmwschema' => 'mediawiki',
421 ] );
422 }
423
424 public function setupPLpgSQL() {
425 // Connect as the install user, since it owns the database and so is
426 // the user that needs to run "CREATE EXTENSION"
427 $status = $this->getConnection( self::CONN_CREATE_SCHEMA );
428 if ( !$status->isOK() ) {
429 return $status;
430 }
431 $conn = $status->getDB();
432 try {
433 $conn->query( 'CREATE EXTENSION IF NOT EXISTS plpgsql', __METHOD__ );
434 } catch ( DBQueryError $e ) {
435 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
436 }
437 return Status::newGood();
438 }
439 }