]> git.mxchange.org Git - friendica.git/blob - src/Core/Installer.php
Remove duplicate profile_uid key in App->profile array
[friendica.git] / src / Core / Installer.php
1 <?php
2 /**
3  * @file src/Core/Install.php
4  */
5 namespace Friendica\Core;
6
7 use DOMDocument;
8 use Exception;
9 use Friendica\Core\Config\Cache;
10 use Friendica\Database\Database;
11 use Friendica\Database\DBStructure;
12 use Friendica\DI;
13 use Friendica\Util\Images;
14 use Friendica\Util\Network;
15 use Friendica\Util\Strings;
16
17 /**
18  * Contains methods for installation purpose of Friendica
19  */
20 class Installer
21 {
22         // Default values for the install page
23         const DEFAULT_LANG = 'en';
24         const DEFAULT_TZ   = 'America/Los_Angeles';
25         const DEFAULT_HOST = 'localhost';
26
27         /**
28          * @var array the check outcomes
29          */
30         private $checks;
31
32         /**
33          * @var string The path to the PHP binary
34          */
35         private $phppath = null;
36
37         /**
38          * Returns all checks made
39          *
40          * @return array the checks
41          */
42         public function getChecks()
43         {
44                 return $this->checks;
45         }
46
47         /**
48          * Returns the PHP path
49          *
50          * @return string the PHP Path
51          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
52          */
53         public function getPHPPath()
54         {
55                 // if not set, determine the PHP path
56                 if (!isset($this->phppath)) {
57                         $this->checkPHP();
58                         $this->resetChecks();
59                 }
60
61                 return $this->phppath;
62         }
63
64         /**
65          * Resets all checks
66          */
67         public function resetChecks()
68         {
69                 $this->checks = [];
70         }
71
72         /**
73          * Install constructor.
74          *
75          */
76         public function __construct()
77         {
78                 $this->checks = [];
79         }
80
81         /**
82          * Checks the current installation environment. There are optional and mandatory checks.
83          *
84          * @param string $baseurl The baseurl of Friendica
85          * @param string $phpath  Optional path to the PHP binary
86          *
87          * @return bool if the check succeed
88          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
89          */
90         public function checkEnvironment($baseurl, $phpath = null)
91         {
92                 $returnVal = true;
93
94                 if (isset($phpath)) {
95                         if (!$this->checkPHP($phpath)) {
96                                 $returnVal = false;
97                         }
98                 }
99
100                 if (!$this->checkFunctions()) {
101                         $returnVal = false;
102                 }
103
104                 if (!$this->checkImagick()) {
105                         $returnVal = false;
106                 }
107
108                 if (!$this->checkLocalIni()) {
109                         $returnVal = false;
110                 }
111
112                 if (!$this->checkSmarty3()) {
113                         $returnVal = false;
114                 }
115
116                 if (!$this->checkKeys()) {
117                         $returnVal = false;
118                 }
119
120                 if (!$this->checkHtAccess($baseurl)) {
121                         $returnVal = false;
122                 }
123
124                 return $returnVal;
125         }
126
127         /**
128          * Executes the installation of Friendica in the given environment.
129          * - Creates `config/local.config.php`
130          * - Installs Database Structure
131          *
132          * @param Cache $configCache The config cache with all config relevant information
133          *
134          * @return bool true if the config was created, otherwise false
135          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
136          */
137         public function createConfig(Cache $configCache)
138         {
139                 $basepath = $configCache->get('system', 'basepath');
140
141                 $tpl = Renderer::getMarkupTemplate('local.config.tpl');
142                 $txt = Renderer::replaceMacros($tpl, [
143                         '$dbhost'    => $configCache->get('database', 'hostname'),
144                         '$dbuser'    => $configCache->get('database', 'username'),
145                         '$dbpass'    => $configCache->get('database', 'password'),
146                         '$dbdata'    => $configCache->get('database', 'database'),
147
148                         '$phpath'    => $configCache->get('config', 'php_path'),
149                         '$adminmail' => $configCache->get('config', 'admin_email'),
150                         '$hostname'  => $configCache->get('config', 'hostname'),
151
152                         '$urlpath'   => $configCache->get('system', 'urlpath'),
153                         '$baseurl'   => $configCache->get('system', 'url'),
154                         '$sslpolicy' => $configCache->get('system', 'ssl_policy'),
155                         '$basepath'  => $basepath,
156                         '$timezone'  => $configCache->get('system', 'default_timezone'),
157                         '$language'  => $configCache->get('system', 'language'),
158                 ]);
159
160                 $result = file_put_contents($basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.config.php', $txt);
161
162                 if (!$result) {
163                         $this->addCheck(DI::l10n()->t('The database configuration file "config/local.config.php" could not be written. Please use the enclosed text to create a configuration file in your web server root.'), false, false, htmlentities($txt, ENT_COMPAT, 'UTF-8'));
164                 }
165
166                 return $result;
167         }
168
169         /***
170          * Installs the DB-Scheme for Friendica
171          *
172          * @param string $basePath The base path of this application
173          *
174          * @return bool true if the installation was successful, otherwise false
175          * @throws Exception
176          */
177         public function installDatabase($basePath)
178         {
179                 $result = DBStructure::update($basePath, false, true, true);
180
181                 if ($result) {
182                         $txt = DI::l10n()->t('You may need to import the file "database.sql" manually using phpmyadmin or mysql.') . EOL;
183                         $txt .= DI::l10n()->t('Please see the file "INSTALL.txt".');
184
185                         $this->addCheck($txt, false, true, htmlentities($result, ENT_COMPAT, 'UTF-8'));
186
187                         return false;
188                 }
189
190                 return true;
191         }
192
193         /**
194          * Adds new checks to the array $checks
195          *
196          * @param string $title The title of the current check
197          * @param bool $status 1 = check passed, 0 = check not passed
198          * @param bool $required 1 = check is mandatory, 0 = check is optional
199          * @param string $help A help-string for the current check
200          * @param string $error_msg Optional. A error message, if the current check failed
201          */
202         private function addCheck($title, $status, $required, $help, $error_msg = "")
203         {
204                 array_push($this->checks, [
205                         'title' => $title,
206                         'status' => $status,
207                         'required' => $required,
208                         'help' => $help,
209                         'error_msg' => $error_msg,
210                 ]);
211         }
212
213         /**
214          * PHP Check
215          *
216          * Checks the PHP environment.
217          *
218          * - Checks if a PHP binary is available
219          * - Checks if it is the CLI version
220          * - Checks if "register_argc_argv" is enabled
221          *
222          * @param string $phppath  Optional. The Path to the PHP-Binary
223          * @param bool   $required Optional. If set to true, the PHP-Binary has to exist (Default false)
224          *
225          * @return bool false if something required failed
226          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227          */
228         public function checkPHP($phppath = null, $required = false)
229         {
230                 $passed3 = false;
231
232                 if (!isset($phppath)) {
233                         $phppath = 'php';
234                 }
235
236                 $passed = file_exists($phppath);
237                 if (!$passed) {
238                         $phppath = trim(shell_exec('which ' . $phppath));
239                         $passed = strlen($phppath);
240                 }
241
242                 $help = "";
243                 if (!$passed) {
244                         $help .= DI::l10n()->t('Could not find a command line version of PHP in the web server PATH.') . EOL;
245                         $help .= DI::l10n()->t("If you don't have a command line version of PHP installed on your server, you will not be able to run the background processing. See <a href='https://github.com/friendica/friendica/blob/master/doc/Install.md#set-up-the-worker'>'Setup the worker'</a>") . EOL;
246                         $help .= EOL . EOL;
247                         $tpl = Renderer::getMarkupTemplate('field_input.tpl');
248                         /// @todo Separate backend Installer class and presentation layer/view
249                         $help .= Renderer::replaceMacros($tpl, [
250                                 '$field' => ['config-php_path', DI::l10n()->t('PHP executable path'), $phppath, DI::l10n()->t('Enter full path to php executable. You can leave this blank to continue the installation.')],
251                         ]);
252                         $phppath = "";
253                 }
254
255                 $this->addCheck(DI::l10n()->t('Command line PHP') . ($passed ? " (<tt>$phppath</tt>)" : ""), $passed, false, $help);
256
257                 if ($passed) {
258                         $cmd = "$phppath -v";
259                         $result = trim(shell_exec($cmd));
260                         $passed2 = (strpos($result, "(cli)") !== false);
261                         list($result) = explode("\n", $result);
262                         $help = "";
263                         if (!$passed2) {
264                                 $help .= DI::l10n()->t("PHP executable is not the php cli binary \x28could be cgi-fgci version\x29") . EOL;
265                                 $help .= DI::l10n()->t('Found PHP version: ') . "<tt>$result</tt>";
266                         }
267                         $this->addCheck(DI::l10n()->t('PHP cli binary'), $passed2, true, $help);
268                 } else {
269                         // return if it was required
270                         return !$required;
271                 }
272
273                 if ($passed2) {
274                         $str = Strings::getRandomName(8);
275                         $cmd = "$phppath bin/testargs.php $str";
276                         $result = trim(shell_exec($cmd));
277                         $passed3 = $result == $str;
278                         $help = "";
279                         if (!$passed3) {
280                                 $help .= DI::l10n()->t('The command line version of PHP on your system does not have "register_argc_argv" enabled.') . EOL;
281                                 $help .= DI::l10n()->t('This is required for message delivery to work.');
282                         } else {
283                                 $this->phppath = $phppath;
284                         }
285
286                         $this->addCheck(DI::l10n()->t('PHP register_argc_argv'), $passed3, true, $help);
287                 }
288
289                 // passed2 & passed3 are required if first check passed
290                 return $passed2 && $passed3;
291         }
292
293         /**
294          * OpenSSL Check
295          *
296          * Checks the OpenSSL Environment
297          *
298          * - Checks, if the command "openssl_pkey_new" is available
299          *
300          * @return bool false if something required failed
301          */
302         public function checkKeys()
303         {
304                 $help = '';
305                 $res = false;
306                 $status = true;
307
308                 if (function_exists('openssl_pkey_new')) {
309                         $res = openssl_pkey_new([
310                                 'digest_alg' => 'sha1',
311                                 'private_key_bits' => 4096,
312                                 'encrypt_key' => false
313                         ]);
314                 }
315
316                 // Get private key
317                 if (!$res) {
318                         $help .= DI::l10n()->t('Error: the "openssl_pkey_new" function on this system is not able to generate encryption keys') . EOL;
319                         $help .= DI::l10n()->t('If running under Windows, please see "http://www.php.net/manual/en/openssl.installation.php".');
320                         $status = false;
321                 }
322                 $this->addCheck(DI::l10n()->t('Generate encryption keys'), $res, true, $help);
323
324                 return $status;
325         }
326
327         /**
328          * PHP basic function check
329          *
330          * @param string $name The name of the function
331          * @param string $title The (localized) title of the function
332          * @param string $help The (localized) help of the function
333          * @param boolean $required If true, this check is required
334          *
335          * @return bool false, if the check failed
336          */
337         private function checkFunction($name, $title, $help, $required)
338         {
339                 $currHelp = '';
340                 $status = true;
341                 if (!function_exists($name)) {
342                         $currHelp = $help;
343                         $status = false;
344                 }
345                 $this->addCheck($title, $status, $required, $currHelp);
346
347                 return $status || (!$status && !$required);
348         }
349
350         /**
351          * PHP functions Check
352          *
353          * Checks the following PHP functions
354          * - libCurl
355          * - GD Graphics
356          * - OpenSSL
357          * - PDO or MySQLi
358          * - mb_string
359          * - XML
360          * - iconv
361          * - fileinfo
362          * - POSIX
363          *
364          * @return bool false if something required failed
365          */
366         public function checkFunctions()
367         {
368                 $returnVal = true;
369
370                 $help = '';
371                 $status = true;
372                 if (function_exists('apache_get_modules')) {
373                         if (!in_array('mod_rewrite', apache_get_modules())) {
374                                 $help = DI::l10n()->t('Error: Apache webserver mod-rewrite module is required but not installed.');
375                                 $status = false;
376                                 $returnVal = false;
377                         }
378                 }
379                 $this->addCheck(DI::l10n()->t('Apache mod_rewrite module'), $status, true, $help);
380
381                 $help = '';
382                 $status = true;
383                 if (!function_exists('mysqli_connect') && !class_exists('pdo')) {
384                         $status = false;
385                         $help = DI::l10n()->t('Error: PDO or MySQLi PHP module required but not installed.');
386                         $returnVal = false;
387                 } else {
388                         if (!function_exists('mysqli_connect') && class_exists('pdo') && !in_array('mysql', \PDO::getAvailableDrivers())) {
389                                 $status = false;
390                                 $help = DI::l10n()->t('Error: The MySQL driver for PDO is not installed.');
391                                 $returnVal = false;
392                         }
393                 }
394                 $this->addCheck(DI::l10n()->t('PDO or MySQLi PHP module'), $status, true, $help);
395
396                 // check for XML DOM Documents being able to be generated
397                 $help = '';
398                 $status = true;
399                 try {
400                         new DOMDocument();
401                 } catch (Exception $e) {
402                         $help = DI::l10n()->t('Error, XML PHP module required but not installed.');
403                         $status = false;
404                         $returnVal = false;
405                 }
406                 $this->addCheck(DI::l10n()->t('XML PHP module'), $status, true, $help);
407
408                 $status = $this->checkFunction('curl_init',
409                         DI::l10n()->t('libCurl PHP module'),
410                         DI::l10n()->t('Error: libCURL PHP module required but not installed.'),
411                         true
412                 );
413                 $returnVal = $returnVal ? $status : false;
414
415                 $status = $this->checkFunction('imagecreatefromjpeg',
416                         DI::l10n()->t('GD graphics PHP module'),
417                         DI::l10n()->t('Error: GD graphics PHP module with JPEG support required but not installed.'),
418                         true
419                 );
420                 $returnVal = $returnVal ? $status : false;
421
422                 $status = $this->checkFunction('openssl_public_encrypt',
423                         DI::l10n()->t('OpenSSL PHP module'),
424                         DI::l10n()->t('Error: openssl PHP module required but not installed.'),
425                         true
426                 );
427                 $returnVal = $returnVal ? $status : false;
428
429                 $status = $this->checkFunction('mb_strlen',
430                         DI::l10n()->t('mb_string PHP module'),
431                         DI::l10n()->t('Error: mb_string PHP module required but not installed.'),
432                         true
433                 );
434                 $returnVal = $returnVal ? $status : false;
435
436                 $status = $this->checkFunction('iconv_strlen',
437                         DI::l10n()->t('iconv PHP module'),
438                         DI::l10n()->t('Error: iconv PHP module required but not installed.'),
439                         true
440                 );
441                 $returnVal = $returnVal ? $status : false;
442
443                 $status = $this->checkFunction('posix_kill',
444                         DI::l10n()->t('POSIX PHP module'),
445                         DI::l10n()->t('Error: POSIX PHP module required but not installed.'),
446                         true
447                 );
448                 $returnVal = $returnVal ? $status : false;
449
450                 $status = $this->checkFunction('json_encode',
451                         DI::l10n()->t('JSON PHP module'),
452                         DI::l10n()->t('Error: JSON PHP module required but not installed.'),
453                         true
454                 );
455                 $returnVal = $returnVal ? $status : false;
456
457                 $status = $this->checkFunction('finfo_open',
458                         DI::l10n()->t('File Information PHP module'),
459                         DI::l10n()->t('Error: File Information PHP module required but not installed.'),
460                         true
461                 );
462                 $returnVal = $returnVal ? $status : false;
463
464                 return $returnVal;
465         }
466
467         /**
468          * "config/local.config.php" - Check
469          *
470          * Checks if it's possible to create the "config/local.config.php"
471          *
472          * @return bool false if something required failed
473          */
474         public function checkLocalIni()
475         {
476                 $status = true;
477                 $help = "";
478                 if ((file_exists('config/local.config.php') && !is_writable('config/local.config.php')) ||
479                         (!file_exists('config/local.config.php') && !is_writable('.'))) {
480
481                         $status = false;
482                         $help = DI::l10n()->t('The web installer needs to be able to create a file called "local.config.php" in the "config" folder of your web server and it is unable to do so.') . EOL;
483                         $help .= DI::l10n()->t('This is most often a permission setting, as the web server may not be able to write files in your folder - even if you can.') . EOL;
484                         $help .= DI::l10n()->t('At the end of this procedure, we will give you a text to save in a file named local.config.php in your Friendica "config" folder.') . EOL;
485                         $help .= DI::l10n()->t('You can alternatively skip this procedure and perform a manual installation. Please see the file "INSTALL.txt" for instructions.') . EOL;
486                 }
487
488                 $this->addCheck(DI::l10n()->t('config/local.config.php is writable'), $status, false, $help);
489
490                 // Local INI File is not required
491                 return true;
492         }
493
494         /**
495          * Smarty3 Template Check
496          *
497          * Checks, if the directory of Smarty3 is writable
498          *
499          * @return bool false if something required failed
500          */
501         public function checkSmarty3()
502         {
503                 $status = true;
504                 $help = "";
505                 if (!is_writable('view/smarty3')) {
506
507                         $status = false;
508                         $help = DI::l10n()->t('Friendica uses the Smarty3 template engine to render its web views. Smarty3 compiles templates to PHP to speed up rendering.') . EOL;
509                         $help .= DI::l10n()->t('In order to store these compiled templates, the web server needs to have write access to the directory view/smarty3/ under the Friendica top level folder.') . EOL;
510                         $help .= DI::l10n()->t("Please ensure that the user that your web server runs as \x28e.g. www-data\x29 has write access to this folder.") . EOL;
511                         $help .= DI::l10n()->t("Note: as a security measure, you should give the web server write access to view/smarty3/ only--not the template files \x28.tpl\x29 that it contains.") . EOL;
512                 }
513
514                 $this->addCheck(DI::l10n()->t('view/smarty3 is writable'), $status, true, $help);
515
516                 return $status;
517         }
518
519         /**
520          * ".htaccess" - Check
521          *
522          * Checks, if "url_rewrite" is enabled in the ".htaccess" file
523          *
524          * @param string $baseurl The baseurl of the app
525          * @return bool false if something required failed
526          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527          */
528         public function checkHtAccess($baseurl)
529         {
530                 $status = true;
531                 $help = "";
532                 $error_msg = "";
533                 if (function_exists('curl_init')) {
534                         $fetchResult = Network::fetchUrlFull($baseurl . "/install/testrewrite");
535
536                         $url = Strings::normaliseLink($baseurl . "/install/testrewrite");
537                         if ($fetchResult->getReturnCode() != 204) {
538                                 $fetchResult = Network::fetchUrlFull($url);
539                         }
540
541                         if ($fetchResult->getReturnCode() != 204) {
542                                 $status = false;
543                                 $help = DI::l10n()->t('Url rewrite in .htaccess is not working. Make sure you copied .htaccess-dist to .htaccess.');
544                                 $error_msg = [];
545                                 $error_msg['head'] = DI::l10n()->t('Error message from Curl when fetching');
546                                 $error_msg['url'] = $fetchResult->getRedirectUrl();
547                                 $error_msg['msg'] = $fetchResult->getError();
548                         }
549
550                         $this->addCheck(DI::l10n()->t('Url rewrite is working'), $status, true, $help, $error_msg);
551                 } else {
552                         // cannot check modrewrite if libcurl is not installed
553                         /// @TODO Maybe issue warning here?
554                 }
555
556                 return $status;
557         }
558
559         /**
560          * Imagick Check
561          *
562          * Checks, if the imagick module is available
563          *
564          * @return bool false if something required failed
565          */
566         public function checkImagick()
567         {
568                 $imagick = false;
569                 $gif = false;
570
571                 if (class_exists('Imagick')) {
572                         $imagick = true;
573                         $supported = Images::supportedTypes();
574                         if (array_key_exists('image/gif', $supported)) {
575                                 $gif = true;
576                         }
577                 }
578                 if (!$imagick) {
579                         $this->addCheck(DI::l10n()->t('ImageMagick PHP extension is not installed'), $imagick, false, "");
580                 } else {
581                         $this->addCheck(DI::l10n()->t('ImageMagick PHP extension is installed'), $imagick, false, "");
582                         if ($imagick) {
583                                 $this->addCheck(DI::l10n()->t('ImageMagick supports GIF'), $gif, false, "");
584                         }
585                 }
586
587                 // Imagick is not required
588                 return true;
589         }
590
591         /**
592          * Checking the Database connection and if it is available for the current installation
593          *
594          * @param Database $dba
595          *
596          * @return bool true if the check was successful, otherwise false
597          * @throws Exception
598          */
599         public function checkDB(Database $dba)
600         {
601                 $dba->reconnect();
602
603                 if ($dba->isConnected()) {
604                         if (DBStructure::existsTable('user')) {
605                                 $this->addCheck(DI::l10n()->t('Database already in use.'), false, true, '');
606
607                                 return false;
608                         }
609                 } else {
610                         $this->addCheck(DI::l10n()->t('Could not connect to database.'), false, true, '');
611
612                         return false;
613                 }
614
615                 return true;
616         }
617
618         /**
619          * Setup the default cache for a new installation
620          *
621          * @param Cache  $configCache The configuration cache
622          * @param string $basePath    The determined basepath
623          *
624          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
625          */
626         public function setUpCache(Cache $configCache, $basePath)
627         {
628                 $configCache->set('config', 'php_path'  , $this->getPHPPath());
629                 $configCache->set('system', 'basepath'  , $basePath);
630         }
631 }