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