[TASK] Refactor misleading method name
[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 if ($this->isConnectSuccessful()) {
214 $this->storeConfiguration();
215 throw new \TYPO3\CMS\Install\Controller\Exception\RedirectException(
216 'Configuration changed, redirect needed',
217 1377611168
218 );
219 }
220 return TRUE;
221 }
222 return FALSE;
223 }
224
225 /**
226 * Render this step
227 *
228 * @return string
229 */
230 public function handle() {
231 $this->initializeHandle();
232
233 $isDbalEnabled = $this->isDbalEnabled();
234 $this->view
235 ->assign('isDbalEnabled', $isDbalEnabled)
236 ->assign('username', $GLOBALS['TYPO3_CONF_VARS']['DB']['username'] ?: '')
237 ->assign('password', $GLOBALS['TYPO3_CONF_VARS']['DB']['password'] ?: '')
238 ->assign('host', $this->getConfiguredHost() ?: '127.0.0.1')
239 ->assign('port', $this->getConfiguredOrDefaultPort())
240 ->assign('database', $GLOBALS['TYPO3_CONF_VARS']['DB']['database'] ?: '')
241 ->assign('socket', $GLOBALS['TYPO3_CONF_VARS']['DB']['socket'] ?: '');
242
243 if ($isDbalEnabled) {
244 $this->view->assign('selectedDbalDriver', $this->getSelectedDbalDriver());
245 $this->view->assign('dbalDrivers', $this->getAvailableDbalDrivers());
246 $this->setDbalInputFieldsToRender();
247 } else {
248 $this->view
249 ->assign('renderConnectDetailsUsername', TRUE)
250 ->assign('renderConnectDetailsPassword', TRUE)
251 ->assign('renderConnectDetailsHost', TRUE)
252 ->assign('renderConnectDetailsPort', TRUE)
253 ->assign('renderConnectDetailsSocket', TRUE);
254 }
255
256 return $this->view->render();
257 }
258
259 /**
260 * Render fields required for successful connect based on dbal driver selection.
261 * Hint: There is a code duplication in handle() and this method. This
262 * is done by intention to keep this code area easy to maintain and understand.
263 *
264 * @return void
265 */
266 protected function setDbalInputFieldsToRender() {
267 $driver = $this->getSelectedDbalDriver();
268 switch($driver) {
269 case 'mssql':
270 case 'odbc_mssql':
271 case 'postgres':
272 $this->view
273 ->assign('renderConnectDetailsUsername', TRUE)
274 ->assign('renderConnectDetailsPassword', TRUE)
275 ->assign('renderConnectDetailsHost', TRUE)
276 ->assign('renderConnectDetailsPort', TRUE)
277 ->assign('renderConnectDetailsDatabase', TRUE);
278 break;
279 case 'oci8':
280 $this->view
281 ->assign('renderConnectDetailsUsername', TRUE)
282 ->assign('renderConnectDetailsPassword', TRUE)
283 ->assign('renderConnectDetailsHost', TRUE)
284 ->assign('renderConnectDetailsPort', TRUE)
285 ->assign('renderConnectDetailsDatabase', TRUE)
286 ->assign('renderConnectDetailsOracleSidConnect', TRUE);
287 $type = isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['handlerCfg']['_DEFAULT']['config']['driverOptions']['connectSID'])
288 ? $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['handlerCfg']['_DEFAULT']['config']['driverOptions']['connectSID']
289 : '';
290 if ($type === TRUE) {
291 $this->view->assign('oracleSidSelected', TRUE);
292 }
293 break;
294 }
295 }
296
297 /**
298 * Render connect port and label
299 *
300 * @return integer Configured or default port
301 */
302 protected function getConfiguredOrDefaultPort() {
303 $configuredPort = (int)$this->getConfiguredPort();
304 if (!$configuredPort) {
305 if ($this->isDbalEnabled()) {
306 $driver = $this->getSelectedDbalDriver();
307 switch ($driver) {
308 case 'postgres':
309 $port = 5432;
310 break;
311 case 'mssql':
312 case 'odbc_mssql':
313 $port = 1433;
314 break;
315 case 'oci8':
316 $port = 1521;
317 break;
318 default:
319 $port = 3306;
320 }
321 } else {
322 $port = 3306;
323 }
324 } else {
325 $port = $configuredPort;
326 }
327 return $port;
328 }
329
330 /**
331 * Test connection with given credentials
332 *
333 * @return boolean TRUE if connect was successful
334 */
335 protected function isConnectSuccessful() {
336 /** @var $databaseConnection \TYPO3\CMS\Core\Database\DatabaseConnection */
337 $databaseConnection = $this->objectManager->get('TYPO3\\CMS\\Core\\Database\\DatabaseConnection');
338
339 if ($this->isDbalEnabled()) {
340 // Set additional connect information based on dbal driver. postgres for example needs
341 // database name already for connect.
342 if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['database'])) {
343 $databaseConnection->setDatabaseName($GLOBALS['TYPO3_CONF_VARS']['DB']['database']);
344 }
345 }
346
347 $username = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['username']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['username'] : '';
348 $databaseConnection->setDatabaseUsername($username);
349 $password = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['password']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['password'] : '';
350 $databaseConnection->setDatabasePassword($password);
351 $databaseConnection->setDatabaseHost($this->getConfiguredHost());
352 $databaseConnection->setDatabasePort($this->getConfiguredOrDefaultPort());
353 $databaseConnection->setDatabaseSocket($this->getConfiguredSocket());
354
355 $result = FALSE;
356 if (@$databaseConnection->sql_pconnect()) {
357 $result = TRUE;
358 }
359 return $result;
360 }
361
362 /**
363 * Returns a list of database drivers that are available on current server.
364 *
365 * @return array
366 */
367 protected function getAvailableDbalDrivers() {
368 $supportedDrivers = $this->getSupportedDbalDrivers();
369 $availableDrivers = array();
370 $selectedDbalDriver = $this->getSelectedDbalDriver();
371 foreach ($supportedDrivers as $abstractionLayer => $drivers) {
372 foreach ($drivers as $driver => $info) {
373 if (isset($info['combine']) && $info['combine'] === 'OR') {
374 $isAvailable = FALSE;
375 } else {
376 $isAvailable = TRUE;
377 }
378 // Loop through each PHP module dependency to ensure it is loaded
379 foreach ($info['extensions'] as $extension) {
380 if (isset($info['combine']) && $info['combine'] === 'OR') {
381 $isAvailable |= extension_loaded($extension);
382 } else {
383 $isAvailable &= extension_loaded($extension);
384 }
385 }
386 if ($isAvailable) {
387 if (!isset($availableDrivers[$abstractionLayer])) {
388 $availableDrivers[$abstractionLayer] = array();
389 }
390 $availableDrivers[$abstractionLayer][$driver] = array();
391 $availableDrivers[$abstractionLayer][$driver]['driver'] = $driver;
392 $availableDrivers[$abstractionLayer][$driver]['label'] = $info['label'];
393 $availableDrivers[$abstractionLayer][$driver]['selected'] = FALSE;
394 if ($selectedDbalDriver === $driver) {
395 $availableDrivers[$abstractionLayer][$driver]['selected'] = TRUE;
396 }
397 }
398 }
399 }
400 return $availableDrivers;
401 }
402
403 /**
404 * Returns a list of DBAL supported database drivers, with a
405 * user-friendly name and any PHP module dependency.
406 *
407 * @return array
408 */
409 protected function getSupportedDbalDrivers() {
410 $supportedDrivers = array(
411 'Native' => array(
412 'mssql' => array(
413 'label' => 'Microsoft SQL Server',
414 'extensions' => array('mssql')
415 ),
416 'oci8' => array(
417 'label' => 'Oracle OCI8',
418 'extensions' => array('oci8')
419 ),
420 'postgres' => array(
421 'label' => 'PostgreSQL',
422 'extensions' => array('pgsql')
423 )
424 ),
425 'ODBC' => array(
426 'odbc_mssql' => array(
427 'label' => 'Microsoft SQL Server',
428 'extensions' => array('odbc', 'mssql')
429 )
430 )
431 );
432 return $supportedDrivers;
433 }
434
435 /**
436 * Get selected dbal driver if any
437 *
438 * @return string Dbal driver or empty string if not yet selected
439 */
440 protected function getSelectedDbalDriver() {
441 if (isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['handlerCfg']['_DEFAULT']['config']['driver'])) {
442 return $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['handlerCfg']['_DEFAULT']['config']['driver'];
443 }
444 return '';
445 }
446
447 /**
448 * Adds dbal and adodb to list of loaded extensions
449 *
450 * @return \TYPO3\CMS\Install\Status\StatusInterface
451 */
452 protected function executeLoadDbalExtension() {
453 if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('adodb')) {
454 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::loadExtension('adodb');
455 }
456 if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('dbal')) {
457 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::loadExtension('dbal');
458 }
459 /** @var $errorStatus \TYPO3\CMS\Install\Status\WarningStatus */
460 $warningStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\WarningStatus');
461 $warningStatus->setTitle('Loaded database abstraction layer');
462 return $warningStatus;
463 }
464
465 /**
466 * Remove dbal and adodb from list of loaded extensions
467 *
468 * @return \TYPO3\CMS\Install\Status\StatusInterface
469 */
470 protected function executeUnloadDbalExtension() {
471 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('adodb')) {
472 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::unloadExtension('adodb');
473 }
474 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('dbal')) {
475 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::unloadExtension('dbal');
476 }
477 // @TODO: Remove configuration from TYPO3_CONF_VARS['EXTCONF']['dbal']
478 /** @var $errorStatus \TYPO3\CMS\Install\Status\WarningStatus */
479 $warningStatus = $this->objectManager->get('TYPO3\\CMS\\Install\\Status\\WarningStatus');
480 $warningStatus->setTitle('Removed database abstraction layer');
481 return $warningStatus;
482 }
483
484 /**
485 * Returns configured host with port split off if given
486 *
487 * @return string
488 */
489 protected function getConfiguredHost() {
490 $host = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['host']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['host'] : '';
491 $port = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['port']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['port'] : '';
492 if (strlen($port) < 1 && substr_count($host, 0, ':') === 1) {
493 list($host) = explode(':', $host);
494 }
495 return $host;
496 }
497
498 /**
499 * Returns configured port. Gets port from host value if port is not yet set.
500 *
501 * @return integer
502 */
503 protected function getConfiguredPort() {
504 $host = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['host']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['host'] : '';
505 $port = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['port']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['port'] : '';
506 if (!strlen($port) > 0 && substr_count($host, 0, ':') === 1) {
507 $hostPortArray = explode(':', $host);
508 $port = $hostPortArray[1];
509 }
510 return (int)$port;
511 }
512
513 /**
514 * Returns configured socket, if set
515 *
516 * @return string|NULL
517 */
518 protected function getConfiguredSocket() {
519 $socket = isset($GLOBALS['TYPO3_CONF_VARS']['DB']['socket']) ? $GLOBALS['TYPO3_CONF_VARS']['DB']['socket'] : NULL;
520 return $socket;
521 }
522
523 /**
524 * Stores detected connection configuration
525 *
526 * @return void
527 */
528 protected function storeConfiguration() {
529 $localConfigurationPathValuePairs = array();
530 $host = $this->getConfiguredHost();
531 if ($host) {
532 $localConfigurationPathValuePairs['DB/host'] = $host;
533 }
534 $port = $this->getConfiguredOrDefaultPort();
535 if ($port) {
536 $localConfigurationPathValuePairs['DB/port'] = $port;
537 }
538 $socket = $this->getConfiguredSocket();
539 if ($socket) {
540 $localConfigurationPathValuePairs['DB/socket'] = $socket;
541 }
542 if (!empty($localConfigurationPathValuePairs)) {
543 /** @var $configurationManager \TYPO3\CMS\Core\Configuration\ConfigurationManager */
544 $configurationManager = $this->objectManager->get('TYPO3\\CMS\\Core\\Configuration\\ConfigurationManager');
545 $configurationManager->setLocalConfigurationValuesByPathValuePairs($localConfigurationPathValuePairs);
546 }
547 }
548 }
549 ?>