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