Introduce HiddenString for Config-Values
[friendica.git/.git] / src / Factory / DBFactory.php
1 <?php
2
3 namespace Friendica\Factory;
4
5 use Friendica\Core\Config\Cache;
6 use Friendica\Database;
7 use Friendica\Util\Logger\VoidLogger;
8 use Friendica\Util\Profiler;
9 use ParagonIE\HiddenString\HiddenString;
10
11 class DBFactory
12 {
13         /**
14          * Initialize the DBA connection
15          *
16          * @param Cache\IConfigCache $configCache The configuration cache
17          * @param Profiler           $profiler    The profiler
18          * @param array              $server      The $_SERVER variables
19          *
20          * @throws \Exception if connection went bad
21          */
22         public static function init(Cache\IConfigCache $configCache, Profiler $profiler, array $server)
23         {
24                 if (Database\DBA::connected()) {
25                         return;
26                 }
27
28                 $db_host = $configCache->get('database', 'hostname');
29                 $db_user = $configCache->get('database', 'username');
30                 $db_pass = $configCache->get('database', 'password');
31                 $db_data = $configCache->get('database', 'database');
32                 $charset = $configCache->get('database', 'charset');
33
34                 // Use environment variables for mysql if they are set beforehand
35                 if (!empty($server['MYSQL_HOST'])
36                         && !empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER']))
37                         && $server['MYSQL_PASSWORD'] !== false
38                         && !empty($server['MYSQL_DATABASE']))
39                 {
40                         $db_host = $server['MYSQL_HOST'];
41                         if (!empty($server['MYSQL_PORT'])) {
42                                 $db_host .= ':' . $server['MYSQL_PORT'];
43                         }
44                         if (!empty($server['MYSQL_USERNAME'])) {
45                                 $db_user = $server['MYSQL_USERNAME'];
46                         } else {
47                                 $db_user = $server['MYSQL_USER'];
48                         }
49                         $db_pass = new HiddenString((string) $server['MYSQL_PASSWORD']);
50                         $db_data = $server['MYSQL_DATABASE'];
51                 }
52
53                 if (Database\DBA::connect($configCache, $profiler, new VoidLogger(), $db_host, $db_user, $db_pass, $db_data, $charset)) {
54                         // Loads DB_UPDATE_VERSION constant
55                         Database\DBStructure::definition($configCache->get('system', 'basepath'), false);
56                 }
57
58                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
59         }
60 }