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