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