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