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