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