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