[BUGFIX] Support mysql socket connection
[Packages/TYPO3.CMS.git] / typo3 / sysext / install / Classes / Controller / Action / Step / DatabaseConnect.php
1 <?php
2 namespace TYPO3\CMS\Install\Controller\Action\Step;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2013 Christian Kuhn <lolli@schwarzbu.ch>
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 *
19 * This script is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * This copyright notice MUST APPEAR in all copies of the script!
25 ***************************************************************/
26
27 use TYPO3\CMS\Install\Controller\Action;
28
29 /**
30 * Database connect step:
31 * - Needs execution if database credentials are not set or fail to connect
32 * - Renders fields for database connection fields
33 * - Sets database credentials in LocalConfiguration
34 * - Loads / unloads ext:dbal and ext:adodb if requested
35 */
36 class DatabaseConnect extends Action\AbstractAction implements StepInterface {
37
38 /**
39 * Execute database step:
40 * - Load / unload dbal & adodb
41 * - Set database connect credentials in LocalConfiguration
42 *
43 * @return array<\TYPO3\CMS\Install\Status\StatusInterface>
44 */
45 public function execute() {
46 $result = array();
47
48 /** @var $configurationManager \TYPO3\CMS\Core\Configuration\ConfigurationManager */
49 $configurationManager = $this->objectManager->get('TYPO3\\CMS\\Core\\Configuration\\ConfigurationManager');
50
51 $postValues = $this->postValues['values'];
52 if (isset($postValues['loadDbal'])) {
53 $result[] = $this->executeLoadDbalExtension();
54 } elseif ($postValues['unloadDbal']) {
55 $result[] = $this->executeUnloadDbalExtension();
56 } elseif ($postValues['setDbalDriver']) {
57 $driver = $postValues['setDbalDriver'];
58 switch ($driver) {
59 case 'mssql':
60 case 'odbc_mssql':
61 $driverConfig = array(
62 'useNameQuote' => TRUE,
63 'quoteClob' => FALSE,
64 );
65 break;
66 case 'oci8':
67 $driverConfig = array(
68 'driverOptions' => array(
69 'connectSID' => '',
70 ),
71 );
72 break;
73 }
74 $config = array(
75 '_DEFAULT' => array(
76 'type' => 'adodb',
77 'config' => array(
78 'driver' => $driver,
79 )
80 )
81 );
82 if (isset($driverConfig)) {
83 $config['_DEFAULT']['config'] = array_merge($config['_DEFAULT']['config'], $driverConfig);
84 }
85 $configurationManager->setLocalConfigurationValueByPath('EXTCONF/dbal/handlerCfg', $config);
86 } else {
87 $localConfigurationPathValuePairs = array();
88
89 if ($this->isDbalEnabled()) {
90 $config = $configurationManager->getConfigurationValueByPath('EXTCONF/dbal/handlerCfg');
91 $driver = $config['_DEFAULT']['config']['driver'];
92 if ($driver === 'oci8') {
93 $configurationManager['_DEFAULT']['config']['driverOptions']['connectSID']
94 = $postValues['type'] === 'sid' ? TRUE : FALSE;
95 }
96 }
97
98 if (isset($postValues['username'])) {
99 $value = $postValues['username'];
100 if (strlen($value) <= 50) {
101 $localConfigurationPathValuePairs['DB/username'] = $value;
102 } else {
103 /** @var $errorStatus \TYPO3\CMS\Install\Status\ErrorStatus */
104 $errorStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\ErrorStatus');
105 $errorStatus->setTitle('Database username not valid');
106 $errorStatus->setMessage('Given username must be shorter than fifty characters.');
107 $result[] = $errorStatus;
108 }
109 }
110
111 if (isset($postValues['password'])) {
112 $value = $postValues['password'];
113 if (strlen($value) <= 50) {
114 $localConfigurationPathValuePairs['DB/password'] = $value;
115 } else {
116 /** @var $errorStatus \TYPO3\CMS\Install\Status\ErrorStatus */
117 $errorStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\ErrorStatus');
118 $errorStatus->setTitle('Database password not valid');
119 $errorStatus->setMessage('Given password must be shorter than fifty characters.');
120 $result[] = $errorStatus;
121 }
122 }
123
124 if (isset($postValues['host'])) {
125 $value = $postValues['host'];
126 if (preg_match('/^[a-zA-Z0-9_\\.-]+(:.+)?$/', $value) && strlen($value) <= 50) {
127 $localConfigurationPathValuePairs['DB/host'] = $value;
128 } else {
129 /** @var $errorStatus \TYPO3\CMS\Install\Status\ErrorStatus */
130 $errorStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\ErrorStatus');
131 $errorStatus->setTitle('Database host not valid');
132 $errorStatus->setMessage('Given host is not alphanumeric (a-z, A-Z, 0-9 or _-.:) or longer than fifty characters.');
133 $result[] = $errorStatus;
134 }
135 }
136
137 if (isset($postValues['port']) && $postValues['host'] !== 'localhost') {
138 $value = $postValues['port'];
139 if (preg_match('/^[0-9]+(:.+)?$/', $value) && $value > 0 && $value <= 65535) {
140 $localConfigurationPathValuePairs['DB/port'] = (int)$value;
141 } else {
142 /** @var $errorStatus \TYPO3\CMS\Install\Status\ErrorStatus */
143 $errorStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\ErrorStatus');
144 $errorStatus->setTitle('Database port not valid');
145 $errorStatus->setMessage('Given port is not numeric or within range 1 to 65535.');
146 $result[] = $errorStatus;
147 }
148 }
149
150 if (isset($postValues['socket']) && $postValues['socket'] !== '') {
151 if (@file_exists($postValues['socket'])) {
152 $localConfigurationPathValuePairs['DB/socket'] = $postValues['socket'];
153 } else {
154 /** @var $errorStatus \TYPO3\CMS\Install\Status\ErrorStatus */
155 $errorStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\ErrorStatus');
156 $errorStatus->setTitle('Socket does not exist');
157 $errorStatus->setMessage('Given socket location does not exist on server.');
158 $result[] = $errorStatus;
159 }
160 }
161
162 if (isset($postValues['database'])) {
163 $value = $postValues['database'];
164 if (strlen($value) <= 50) {
165 $localConfigurationPathValuePairs['DB/database'] = $value;
166 } else {
167 /** @var $errorStatus \TYPO3\CMS\Install\Status\ErrorStatus */
168 $errorStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\ErrorStatus');
169 $errorStatus->setTitle('Database name not valid');
170 $errorStatus->setMessage('Given database name must be shorter than fifty characters.');
171 $result[] = $errorStatus;
172 }
173 }
174
175 if (!empty($localConfigurationPathValuePairs)) {
176 $configurationManager->setLocalConfigurationValuesByPathValuePairs($localConfigurationPathValuePairs);
177
178 // After setting new credentials, test again and create an error message if connect is not successful
179 // @TODO: This could be simplified, if isConnectSuccessful could be released from TYPO3_CONF_VARS
180 // and feeded with connect values directly in order to obsolete the bootstrap reload.
181 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()
182 ->populateLocalConfiguration()
183 ->setCoreCacheToNullBackend();
184 if ($this->isDbalEnabled()) {
185 require(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('dbal') . 'ext_localconf.php');
186 $GLOBALS['typo3CacheManager']->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
187 }
188 if (!$this->isConnectSuccessful()) {
189 /** @var $errorStatus \TYPO3\CMS\Install\Status\ErrorStatus */
190 $errorStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\ErrorStatus');
191 $errorStatus->setTitle('Database connect not successful');
192 $errorStatus->setMessage('Connecting the database with given settings failed. Please check.');
193 $result[] = $errorStatus;
194 }
195 }
196 }
197
198 return $result;
199 }
200
201 /**
202 * Step needs to be executed if database connection is not successful.
203 *
204 * @return boolean
205 */
206 public function needsExecution() {
207 if (!$this->isConnectSuccessful()) {
208 return TRUE;
209 }
210 if (!isset($GLOBALS['TYPO3_CONF_VARS']['DB']['host'])
211 || (!isset($GLOBALS['TYPO3_CONF_VARS']['DB']['port']) && $GLOBALS['TYPO3_CONF_VARS']['DB']['host'] !== 'localhost')
212 ) {
213 return TRUE;
214 }
215 return FALSE;
216 }
217
218 /**
219 * Render this step
220 *
221 * @return string
222 */
223 public function handle() {
224 $this->initialize();
225
226 $isDbalEnabled = $this->isDbalEnabled();
227 $this->view
228 ->assign('isDbalEnabled', $isDbalEnabled)
229 ->assign('username', $GLOBALS['TYPO3_CONF_VARS']['DB']['username'] ?: '')
230 ->assign('password', $GLOBALS['TYPO3_CONF_VARS']['DB']['password'] ?: '')
231 ->assign('host', $this->getConfiguredHost() ?: '127.0.0.1')
232 ->assign('port', $this->getConfiguredOrDefaultPort())
233 ->assign('database', $GLOBALS['TYPO3_CONF_VARS']['DB']['database'] ?: '')
234 ->assign('socket', $GLOBALS['TYPO3_CONF_VARS']['DB']['socket'] ?: '');
235
236 if ($isDbalEnabled) {
237 $this->view->assign('selectedDbalDriver', $this->getSelectedDbalDriver());
238 $this->view->assign('dbalDrivers', $this->getAvailableDbalDrivers());
239 $this->setDbalInputFieldsToRender();
240 } else {
241 $this->view
242 ->assign('renderConnectDetailsUsername', TRUE)
243 ->assign('renderConnectDetailsPassword', TRUE)
244 ->assign('renderConnectDetailsHost', TRUE)
245 ->assign('renderConnectDetailsPort', TRUE)
246 ->assign('renderConnectDetailsSocket', TRUE);
247 }
248
249 return $this->view->render();
250 }
251
252 /**
253 * Render fields required for successful connect based on dbal driver selection.
254 * Hint: There is a code duplication in handle() and this method. This
255 * is done by intention to keep this code area easy to maintain and understand.
256 *
257 * @return void
258 */
259 protected function setDbalInputFieldsToRender() {
260 $driver = $this->getSelectedDbalDriver();
261 switch($driver) {
262 case 'mssql':
263 case 'odbc_mssql':
264 case 'postgres':
265 $this->view
266 ->assign('renderConnectDetailsUsername', TRUE)
267 ->assign('renderConnectDetailsPassword', TRUE)
268 ->assign('renderConnectDetailsHost', TRUE)
269 ->assign('renderConnectDetailsPort', TRUE)
270 ->assign('renderConnectDetailsDatabase', TRUE);
271 break;
272 case 'oci8':
273 $this->view
274 ->assign('renderConnectDetailsUsername', TRUE)
275 ->assign('renderConnectDetailsPassword', TRUE)
276 ->assign('renderConnectDetailsHost', TRUE)
277 ->assign('renderConnectDetailsPort', TRUE)
278 ->assign('renderConnectDetailsDatabase', TRUE)
279 ->assign('renderConnectDetailsOracleSidConnect', TRUE);
280 $type = isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['handlerCfg']['_DEFAULT']['config']['driverOptions']['connectSID'])
281 ? $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['handlerCfg']['_DEFAULT']['config']['driverOptions']['connectSID']
282 : '';
283 if ($type === TRUE) {
284 $this->view->assign('oracleSidSelected', TRUE);
285 }
286 break;
287 }
288 }
289
290 /**
291 * Render connect port and label
292 *
293 * @return integer Configured or default port
294 */
295 protected function getConfiguredOrDefaultPort() {
296 $configuredPort = (int)$this->getConfiguredPort();
297 if (!$configuredPort) {
298 if ($this->isDbalEnabled()) {
299 $driver = $this->getSelectedDbalDriver();
300 switch ($driver) {
301 case 'postgres':
302 $port = 5432;
303 break;
304 case 'mssql':
305 case 'odbc_mssql':
306 $port = 1433;
307 break;
308 case 'oci8':
309 $port = 1521;
310 break;
311 default:
312 $port = 3306;
313 }
314 } else {
315 $port = 3306;
316 }
317 } else {
318 $port = $configuredPort;
319 }
320 return $port;
321 }
322
323 /**
324 * Test connection with given credentials
325 *
326 * @return boolean TRUE if connect was successful
327 */
328 protected function isConnectSuccessful() {
329 /** @var $databaseConnection \TYPO3\CMS\Core\Database\DatabaseConnection */
330 $databaseConnection = $this->objectManager->get('TYPO3\\CMS\\Core\\Database\\DatabaseConnection');
331
332 if ($this->isDbalEnabled()) {
333 // Set additional connect information based on dbal driver. postgres for example needs
334 // database name already for connect.
335 if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['database'])) {
336 $databaseConnection->setDatabaseName($GLOBALS['TYPO3_CONF_VARS']['DB']['database']);
337 }
338 }
339
340 $username = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['username']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['username'] : '';
341 $databaseConnection->setDatabaseUsername($username);
342 $password = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['password']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['password'] : '';
343 $databaseConnection->setDatabasePassword($password);
344 $databaseConnection->setDatabaseHost($this->getConfiguredHost());
345 $databaseConnection->setDatabasePort($this->getConfiguredPort());
346 $databaseConnection->setDatabaseSocket($this->getConfiguredSocket());
347
348 $result = FALSE;
349 if (@$databaseConnection->sql_pconnect()) {
350 $result = TRUE;
351 }
352 return $result;
353 }
354
355 /**
356 * Returns a list of database drivers that are available on current server.
357 *
358 * @return array
359 */
360 protected function getAvailableDbalDrivers() {
361 $supportedDrivers = $this->getSupportedDbalDrivers();
362 $availableDrivers = array();
363 $selectedDbalDriver = $this->getSelectedDbalDriver();
364 foreach ($supportedDrivers as $abstractionLayer => $drivers) {
365 foreach ($drivers as $driver => $info) {
366 if (isset($info['combine']) && $info['combine'] === 'OR') {
367 $isAvailable = FALSE;
368 } else {
369 $isAvailable = TRUE;
370 }
371 // Loop through each PHP module dependency to ensure it is loaded
372 foreach ($info['extensions'] as $extension) {
373 if (isset($info['combine']) && $info['combine'] === 'OR') {
374 $isAvailable |= extension_loaded($extension);
375 } else {
376 $isAvailable &= extension_loaded($extension);
377 }
378 }
379 if ($isAvailable) {
380 if (!isset($availableDrivers[$abstractionLayer])) {
381 $availableDrivers[$abstractionLayer] = array();
382 }
383 $availableDrivers[$abstractionLayer][$driver] = array();
384 $availableDrivers[$abstractionLayer][$driver]['driver'] = $driver;
385 $availableDrivers[$abstractionLayer][$driver]['label'] = $info['label'];
386 $availableDrivers[$abstractionLayer][$driver]['selected'] = FALSE;
387 if ($selectedDbalDriver === $driver) {
388 $availableDrivers[$abstractionLayer][$driver]['selected'] = TRUE;
389 }
390 }
391 }
392 }
393 return $availableDrivers;
394 }
395
396 /**
397 * Returns a list of DBAL supported database drivers, with a
398 * user-friendly name and any PHP module dependency.
399 *
400 * @return array
401 */
402 protected function getSupportedDbalDrivers() {
403 $supportedDrivers = array(
404 'Native' => array(
405 'mssql' => array(
406 'label' => 'Microsoft SQL Server',
407 'extensions' => array('mssql')
408 ),
409 'oci8' => array(
410 'label' => 'Oracle OCI8',
411 'extensions' => array('oci8')
412 ),
413 'postgres' => array(
414 'label' => 'PostgreSQL',
415 'extensions' => array('pgsql')
416 )
417 ),
418 'ODBC' => array(
419 'odbc_mssql' => array(
420 'label' => 'Microsoft SQL Server',
421 'extensions' => array('odbc', 'mssql')
422 )
423 )
424 );
425 return $supportedDrivers;
426 }
427
428 /**
429 * Get selected dbal driver if any
430 *
431 * @return string Dbal driver or empty string if not yet selected
432 */
433 protected function getSelectedDbalDriver() {
434 if (isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['handlerCfg']['_DEFAULT']['config']['driver'])) {
435 return $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['handlerCfg']['_DEFAULT']['config']['driver'];
436 }
437 return '';
438 }
439
440 /**
441 * Adds dbal and adodb to list of loaded extensions
442 *
443 * @return \TYPO3\CMS\Install\Status\StatusInterface
444 */
445 protected function executeLoadDbalExtension() {
446 if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('adodb')) {
447 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::loadExtension('adodb');
448 }
449 if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('dbal')) {
450 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::loadExtension('dbal');
451 }
452 /** @var $errorStatus \TYPO3\CMS\Install\Status\WarningStatus */
453 $warningStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\WarningStatus');
454 $warningStatus->setTitle('Loaded database abstraction layer');
455 return $warningStatus;
456 }
457
458 /**
459 * Remove dbal and adodb from list of loaded extensions
460 *
461 * @return \TYPO3\CMS\Install\Status\StatusInterface
462 */
463 protected function executeUnloadDbalExtension() {
464 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('adodb')) {
465 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::unloadExtension('adodb');
466 }
467 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('dbal')) {
468 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::unloadExtension('dbal');
469 }
470 // @TODO: Remove configuration from TYPO3_CONF_VARS['EXTCONF']['dbal']
471 /** @var $errorStatus \TYPO3\CMS\Install\Status\WarningStatus */
472 $warningStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\WarningStatus');
473 $warningStatus->setTitle('Removed database abstraction layer');
474 return $warningStatus;
475 }
476
477 /**
478 * Returns configured host with port split off if given
479 *
480 * @return string
481 */
482 protected function getConfiguredHost() {
483 $host = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['host']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['host'] : '';
484 $port = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['port']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['port'] : '';
485 if (strlen($port) < 1 && strpos($host, ':') > 0) {
486 list($host) = explode(':', $host);
487 }
488 return $host;
489 }
490
491 /**
492 * Returns configured port. Gets port from host value if port is not yet set.
493 *
494 * @return integer
495 */
496 protected function getConfiguredPort() {
497 $host = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['host']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['host'] : '';
498 $port = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['port']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['port'] : '';
499 if (!strlen($port) > 0 && strpos($host, ':') > 0) {
500 $hostPortArray = explode(':', $host);
501 $port = $hostPortArray[1];
502 }
503 return (int)$port;
504 }
505
506 /**
507 * Returns configured socket, if set
508 *
509 * @return string|NULL
510 */
511 protected function getConfiguredSocket() {
512 $socket = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['socket']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['socket'] : NULL;
513 return $socket;
514 }
515 }
516 ?>