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