]> git.mxchange.org Git - friendica.git/blob - src/Core/Installer.php
Code cleanup
[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\ConfigCache;
10 use Friendica\Database\DBA;
11 use Friendica\Database\DBStructure;
12 use Friendica\Object\Image;
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 string $phppath   Path to the PHP-Binary (optional, if not set e.g. 'php' or '/usr/bin/php')
132          * @param string $urlpath   Path based on the URL of Friendica (e.g. '/friendica')
133          * @param string $dbhost    Hostname/IP of the Friendica Database
134          * @param string $dbuser    Username of the Database connection credentials
135          * @param string $dbpass    Password of the Database connection credentials
136          * @param string $dbdata    Name of the Database
137          * @param string $timezone  Timezone of the Friendica Installaton (e.g. 'Europe/Berlin')
138          * @param string $language  2-letter ISO 639-1 code (eg. 'en')
139          * @param string $adminmail Mail-Adress of the administrator
140          * @param string $basepath  The basepath of Friendica
141          *
142          * @return bool true if the config was created, otherwise false
143          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
144          */
145         public function createConfig($phppath, $urlpath, $dbhost, $dbuser, $dbpass, $dbdata, $timezone, $language, $adminmail, $basepath)
146         {
147                 $tpl = Renderer::getMarkupTemplate('local.config.tpl');
148                 $txt = Renderer::replaceMacros($tpl, [
149                         '$phpath' => $phppath,
150                         '$dbhost' => $dbhost,
151                         '$dbuser' => $dbuser,
152                         '$dbpass' => $dbpass,
153                         '$dbdata' => $dbdata,
154                         '$timezone' => $timezone,
155                         '$language' => $language,
156                         '$urlpath' => $urlpath,
157                         '$adminmail' => $adminmail,
158                 ]);
159
160                 $result = file_put_contents($basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.config.php', $txt);
161
162                 if (!$result) {
163                         $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'));
164                 }
165
166                 return $result;
167         }
168
169         /***
170          * Installs the DB-Scheme for Friendica
171          *
172          * @param string $basePath The base path of this application
173          *
174          * @return bool true if the installation was successful, otherwise false
175          * @throws Exception
176          */
177         public function installDatabase($basePath)
178         {
179                 $result = DBStructure::update($basePath, false, true, true);
180
181                 if ($result) {
182                         $txt = L10n::t('You may need to import the file "database.sql" manually using phpmyadmin or mysql.') . EOL;
183                         $txt .= L10n::t('Please see the file "INSTALL.txt".');
184
185                         $this->addCheck($txt, false, true, htmlentities($result, ENT_COMPAT, 'UTF-8'));
186
187                         return false;
188                 }
189
190                 return true;
191         }
192
193         /**
194          * Adds new checks to the array $checks
195          *
196          * @param string $title The title of the current check
197          * @param bool $status 1 = check passed, 0 = check not passed
198          * @param bool $required 1 = check is mandatory, 0 = check is optional
199          * @param string $help A help-string for the current check
200          * @param string $error_msg Optional. A error message, if the current check failed
201          */
202         private function addCheck($title, $status, $required, $help, $error_msg = "")
203         {
204                 array_push($this->checks, [
205                         'title' => $title,
206                         'status' => $status,
207                         'required' => $required,
208                         'help' => $help,
209                         'error_msg' => $error_msg,
210                 ]);
211         }
212
213         /**
214          * PHP Check
215          *
216          * Checks the PHP environment.
217          *
218          * - Checks if a PHP binary is available
219          * - Checks if it is the CLI version
220          * - Checks if "register_argc_argv" is enabled
221          *
222          * @param string $phppath  Optional. The Path to the PHP-Binary
223          * @param bool   $required Optional. If set to true, the PHP-Binary has to exist (Default false)
224          *
225          * @return bool false if something required failed
226          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227          */
228         public function checkPHP($phppath = null, $required = false)
229         {
230                 $passed3 = false;
231
232                 if (!isset($phppath)) {
233                         $phppath = 'php';
234                 }
235
236                 $passed = file_exists($phppath);
237                 if (!$passed) {
238                         $phppath = trim(shell_exec('which ' . $phppath));
239                         $passed = strlen($phppath);
240                 }
241
242                 $help = "";
243                 if (!$passed) {
244                         $help .= L10n::t('Could not find a command line version of PHP in the web server PATH.') . EOL;
245                         $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;
246                         $help .= EOL . EOL;
247                         $tpl = Renderer::getMarkupTemplate('field_input.tpl');
248                         $help .= Renderer::replaceMacros($tpl, [
249                                 '$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.')],
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          * - POSIX
361          *
362          * @return bool false if something required failed
363          */
364         public function checkFunctions()
365         {
366                 $returnVal = true;
367
368                 $help = '';
369                 $status = true;
370                 if (function_exists('apache_get_modules')) {
371                         if (!in_array('mod_rewrite', apache_get_modules())) {
372                                 $help = L10n::t('Error: Apache webserver mod-rewrite module is required but not installed.');
373                                 $status = false;
374                                 $returnVal = false;
375                         }
376                 }
377                 $this->addCheck(L10n::t('Apache mod_rewrite module'), $status, true, $help);
378
379                 $help = '';
380                 $status = true;
381                 if (!function_exists('mysqli_connect') && !class_exists('pdo')) {
382                         $status = false;
383                         $help = L10n::t('Error: PDO or MySQLi PHP module required but not installed.');
384                         $returnVal = false;
385                 } else {
386                         if (!function_exists('mysqli_connect') && class_exists('pdo') && !in_array('mysql', \PDO::getAvailableDrivers())) {
387                                 $status = false;
388                                 $help = L10n::t('Error: The MySQL driver for PDO is not installed.');
389                                 $returnVal = false;
390                         }
391                 }
392                 $this->addCheck(L10n::t('PDO or MySQLi PHP module'), $status, true, $help);
393
394                 // check for XML DOM Documents being able to be generated
395                 $help = '';
396                 $status = true;
397                 try {
398                         new DOMDocument();
399                 } catch (Exception $e) {
400                         $help = L10n::t('Error, XML PHP module required but not installed.');
401                         $status = false;
402                         $returnVal = false;
403                 }
404                 $this->addCheck(L10n::t('XML PHP module'), $status, true, $help);
405
406                 $status = $this->checkFunction('curl_init',
407                         L10n::t('libCurl PHP module'),
408                         L10n::t('Error: libCURL PHP module required but not installed.'),
409                         true
410                 );
411                 $returnVal = $returnVal ? $status : false;
412
413                 $status = $this->checkFunction('imagecreatefromjpeg',
414                         L10n::t('GD graphics PHP module'),
415                         L10n::t('Error: GD graphics PHP module with JPEG support required but not installed.'),
416                         true
417                 );
418                 $returnVal = $returnVal ? $status : false;
419
420                 $status = $this->checkFunction('openssl_public_encrypt',
421                         L10n::t('OpenSSL PHP module'),
422                         L10n::t('Error: openssl PHP module required but not installed.'),
423                         true
424                 );
425                 $returnVal = $returnVal ? $status : false;
426
427                 $status = $this->checkFunction('mb_strlen',
428                         L10n::t('mb_string PHP module'),
429                         L10n::t('Error: mb_string PHP module required but not installed.'),
430                         true
431                 );
432                 $returnVal = $returnVal ? $status : false;
433
434                 $status = $this->checkFunction('iconv_strlen',
435                         L10n::t('iconv PHP module'),
436                         L10n::t('Error: iconv PHP module required but not installed.'),
437                         true
438                 );
439                 $returnVal = $returnVal ? $status : false;
440
441                 $status = $this->checkFunction('posix_kill',
442                         L10n::t('POSIX PHP module'),
443                         L10n::t('Error: POSIX PHP module required but not installed.'),
444                         true
445                 );
446                 $returnVal = $returnVal ? $status : false;
447
448                 $status = $this->checkFunction('json_encode',
449                         L10n::t('JSON PHP module'),
450                         L10n::t('Error: JSON PHP module required but not installed.'),
451                         true
452                 );
453                 $returnVal = $returnVal ? $status : false;
454
455                 return $returnVal;
456         }
457
458         /**
459          * "config/local.config.php" - Check
460          *
461          * Checks if it's possible to create the "config/local.config.php"
462          *
463          * @return bool false if something required failed
464          */
465         public function checkLocalIni()
466         {
467                 $status = true;
468                 $help = "";
469                 if ((file_exists('config/local.config.php') && !is_writable('config/local.config.php')) ||
470                         (!file_exists('config/local.config.php') && !is_writable('.'))) {
471
472                         $status = false;
473                         $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;
474                         $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;
475                         $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;
476                         $help .= L10n::t('You can alternatively skip this procedure and perform a manual installation. Please see the file "INSTALL.txt" for instructions.') . EOL;
477                 }
478
479                 $this->addCheck(L10n::t('config/local.config.php is writable'), $status, false, $help);
480
481                 // Local INI File is not required
482                 return true;
483         }
484
485         /**
486          * Smarty3 Template Check
487          *
488          * Checks, if the directory of Smarty3 is writable
489          *
490          * @return bool false if something required failed
491          */
492         public function checkSmarty3()
493         {
494                 $status = true;
495                 $help = "";
496                 if (!is_writable('view/smarty3')) {
497
498                         $status = false;
499                         $help = L10n::t('Friendica uses the Smarty3 template engine to render its web views. Smarty3 compiles templates to PHP to speed up rendering.') . EOL;
500                         $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;
501                         $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;
502                         $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;
503                 }
504
505                 $this->addCheck(L10n::t('view/smarty3 is writable'), $status, true, $help);
506
507                 return $status;
508         }
509
510         /**
511          * ".htaccess" - Check
512          *
513          * Checks, if "url_rewrite" is enabled in the ".htaccess" file
514          *
515          * @param string $baseurl The baseurl of the app
516          * @return bool false if something required failed
517          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
518          */
519         public function checkHtAccess($baseurl)
520         {
521                 $status = true;
522                 $help = "";
523                 $error_msg = "";
524                 if (function_exists('curl_init')) {
525                         $fetchResult = Network::fetchUrlFull($baseurl . "/install/testrewrite");
526
527                         $url = Strings::normaliseLink($baseurl . "/install/testrewrite");
528                         if ($fetchResult->getReturnCode() != 204) {
529                                 $fetchResult = Network::fetchUrlFull($url);
530                         }
531
532                         if ($fetchResult->getReturnCode() != 204) {
533                                 $status = false;
534                                 $help = L10n::t('Url rewrite in .htaccess is not working. Make sure you copied .htaccess-dist to .htaccess.');
535                                 $error_msg = [];
536                                 $error_msg['head'] = L10n::t('Error message from Curl when fetching');
537                                 $error_msg['url'] = $fetchResult->getRedirectUrl();
538                                 $error_msg['msg'] = $fetchResult->getError();
539                         }
540
541                         $this->addCheck(L10n::t('Url rewrite is working'), $status, true, $help, $error_msg);
542                 } else {
543                         // cannot check modrewrite if libcurl is not installed
544                         /// @TODO Maybe issue warning here?
545                 }
546
547                 return $status;
548         }
549
550         /**
551          * Imagick Check
552          *
553          * Checks, if the imagick module is available
554          *
555          * @return bool false if something required failed
556          */
557         public function checkImagick()
558         {
559                 $imagick = false;
560                 $gif = false;
561
562                 if (class_exists('Imagick')) {
563                         $imagick = true;
564                         $supported = Image::supportedTypes();
565                         if (array_key_exists('image/gif', $supported)) {
566                                 $gif = true;
567                         }
568                 }
569                 if (!$imagick) {
570                         $this->addCheck(L10n::t('ImageMagick PHP extension is not installed'), $imagick, false, "");
571                 } else {
572                         $this->addCheck(L10n::t('ImageMagick PHP extension is installed'), $imagick, false, "");
573                         if ($imagick) {
574                                 $this->addCheck(L10n::t('ImageMagick supports GIF'), $gif, false, "");
575                         }
576                 }
577
578                 // Imagick is not required
579                 return true;
580         }
581
582         /**
583          * Checking the Database connection and if it is available for the current installation
584          *
585          * @param ConfigCache $configCache The configuration cache
586          * @param string $dbhost           Hostname/IP of the Friendica Database
587          * @param string $dbuser           Username of the Database connection credentials
588          * @param string $dbpass           Password of the Database connection credentials
589          * @param string $dbdata           Name of the Database
590          *
591          * @return bool true if the check was successful, otherwise false
592          * @throws Exception
593          */
594         public function checkDB(ConfigCache $configCache, $dbhost, $dbuser, $dbpass, $dbdata)
595         {
596                 if (!DBA::connect($configCache, $dbhost, $dbuser, $dbpass, $dbdata)) {
597                         $this->addCheck(L10n::t('Could not connect to database.'), false, true, '');
598
599                         return false;
600                 }
601
602                 if (DBA::connected()) {
603                         if (DBStructure::existsTable('user')) {
604                                 $this->addCheck(L10n::t('Database already in use.'), false, true, '');
605
606                                 return false;
607                         }
608                 }
609
610                 return true;
611         }
612 }