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