]> git.mxchange.org Git - friendica.git/blob - src/Core/Installer.php
Merge pull request #13704 from MrPetovan/bug/13693-infinite-indentation-level
[friendica.git] / src / Core / Installer.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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 $phppath 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, $phppath = null)
107         {
108                 $returnVal = true;
109
110                 if (isset($phppath)) {
111                         if (!$this->checkPHP($phppath)) {
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('install/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                         '$phppath'    => $configCache->get('config', 'php_path'),
169                         '$adminmail'  => $configCache->get('config', 'admin_email'),
170
171                         '$system_url' => $configCache->get('system', 'url'),
172                         '$basepath'   => $basepath,
173                         '$timezone'   => $configCache->get('system', 'default_timezone'),
174                         '$language'   => $configCache->get('system', 'language'),
175                 ]);
176
177                 $result = file_put_contents($basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.config.php', $txt);
178
179                 if (!$result) {
180                         $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'));
181                 }
182
183                 return $result;
184         }
185
186         /***
187          * Installs the DB-Scheme for Friendica
188          *
189          * @return bool true if the installation was successful, otherwise false
190          * @throws Exception
191          */
192         public function installDatabase(): bool
193         {
194                 $result = DBStructure::install();
195
196                 if ($result) {
197                         $txt = DI::l10n()->t('You may need to import the file "database.sql" manually using phpmyadmin or mysql.') . '<br />';
198                         $txt .= DI::l10n()->t('Please see the file "doc/INSTALL.md".');
199
200                         $this->addCheck($txt, false, true, htmlentities($result, ENT_COMPAT, 'UTF-8'));
201
202                         return false;
203                 }
204
205                 return true;
206         }
207
208         /**
209          * Adds new checks to the array $checks
210          *
211          * @param string $title The title of the current check
212          * @param bool $status 1 = check passed, 0 = check not passed
213          * @param bool $required 1 = check is mandatory, 0 = check is optional
214          * @param string $help A help-string for the current check
215          * @param string $error_msg Optional. A error message, if the current check failed
216          */
217         private function addCheck($title, $status, $required, $help, $error_msg = "")
218         {
219                 array_push($this->checks, [
220                         'title' => $title,
221                         'status' => $status,
222                         'required' => $required,
223                         'help' => $help,
224                         'error_msg' => $error_msg,
225                 ]);
226         }
227
228         /**
229          * PHP Check
230          *
231          * Checks the PHP environment.
232          *
233          * - Checks if a PHP binary is available
234          * - Checks if it is the CLI version
235          * - Checks if "register_argc_argv" is enabled
236          *
237          * @param string $phppath  Optional. The Path to the PHP-Binary
238          * @param bool   $required Optional. If set to true, the PHP-Binary has to exist (Default false)
239          *
240          * @return bool false if something required failed
241          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
242          */
243         public function checkPHP($phppath = null, $required = false)
244         {
245                 $passed3 = false;
246
247                 if (!isset($phppath)) {
248                         $phppath = 'php';
249                 }
250
251                 $passed = file_exists($phppath);
252                 if (!$passed) {
253                         $phppath = trim(shell_exec('which ' . $phppath));
254                         $passed = strlen($phppath);
255                 }
256
257                 $help = "";
258                 if (!$passed) {
259                         $help .= DI::l10n()->t('Could not find a command line version of PHP in the web server PATH.') . '<br />';
260                         $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>") . '<br />';
261                         $help .= '<br /><br />';
262                         $tpl = Renderer::getMarkupTemplate('field_input.tpl');
263                         /// @todo Separate backend Installer class and presentation layer/view
264                         $help .= Renderer::replaceMacros($tpl, [
265                                 '$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.')],
266                         ]);
267                         $phppath = "";
268                 }
269
270                 $this->addCheck(DI::l10n()->t('Command line PHP') . ($passed ? " (<tt>$phppath</tt>)" : ""), $passed, false, $help);
271
272                 if ($passed) {
273                         $cmd = "$phppath -v";
274                         $result = trim(shell_exec($cmd));
275                         $passed2 = (strpos($result, "(cli)") !== false);
276                         [$result] = explode("\n", $result);
277                         $help = "";
278                         if (!$passed2) {
279                                 $help .= DI::l10n()->t("PHP executable is not the php cli binary \x28could be cgi-fgci version\x29") . '<br />';
280                                 $help .= DI::l10n()->t('Found PHP version: ') . "<tt>$result</tt>";
281                         }
282                         $this->addCheck(DI::l10n()->t('PHP cli binary'), $passed2, true, $help);
283                 } else {
284                         // return if it was required
285                         return !$required;
286                 }
287
288                 if ($passed2) {
289                         $str = Strings::getRandomName(8);
290                         $cmd = "$phppath bin/testargs.php $str";
291                         $result = trim(shell_exec($cmd));
292                         $passed3 = $result == $str;
293                         $help = "";
294                         if (!$passed3) {
295                                 $help .= DI::l10n()->t('The command line version of PHP on your system does not have "register_argc_argv" enabled.') . '<br />';
296                                 $help .= DI::l10n()->t('This is required for message delivery to work.');
297                         } else {
298                                 $this->phppath = $phppath;
299                         }
300
301                         $this->addCheck(DI::l10n()->t('PHP register_argc_argv'), $passed3, true, $help);
302                 }
303
304                 // passed2 & passed3 are required if first check passed
305                 return $passed2 && $passed3;
306         }
307
308         /**
309          * OpenSSL Check
310          *
311          * Checks the OpenSSL Environment
312          *
313          * - Checks, if the command "openssl_pkey_new" is available
314          *
315          * @return bool false if something required failed
316          */
317         public function checkKeys()
318         {
319                 $help = '';
320                 $res = false;
321                 $status = true;
322
323                 if (function_exists('openssl_pkey_new')) {
324                         $res = openssl_pkey_new([
325                                 'digest_alg' => 'sha1',
326                                 'private_key_bits' => 4096,
327                                 'encrypt_key' => false
328                         ]);
329                 }
330
331                 // Get private key
332                 if (!$res) {
333                         $help .= DI::l10n()->t('Error: the "openssl_pkey_new" function on this system is not able to generate encryption keys') . '<br />';
334                         $help .= DI::l10n()->t('If running under Windows, please see "http://www.php.net/manual/en/openssl.installation.php".');
335                         $status = false;
336                 }
337                 $this->addCheck(DI::l10n()->t('Generate encryption keys'), $res, true, $help);
338
339                 return $status;
340         }
341
342         /**
343          * PHP basic function check
344          *
345          * @param string $name The name of the function
346          * @param string $title The (localized) title of the function
347          * @param string $help The (localized) help of the function
348          * @param boolean $required If true, this check is required
349          *
350          * @return bool false, if the check failed
351          */
352         private function checkFunction($name, $title, $help, $required)
353         {
354                 $currHelp = '';
355                 $status = true;
356                 if (!function_exists($name)) {
357                         $currHelp = $help;
358                         $status = false;
359                 }
360                 $this->addCheck($title, $status, $required, $currHelp);
361
362                 return $status || (!$status && !$required);
363         }
364
365         /**
366          * PHP functions Check
367          *
368          * Checks the following PHP functions
369          * - libCurl
370          * - GD Graphics
371          * - OpenSSL
372          * - PDO or MySQLi
373          * - mb_string
374          * - XML
375          * - iconv
376          * - fileinfo
377          * - POSIX
378          *
379          * @return bool false if something required failed
380          */
381         public function checkFunctions()
382         {
383                 $returnVal = true;
384
385                 $help = '';
386                 $status = true;
387                 if (function_exists('apache_get_modules') && !in_array('mod_rewrite', apache_get_modules())) {
388                         $help = DI::l10n()->t('Error: Apache webserver mod-rewrite module is required but not installed.');
389                         $status = false;
390                         $returnVal = false;
391                 }
392                 $this->addCheck(DI::l10n()->t('Apache mod_rewrite module'), $status, true, $help);
393
394                 $help = '';
395                 $status = true;
396                 if (!function_exists('mysqli_connect') && !class_exists('pdo')) {
397                         $status = false;
398                         $help = DI::l10n()->t('Error: PDO or MySQLi PHP module required but not installed.');
399                         $returnVal = false;
400                 } elseif (!function_exists('mysqli_connect') && class_exists('pdo') && !in_array('mysql', \PDO::getAvailableDrivers())) {
401                         $status = false;
402                         $help = DI::l10n()->t('Error: The MySQL driver for PDO is not installed.');
403                         $returnVal = false;
404                 }
405                 $this->addCheck(DI::l10n()->t('PDO or MySQLi PHP module'), $status, true, $help);
406
407                 $help   = '';
408                 $status = true;
409                 if (!class_exists('IntlChar')) {
410                         $status    = false;
411                         $help      = DI::l10n()->t('Error: The IntlChar module is not installed.');
412                         $returnVal = false;
413                 }
414                 $this->addCheck(DI::l10n()->t('IntlChar PHP module'), $status, true, $help);
415
416                 // check for XML DOM Documents being able to be generated
417                 $help = '';
418                 $status = true;
419                 try {
420                         new DOMDocument();
421                 } catch (Exception $e) {
422                         $help = DI::l10n()->t('Error, XML PHP module required but not installed.');
423                         $status = false;
424                         $returnVal = false;
425                 }
426                 $this->addCheck(DI::l10n()->t('XML PHP module'), $status, true, $help);
427
428                 $status = $this->checkFunction('curl_init',
429                         DI::l10n()->t('libCurl PHP module'),
430                         DI::l10n()->t('Error: libCURL PHP module required but not installed.'),
431                         true
432                 );
433                 $returnVal = $returnVal ? $status : false;
434
435                 $status = $this->checkFunction('imagecreatefromjpeg',
436                         DI::l10n()->t('GD graphics PHP module'),
437                         DI::l10n()->t('Error: GD graphics PHP module with JPEG support required but not installed.'),
438                         true
439                 );
440                 $returnVal = $returnVal ? $status : false;
441
442                 $status = $this->checkFunction('openssl_public_encrypt',
443                         DI::l10n()->t('OpenSSL PHP module'),
444                         DI::l10n()->t('Error: openssl PHP module required but not installed.'),
445                         true
446                 );
447                 $returnVal = $returnVal ? $status : false;
448
449                 $status = $this->checkFunction('mb_strlen',
450                         DI::l10n()->t('mb_string PHP module'),
451                         DI::l10n()->t('Error: mb_string PHP module required but not installed.'),
452                         true
453                 );
454                 $returnVal = $returnVal ? $status : false;
455
456                 $status = $this->checkFunction('iconv_strlen',
457                         DI::l10n()->t('iconv PHP module'),
458                         DI::l10n()->t('Error: iconv PHP module required but not installed.'),
459                         true
460                 );
461                 $returnVal = $returnVal ? $status : false;
462
463                 $status = $this->checkFunction('posix_kill',
464                         DI::l10n()->t('POSIX PHP module'),
465                         DI::l10n()->t('Error: POSIX PHP module required but not installed.'),
466                         true
467                 );
468                 $returnVal = $returnVal ? $status : false;
469
470                 $status = $this->checkFunction('proc_open',
471                         DI::l10n()->t('Program execution functions'),
472                         DI::l10n()->t('Error: Program execution functions (proc_open) required but not enabled.'),
473                         true
474                 );
475                 $returnVal = $returnVal ? $status : false;
476
477                 $status = $this->checkFunction('json_encode',
478                         DI::l10n()->t('JSON PHP module'),
479                         DI::l10n()->t('Error: JSON PHP module required but not installed.'),
480                         true
481                 );
482                 $returnVal = $returnVal ? $status : false;
483
484                 $status = $this->checkFunction('finfo_open',
485                         DI::l10n()->t('File Information PHP module'),
486                         DI::l10n()->t('Error: File Information PHP module required but not installed.'),
487                         true
488                 );
489                 $returnVal = $returnVal ? $status : false;
490
491                 $status = $this->checkFunction('gmp_strval',
492                         DI::l10n()->t('GNU Multiple Precision PHP module'),
493                         DI::l10n()->t('Error: GNU Multiple Precision PHP module required but not installed.'),
494                         true
495                 );
496                 $returnVal = $returnVal ? $status : false;
497
498                 return $returnVal;
499         }
500
501         /**
502          * "config/local.config.php" - Check
503          *
504          * Checks if it's possible to create the "config/local.config.php"
505          *
506          * @return bool false if something required failed
507          */
508         public function checkLocalIni()
509         {
510                 $status = true;
511                 $help = "";
512                 if ((file_exists('config/local.config.php') && !is_writable('config/local.config.php')) ||
513                         (!file_exists('config/local.config.php') && !is_writable('.'))) {
514
515                         $status = false;
516                         $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.') . '<br />';
517                         $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.') . '<br />';
518                         $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.') . '<br />';
519                         $help .= DI::l10n()->t('You can alternatively skip this procedure and perform a manual installation. Please see the file "doc/INSTALL.md" for instructions.') . '<br />';
520                 }
521
522                 $this->addCheck(DI::l10n()->t('config/local.config.php is writable'), $status, false, $help);
523
524                 // Local INI File is not required
525                 return true;
526         }
527
528         /**
529          * Smarty3 Template Check
530          *
531          * Checks, if the directory of Smarty3 is writable
532          *
533          * @return bool false if something required failed
534          */
535         public function checkSmarty3()
536         {
537                 $status = true;
538                 $help = "";
539                 if (!is_writable('view/smarty3')) {
540
541                         $status = false;
542                         $help = DI::l10n()->t('Friendica uses the Smarty3 template engine to render its web views. Smarty3 compiles templates to PHP to speed up rendering.') . '<br />';
543                         $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.') . '<br />';
544                         $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.") . '<br />';
545                         $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.") . '<br />';
546                 }
547
548                 $this->addCheck(DI::l10n()->t('view/smarty3 is writable'), $status, true, $help);
549
550                 return $status;
551         }
552
553         /**
554          * ".htaccess" - Check
555          *
556          * Checks, if "url_rewrite" is enabled in the ".htaccess" file
557          *
558          * @param string $baseurl The baseurl of the app
559          * @return bool false if something required failed
560          */
561         public function checkHtAccess($baseurl)
562         {
563                 $status = true;
564                 $help = "";
565                 $error_msg = "";
566                 if (function_exists('curl_init')) {
567                         $fetchResult = DI::httpClient()->fetchFull($baseurl . "/install/testrewrite");
568
569                         $url = Strings::normaliseLink($baseurl . "/install/testrewrite");
570                         if ($fetchResult->getReturnCode() != 204) {
571                                 $fetchResult = DI::httpClient()->fetchFull($url);
572                         }
573
574                         if ($fetchResult->getReturnCode() != 204) {
575                                 $status = false;
576                                 $help = DI::l10n()->t('Url rewrite in .htaccess seems not working. Make sure you copied .htaccess-dist to .htaccess.') . '<br />';
577                                 $help .= DI::l10n()->t('In some circumstances (like running inside containers), you can skip this error.');
578                                 $error_msg = [];
579                                 $error_msg['head'] = DI::l10n()->t('Error message from Curl when fetching');
580                                 $error_msg['url'] = $fetchResult->getRedirectUrl();
581                                 $error_msg['msg'] = $fetchResult->getError();
582                         }
583
584                         /// @TODO Required false because of cURL issues in containers - see https://github.com/friendica/docker/issues/134
585                         $this->addCheck(DI::l10n()->t('Url rewrite is working'), $status, false, $help, $error_msg);
586                 } else {
587                         // cannot check modrewrite if libcurl is not installed
588                         /// @TODO Maybe issue warning here?
589                 }
590
591                 return $status;
592         }
593
594         /**
595          * TLS Check
596          *
597          * Tries to determine whether the connection to the server is secured
598          * by TLS or not. If not the user will be warned that it is highly
599          * encouraged to use TLS.
600          *
601          * @return bool (true) as TLS is not mandatory
602          */
603         public function checkTLS()
604         {
605                 $tls = false;
606
607                 if (isset($_SERVER['HTTPS'])) {
608                         if (($_SERVER['HTTPS'] == 1) || ($_SERVER['HTTPS'] == 'on')) {
609                                 $tls = true;
610                         }
611                 }
612
613                 if (!$tls) {
614                         $help = DI::l10n()->t('The detection of TLS to secure the communication between the browser and the new Friendica server failed.');
615                         $help .= ' ' . DI::l10n()->t('It is highly encouraged to use Friendica only over a secure connection as sensitive information like passwords will be transmitted.');
616                         $help .= ' ' . DI::l10n()->t('Please ensure that the connection to the server is secure.');
617                         $this->addCheck(DI::l10n()->t('No TLS detected'), $tls, false, $help);
618                 } else {
619                         $this->addCheck(DI::l10n()->t('TLS detected'), $tls, false, '');
620                 }
621
622                 // TLS is not required
623                 return true;
624         }
625
626         /**
627          * Imagick Check
628          *
629          * Checks, if the imagick module is available
630          *
631          * @return bool false if something required failed
632          */
633         public function checkImagick()
634         {
635                 $imagick = false;
636                 $gif = false;
637
638                 if (class_exists('Imagick')) {
639                         $imagick = true;
640                         $supported = Images::supportedTypes();
641                         if (array_key_exists('image/gif', $supported)) {
642                                 $gif = true;
643                         }
644                 }
645                 if (!$imagick) {
646                         $this->addCheck(DI::l10n()->t('ImageMagick PHP extension is not installed'), $imagick, false, "");
647                 } else {
648                         $this->addCheck(DI::l10n()->t('ImageMagick PHP extension is installed'), $imagick, false, "");
649                         if ($imagick) {
650                                 $this->addCheck(DI::l10n()->t('ImageMagick supports GIF'), $gif, false, "");
651                         }
652                 }
653
654                 // Imagick is not required
655                 return true;
656         }
657
658         /**
659          * Checking the Database connection and if it is available for the current installation
660          *
661          * @param Database $dba
662          *
663          * @return bool true if the check was successful, otherwise false
664          * @throws Exception
665          */
666         public function checkDB(Database $dba): bool
667         {
668                 $dba->reconnect();
669
670                 if ($dba->isConnected()) {
671                         if (DBStructure::existsTable('user')) {
672                                 $this->addCheck(DI::l10n()->t('Database already in use.'), false, true, '');
673
674                                 return false;
675                         }
676                 } else {
677                         $this->addCheck(DI::l10n()->t('Could not connect to database.'), false, true, '');
678
679                         return false;
680                 }
681
682                 return true;
683         }
684
685         /**
686          * Setup the default cache for a new installation
687          *
688          * @param \Friendica\Core\Config\ValueObject\Cache $configCache The configuration cache
689          * @param string                                   $basePath    The determined basepath
690          *
691          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
692          */
693         public function setUpCache(Cache $configCache, $basePath)
694         {
695                 $configCache->set('config', 'php_path'  , $this->getPHPPath());
696                 $configCache->set('system', 'basepath'  , $basePath);
697         }
698 }