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