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