]> git.mxchange.org Git - friendica.git/blob - src/Core/Installer.php
Merge pull request #6601 from annando/false-notifications
[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\Database\DBA;
10 use Friendica\Database\DBStructure;
11 use Friendica\Object\Image;
12 use Friendica\Util\Network;
13 use Friendica\Util\Strings;
14
15 /**
16  * Contains methods for installation purpose of Friendica
17  */
18 class Installer
19 {
20         // Default values for the install page
21         const DEFAULT_LANG = 'en';
22         const DEFAULT_TZ   = 'America/Los_Angeles';
23         const DEFAULT_HOST = 'localhost';
24
25         /**
26          * @var array the check outcomes
27          */
28         private $checks;
29
30         /**
31          * @var string The path to the PHP binary
32          */
33         private $phppath = null;
34
35         /**
36          * Returns all checks made
37          *
38          * @return array the checks
39          */
40         public function getChecks()
41         {
42                 return $this->checks;
43         }
44
45         /**
46          * Returns the PHP path
47          *
48          * @return string the PHP Path
49          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
50          */
51         public function getPHPPath()
52         {
53                 // if not set, determine the PHP path
54                 if (!isset($this->phppath)) {
55                         $this->checkPHP();
56                         $this->resetChecks();
57                 }
58
59                 return $this->phppath;
60         }
61
62         /**
63          * Resets all checks
64          */
65         public function resetChecks()
66         {
67                 $this->checks = [];
68         }
69
70         /**
71          * Install constructor.
72          *
73          */
74         public function __construct()
75         {
76                 $this->checks = [];
77         }
78
79         /**
80          * Checks the current installation environment. There are optional and mandatory checks.
81          *
82          * @param string $baseurl The baseurl of Friendica
83          * @param string $phpath  Optional path to the PHP binary
84          *
85          * @return bool if the check succeed
86          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
87          */
88         public function checkEnvironment($baseurl, $phpath = null)
89         {
90                 $returnVal = true;
91
92                 if (isset($phpath)) {
93                         if (!$this->checkPHP($phpath)) {
94                                 $returnVal = false;
95                         }
96                 }
97
98                 if (!$this->checkFunctions()) {
99                         $returnVal = false;
100                 }
101
102                 if (!$this->checkImagick()) {
103                         $returnVal = false;
104                 }
105
106                 if (!$this->checkLocalIni()) {
107                         $returnVal = false;
108                 }
109
110                 if (!$this->checkSmarty3()) {
111                         $returnVal = false;
112                 }
113
114                 if (!$this->checkKeys()) {
115                         $returnVal = false;
116                 }
117
118                 if (!$this->checkHtAccess($baseurl)) {
119                         $returnVal = false;
120                 }
121
122                 return $returnVal;
123         }
124
125         /**
126          * Executes the installation of Friendica in the given environment.
127          * - Creates `config/local.config.php`
128          * - Installs Database Structure
129          *
130          * @param string $phppath   Path to the PHP-Binary (optional, if not set e.g. 'php' or '/usr/bin/php')
131          * @param string $urlpath   Path based on the URL of Friendica (e.g. '/friendica')
132          * @param string $dbhost    Hostname/IP of the Friendica Database
133          * @param string $dbuser    Username of the Database connection credentials
134          * @param string $dbpass    Password of the Database connection credentials
135          * @param string $dbdata    Name of the Database
136          * @param string $timezone  Timezone of the Friendica Installaton (e.g. 'Europe/Berlin')
137          * @param string $language  2-letter ISO 639-1 code (eg. 'en')
138          * @param string $adminmail Mail-Adress of the administrator
139          * @param string $basepath  The basepath of Friendica
140          *
141          * @return bool true if the config was created, otherwise false
142          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
143          */
144         public function createConfig($phppath, $urlpath, $dbhost, $dbuser, $dbpass, $dbdata, $timezone, $language, $adminmail, $basepath)
145         {
146                 $tpl = Renderer::getMarkupTemplate('local.config.tpl');
147                 $txt = Renderer::replaceMacros($tpl, [
148                         '$phpath' => $phppath,
149                         '$dbhost' => $dbhost,
150                         '$dbuser' => $dbuser,
151                         '$dbpass' => $dbpass,
152                         '$dbdata' => $dbdata,
153                         '$timezone' => $timezone,
154                         '$language' => $language,
155                         '$urlpath' => $urlpath,
156                         '$adminmail' => $adminmail,
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                         $help .= Renderer::replaceMacros($tpl, [
248                                 '$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.')],
249                         ]);
250                         $phppath = "";
251                 }
252
253                 $this->addCheck(L10n::t('Command line PHP') . ($passed ? " (<tt>$phppath</tt>)" : ""), $passed, false, $help);
254
255                 if ($passed) {
256                         $cmd = "$phppath -v";
257                         $result = trim(shell_exec($cmd));
258                         $passed2 = (strpos($result, "(cli)") !== false);
259                         list($result) = explode("\n", $result);
260                         $help = "";
261                         if (!$passed2) {
262                                 $help .= L10n::t("PHP executable is not the php cli binary \x28could be cgi-fgci version\x29") . EOL;
263                                 $help .= L10n::t('Found PHP version: ') . "<tt>$result</tt>";
264                         }
265                         $this->addCheck(L10n::t('PHP cli binary'), $passed2, true, $help);
266                 } else {
267                         // return if it was required
268                         return !$required;
269                 }
270
271                 if ($passed2) {
272                         $str = Strings::getRandomName(8);
273                         $cmd = "$phppath bin/testargs.php $str";
274                         $result = trim(shell_exec($cmd));
275                         $passed3 = $result == $str;
276                         $help = "";
277                         if (!$passed3) {
278                                 $help .= L10n::t('The command line version of PHP on your system does not have "register_argc_argv" enabled.') . EOL;
279                                 $help .= L10n::t('This is required for message delivery to work.');
280                         } else {
281                                 $this->phppath = $phppath;
282                         }
283
284                         $this->addCheck(L10n::t('PHP register_argc_argv'), $passed3, true, $help);
285                 }
286
287                 // passed2 & passed3 are required if first check passed
288                 return $passed2 && $passed3;
289         }
290
291         /**
292          * OpenSSL Check
293          *
294          * Checks the OpenSSL Environment
295          *
296          * - Checks, if the command "openssl_pkey_new" is available
297          *
298          * @return bool false if something required failed
299          */
300         public function checkKeys()
301         {
302                 $help = '';
303                 $res = false;
304                 $status = true;
305
306                 if (function_exists('openssl_pkey_new')) {
307                         $res = openssl_pkey_new([
308                                 'digest_alg' => 'sha1',
309                                 'private_key_bits' => 4096,
310                                 'encrypt_key' => false
311                         ]);
312                 }
313
314                 // Get private key
315                 if (!$res) {
316                         $help .= L10n::t('Error: the "openssl_pkey_new" function on this system is not able to generate encryption keys') . EOL;
317                         $help .= L10n::t('If running under Windows, please see "http://www.php.net/manual/en/openssl.installation.php".');
318                         $status = false;
319                 }
320                 $this->addCheck(L10n::t('Generate encryption keys'), $res, true, $help);
321
322                 return $status;
323         }
324
325         /**
326          * PHP basic function check
327          *
328          * @param string $name The name of the function
329          * @param string $title The (localized) title of the function
330          * @param string $help The (localized) help of the function
331          * @param boolean $required If true, this check is required
332          *
333          * @return bool false, if the check failed
334          */
335         private function checkFunction($name, $title, $help, $required)
336         {
337                 $currHelp = '';
338                 $status = true;
339                 if (!function_exists($name)) {
340                         $currHelp = $help;
341                         $status = false;
342                 }
343                 $this->addCheck($title, $status, $required, $currHelp);
344
345                 return $status || (!$status && !$required);
346         }
347
348         /**
349          * PHP functions Check
350          *
351          * Checks the following PHP functions
352          * - libCurl
353          * - GD Graphics
354          * - OpenSSL
355          * - PDO or MySQLi
356          * - mb_string
357          * - XML
358          * - iconv
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                 return $returnVal;
455         }
456
457         /**
458          * "config/local.config.php" - Check
459          *
460          * Checks if it's possible to create the "config/local.config.php"
461          *
462          * @return bool false if something required failed
463          */
464         public function checkLocalIni()
465         {
466                 $status = true;
467                 $help = "";
468                 if ((file_exists('config/local.config.php') && !is_writable('config/local.config.php')) ||
469                         (!file_exists('config/local.config.php') && !is_writable('.'))) {
470
471                         $status = false;
472                         $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;
473                         $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;
474                         $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;
475                         $help .= L10n::t('You can alternatively skip this procedure and perform a manual installation. Please see the file "INSTALL.txt" for instructions.') . EOL;
476                 }
477
478                 $this->addCheck(L10n::t('config/local.config.php is writable'), $status, false, $help);
479
480                 // Local INI File is not required
481                 return true;
482         }
483
484         /**
485          * Smarty3 Template Check
486          *
487          * Checks, if the directory of Smarty3 is writable
488          *
489          * @return bool false if something required failed
490          */
491         public function checkSmarty3()
492         {
493                 $status = true;
494                 $help = "";
495                 if (!is_writable('view/smarty3')) {
496
497                         $status = false;
498                         $help = L10n::t('Friendica uses the Smarty3 template engine to render its web views. Smarty3 compiles templates to PHP to speed up rendering.') . EOL;
499                         $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;
500                         $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;
501                         $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;
502                 }
503
504                 $this->addCheck(L10n::t('view/smarty3 is writable'), $status, true, $help);
505
506                 return $status;
507         }
508
509         /**
510          * ".htaccess" - Check
511          *
512          * Checks, if "url_rewrite" is enabled in the ".htaccess" file
513          *
514          * @param string $baseurl The baseurl of the app
515          * @return bool false if something required failed
516          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517          */
518         public function checkHtAccess($baseurl)
519         {
520                 $status = true;
521                 $help = "";
522                 $error_msg = "";
523                 if (function_exists('curl_init')) {
524                         $fetchResult = Network::fetchUrlFull($baseurl . "/install/testrewrite");
525
526                         $url = Strings::normaliseLink($baseurl . "/install/testrewrite");
527                         if ($fetchResult->getReturnCode() != 204) {
528                                 $fetchResult = Network::fetchUrlFull($url);
529                         }
530
531                         if ($fetchResult->getReturnCode() != 204) {
532                                 $status = false;
533                                 $help = L10n::t('Url rewrite in .htaccess is not working. Make sure you copied .htaccess-dist to .htaccess.');
534                                 $error_msg = [];
535                                 $error_msg['head'] = L10n::t('Error message from Curl when fetching');
536                                 $error_msg['url'] = $fetchResult->getRedirectUrl();
537                                 $error_msg['msg'] = $fetchResult->getError();
538                         }
539
540                         $this->addCheck(L10n::t('Url rewrite is working'), $status, true, $help, $error_msg);
541                 } else {
542                         // cannot check modrewrite if libcurl is not installed
543                         /// @TODO Maybe issue warning here?
544                 }
545
546                 return $status;
547         }
548
549         /**
550          * Imagick Check
551          *
552          * Checks, if the imagick module is available
553          *
554          * @return bool false if something required failed
555          */
556         public function checkImagick()
557         {
558                 $imagick = false;
559                 $gif = false;
560
561                 if (class_exists('Imagick')) {
562                         $imagick = true;
563                         $supported = Image::supportedTypes();
564                         if (array_key_exists('image/gif', $supported)) {
565                                 $gif = true;
566                         }
567                 }
568                 if (!$imagick) {
569                         $this->addCheck(L10n::t('ImageMagick PHP extension is not installed'), $imagick, false, "");
570                 } else {
571                         $this->addCheck(L10n::t('ImageMagick PHP extension is installed'), $imagick, false, "");
572                         if ($imagick) {
573                                 $this->addCheck(L10n::t('ImageMagick supports GIF'), $gif, false, "");
574                         }
575                 }
576
577                 // Imagick is not required
578                 return true;
579         }
580
581         /**
582          * Checking the Database connection and if it is available for the current installation
583          *
584          * @param string $dbhost Hostname/IP of the Friendica Database
585          * @param string $dbuser Username of the Database connection credentials
586          * @param string $dbpass Password of the Database connection credentials
587          * @param string $dbdata Name of the Database
588          *
589          * @return bool true if the check was successful, otherwise false
590          * @throws Exception
591          */
592         public function checkDB($dbhost, $dbuser, $dbpass, $dbdata)
593         {
594                 if (!DBA::connect($dbhost, $dbuser, $dbpass, $dbdata)) {
595                         $this->addCheck(L10n::t('Could not connect to database.'), false, true, '');
596
597                         return false;
598                 }
599
600                 if (DBA::connected()) {
601                         if (DBStructure::existsTable('user')) {
602                                 $this->addCheck(L10n::t('Database already in use.'), false, true, '');
603
604                                 return false;
605                         }
606                 }
607
608                 return true;
609         }
610 }