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