3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core;
26 use Friendica\Core\Config\Cache;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBStructure;
30 use Friendica\Util\Images;
31 use Friendica\Util\Strings;
34 * Contains methods for installation purpose of Friendica
38 // Default values for the install page
39 const DEFAULT_LANG = 'en';
40 const DEFAULT_TZ = 'America/Los_Angeles';
41 const DEFAULT_HOST = 'localhost';
44 * @var array the check outcomes
49 * @var string The path to the PHP binary
51 private $phppath = null;
54 * Returns all checks made
56 * @return array the checks
58 public function getChecks()
64 * Returns the PHP path
66 * @return string the PHP Path
67 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69 public function getPHPPath()
71 // if not set, determine the PHP path
72 if (!isset($this->phppath)) {
77 return $this->phppath;
83 public function resetChecks()
89 * Install constructor.
92 public function __construct()
98 * Checks the current installation environment. There are optional and mandatory checks.
100 * @param string $baseurl The baseurl of Friendica
101 * @param string $phpath Optional path to the PHP binary
103 * @return bool if the check succeed
104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
106 public function checkEnvironment($baseurl, $phpath = null)
110 if (isset($phpath)) {
111 if (!$this->checkPHP($phpath)) {
116 if (!$this->checkFunctions()) {
120 if (!$this->checkImagick()) {
124 if (!$this->checkLocalIni()) {
128 if (!$this->checkSmarty3()) {
132 if (!$this->checkTLS()) {
136 if (!$this->checkKeys()) {
140 /// @TODO This check should not block installations because of containerization issues
141 /// @see https://github.com/friendica/docker/issues/134
142 $this->checkHtAccess($baseurl);
148 * Executes the installation of Friendica in the given environment.
149 * - Creates `config/local.config.php`
150 * - Installs Database Structure
152 * @param Cache $configCache The config cache with all config relevant information
154 * @return bool true if the config was created, otherwise false
155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
157 public function createConfig(Cache $configCache)
159 $basepath = $configCache->get('system', 'basepath');
161 $tpl = Renderer::getMarkupTemplate('local.config.tpl');
162 $txt = Renderer::replaceMacros($tpl, [
163 '$dbhost' => $configCache->get('database', 'hostname'),
164 '$dbuser' => $configCache->get('database', 'username'),
165 '$dbpass' => $configCache->get('database', 'password'),
166 '$dbdata' => $configCache->get('database', 'database'),
168 '$phpath' => $configCache->get('config', 'php_path'),
169 '$adminmail' => $configCache->get('config', 'admin_email'),
170 '$hostname' => $configCache->get('config', 'hostname'),
172 '$urlpath' => $configCache->get('system', 'urlpath'),
173 '$baseurl' => $configCache->get('system', 'url'),
174 '$sslpolicy' => $configCache->get('system', 'ssl_policy'),
175 '$basepath' => $basepath,
176 '$timezone' => $configCache->get('system', 'default_timezone'),
177 '$language' => $configCache->get('system', 'language'),
180 $result = file_put_contents($basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.config.php', $txt);
183 $this->addCheck(DI::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'));
190 * Installs the DB-Scheme for Friendica
192 * @param string $basePath The base path of this application
194 * @return bool true if the installation was successful, otherwise false
197 public function installDatabase($basePath)
199 $result = DBStructure::install($basePath);
202 $txt = DI::l10n()->t('You may need to import the file "database.sql" manually using phpmyadmin or mysql.') . EOL;
203 $txt .= DI::l10n()->t('Please see the file "doc/INSTALL.md".');
205 $this->addCheck($txt, false, true, htmlentities($result, ENT_COMPAT, 'UTF-8'));
214 * Adds new checks to the array $checks
216 * @param string $title The title of the current check
217 * @param bool $status 1 = check passed, 0 = check not passed
218 * @param bool $required 1 = check is mandatory, 0 = check is optional
219 * @param string $help A help-string for the current check
220 * @param string $error_msg Optional. A error message, if the current check failed
222 private function addCheck($title, $status, $required, $help, $error_msg = "")
224 array_push($this->checks, [
227 'required' => $required,
229 'error_msg' => $error_msg,
236 * Checks the PHP environment.
238 * - Checks if a PHP binary is available
239 * - Checks if it is the CLI version
240 * - Checks if "register_argc_argv" is enabled
242 * @param string $phppath Optional. The Path to the PHP-Binary
243 * @param bool $required Optional. If set to true, the PHP-Binary has to exist (Default false)
245 * @return bool false if something required failed
246 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
248 public function checkPHP($phppath = null, $required = false)
252 if (!isset($phppath)) {
256 $passed = file_exists($phppath);
258 $phppath = trim(shell_exec('which ' . $phppath));
259 $passed = strlen($phppath);
264 $help .= DI::l10n()->t('Could not find a command line version of PHP in the web server PATH.') . EOL;
265 $help .= DI::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/stable/doc/Install.md#set-up-the-worker'>'Setup the worker'</a>") . EOL;
267 $tpl = Renderer::getMarkupTemplate('field_input.tpl');
268 /// @todo Separate backend Installer class and presentation layer/view
269 $help .= Renderer::replaceMacros($tpl, [
270 '$field' => ['config-php_path', DI::l10n()->t('PHP executable path'), $phppath, DI::l10n()->t('Enter full path to php executable. You can leave this blank to continue the installation.')],
275 $this->addCheck(DI::l10n()->t('Command line PHP') . ($passed ? " (<tt>$phppath</tt>)" : ""), $passed, false, $help);
278 $cmd = "$phppath -v";
279 $result = trim(shell_exec($cmd));
280 $passed2 = (strpos($result, "(cli)") !== false);
281 list($result) = explode("\n", $result);
284 $help .= DI::l10n()->t("PHP executable is not the php cli binary \x28could be cgi-fgci version\x29") . EOL;
285 $help .= DI::l10n()->t('Found PHP version: ') . "<tt>$result</tt>";
287 $this->addCheck(DI::l10n()->t('PHP cli binary'), $passed2, true, $help);
289 // return if it was required
294 $str = Strings::getRandomName(8);
295 $cmd = "$phppath bin/testargs.php $str";
296 $result = trim(shell_exec($cmd));
297 $passed3 = $result == $str;
300 $help .= DI::l10n()->t('The command line version of PHP on your system does not have "register_argc_argv" enabled.') . EOL;
301 $help .= DI::l10n()->t('This is required for message delivery to work.');
303 $this->phppath = $phppath;
306 $this->addCheck(DI::l10n()->t('PHP register_argc_argv'), $passed3, true, $help);
309 // passed2 & passed3 are required if first check passed
310 return $passed2 && $passed3;
316 * Checks the OpenSSL Environment
318 * - Checks, if the command "openssl_pkey_new" is available
320 * @return bool false if something required failed
322 public function checkKeys()
328 if (function_exists('openssl_pkey_new')) {
329 $res = openssl_pkey_new([
330 'digest_alg' => 'sha1',
331 'private_key_bits' => 4096,
332 'encrypt_key' => false
338 $help .= DI::l10n()->t('Error: the "openssl_pkey_new" function on this system is not able to generate encryption keys') . EOL;
339 $help .= DI::l10n()->t('If running under Windows, please see "http://www.php.net/manual/en/openssl.installation.php".');
342 $this->addCheck(DI::l10n()->t('Generate encryption keys'), $res, true, $help);
348 * PHP basic function check
350 * @param string $name The name of the function
351 * @param string $title The (localized) title of the function
352 * @param string $help The (localized) help of the function
353 * @param boolean $required If true, this check is required
355 * @return bool false, if the check failed
357 private function checkFunction($name, $title, $help, $required)
361 if (!function_exists($name)) {
365 $this->addCheck($title, $status, $required, $currHelp);
367 return $status || (!$status && !$required);
371 * PHP functions Check
373 * Checks the following PHP functions
384 * @return bool false if something required failed
386 public function checkFunctions()
392 if (function_exists('apache_get_modules')) {
393 if (!in_array('mod_rewrite', apache_get_modules())) {
394 $help = DI::l10n()->t('Error: Apache webserver mod-rewrite module is required but not installed.');
399 $this->addCheck(DI::l10n()->t('Apache mod_rewrite module'), $status, true, $help);
403 if (!function_exists('mysqli_connect') && !class_exists('pdo')) {
405 $help = DI::l10n()->t('Error: PDO or MySQLi PHP module required but not installed.');
408 if (!function_exists('mysqli_connect') && class_exists('pdo') && !in_array('mysql', \PDO::getAvailableDrivers())) {
410 $help = DI::l10n()->t('Error: The MySQL driver for PDO is not installed.');
414 $this->addCheck(DI::l10n()->t('PDO or MySQLi PHP module'), $status, true, $help);
416 // check for XML DOM Documents being able to be generated
421 } catch (Exception $e) {
422 $help = DI::l10n()->t('Error, XML PHP module required but not installed.');
426 $this->addCheck(DI::l10n()->t('XML PHP module'), $status, true, $help);
428 $status = $this->checkFunction('curl_init',
429 DI::l10n()->t('libCurl PHP module'),
430 DI::l10n()->t('Error: libCURL PHP module required but not installed.'),
433 $returnVal = $returnVal ? $status : false;
435 $status = $this->checkFunction('imagecreatefromjpeg',
436 DI::l10n()->t('GD graphics PHP module'),
437 DI::l10n()->t('Error: GD graphics PHP module with JPEG support required but not installed.'),
440 $returnVal = $returnVal ? $status : false;
442 $status = $this->checkFunction('openssl_public_encrypt',
443 DI::l10n()->t('OpenSSL PHP module'),
444 DI::l10n()->t('Error: openssl PHP module required but not installed.'),
447 $returnVal = $returnVal ? $status : false;
449 $status = $this->checkFunction('mb_strlen',
450 DI::l10n()->t('mb_string PHP module'),
451 DI::l10n()->t('Error: mb_string PHP module required but not installed.'),
454 $returnVal = $returnVal ? $status : false;
456 $status = $this->checkFunction('iconv_strlen',
457 DI::l10n()->t('iconv PHP module'),
458 DI::l10n()->t('Error: iconv PHP module required but not installed.'),
461 $returnVal = $returnVal ? $status : false;
463 $status = $this->checkFunction('posix_kill',
464 DI::l10n()->t('POSIX PHP module'),
465 DI::l10n()->t('Error: POSIX PHP module required but not installed.'),
468 $returnVal = $returnVal ? $status : false;
470 $status = $this->checkFunction('proc_open',
471 DI::l10n()->t('Program execution functions'),
472 DI::l10n()->t('Error: Program execution functions (proc_open) required but not enabled.'),
475 $returnVal = $returnVal ? $status : false;
477 $status = $this->checkFunction('json_encode',
478 DI::l10n()->t('JSON PHP module'),
479 DI::l10n()->t('Error: JSON PHP module required but not installed.'),
482 $returnVal = $returnVal ? $status : false;
484 $status = $this->checkFunction('finfo_open',
485 DI::l10n()->t('File Information PHP module'),
486 DI::l10n()->t('Error: File Information PHP module required but not installed.'),
489 $returnVal = $returnVal ? $status : false;
495 * "config/local.config.php" - Check
497 * Checks if it's possible to create the "config/local.config.php"
499 * @return bool false if something required failed
501 public function checkLocalIni()
505 if ((file_exists('config/local.config.php') && !is_writable('config/local.config.php')) ||
506 (!file_exists('config/local.config.php') && !is_writable('.'))) {
509 $help = DI::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;
510 $help .= DI::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;
511 $help .= DI::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;
512 $help .= DI::l10n()->t('You can alternatively skip this procedure and perform a manual installation. Please see the file "doc/INSTALL.md" for instructions.') . EOL;
515 $this->addCheck(DI::l10n()->t('config/local.config.php is writable'), $status, false, $help);
517 // Local INI File is not required
522 * Smarty3 Template Check
524 * Checks, if the directory of Smarty3 is writable
526 * @return bool false if something required failed
528 public function checkSmarty3()
532 if (!is_writable('view/smarty3')) {
535 $help = DI::l10n()->t('Friendica uses the Smarty3 template engine to render its web views. Smarty3 compiles templates to PHP to speed up rendering.') . EOL;
536 $help .= DI::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;
537 $help .= DI::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;
538 $help .= DI::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;
541 $this->addCheck(DI::l10n()->t('view/smarty3 is writable'), $status, true, $help);
547 * ".htaccess" - Check
549 * Checks, if "url_rewrite" is enabled in the ".htaccess" file
551 * @param string $baseurl The baseurl of the app
552 * @return bool false if something required failed
554 public function checkHtAccess($baseurl)
559 if (function_exists('curl_init')) {
560 $fetchResult = DI::httpClient()->fetchFull($baseurl . "/install/testrewrite");
562 $url = Strings::normaliseLink($baseurl . "/install/testrewrite");
563 if ($fetchResult->getReturnCode() != 204) {
564 $fetchResult = DI::httpClient()->fetchFull($url);
567 if ($fetchResult->getReturnCode() != 204) {
569 $help = DI::l10n()->t('Url rewrite in .htaccess seems not working. Make sure you copied .htaccess-dist to .htaccess.') . EOL;
570 $help .= DI::l10n()->t('In some circumstances (like running inside containers), you can skip this error.');
572 $error_msg['head'] = DI::l10n()->t('Error message from Curl when fetching');
573 $error_msg['url'] = $fetchResult->getRedirectUrl();
574 $error_msg['msg'] = $fetchResult->getError();
577 /// @TODO Required false because of cURL issues in containers - see https://github.com/friendica/docker/issues/134
578 $this->addCheck(DI::l10n()->t('Url rewrite is working'), $status, false, $help, $error_msg);
580 // cannot check modrewrite if libcurl is not installed
581 /// @TODO Maybe issue warning here?
590 * Tries to determine whether the connection to the server is secured
591 * by TLS or not. If not the user will be warned that it is higly
592 * encuraged to use TLS.
594 * @return bool (true) as TLS is not mandatory
596 public function checkTLS()
600 if (isset($_SERVER['HTTPS'])) {
601 if (($_SERVER['HTTPS'] == 1) || ($_SERVER['HTTPS'] == 'on')) {
607 $help = DI::l10n()->t('The detection of TLS to secure the communication between the browser and the new Friendica server failed.');
608 $help .= ' ' . DI::l10n()->t('It is highly encouraged to use Friendica only over a secure connection as sensitive information like passwords will be transmitted.');
609 $help .= ' ' . DI::l10n()->t('Please ensure that the connection to the server is secure.');
610 $this->addCheck(DI::l10n()->t('No TLS detected'), $tls, false, $help);
612 $this->addCheck(DI::l10n()->t('TLS detected'), $tls, false, '');
615 // TLS is not required
622 * Checks, if the imagick module is available
624 * @return bool false if something required failed
626 public function checkImagick()
631 if (class_exists('Imagick')) {
633 $supported = Images::supportedTypes();
634 if (array_key_exists('image/gif', $supported)) {
639 $this->addCheck(DI::l10n()->t('ImageMagick PHP extension is not installed'), $imagick, false, "");
641 $this->addCheck(DI::l10n()->t('ImageMagick PHP extension is installed'), $imagick, false, "");
643 $this->addCheck(DI::l10n()->t('ImageMagick supports GIF'), $gif, false, "");
647 // Imagick is not required
652 * Checking the Database connection and if it is available for the current installation
654 * @param Database $dba
656 * @return bool true if the check was successful, otherwise false
659 public function checkDB(Database $dba)
663 if ($dba->isConnected()) {
664 if (DBStructure::existsTable('user')) {
665 $this->addCheck(DI::l10n()->t('Database already in use.'), false, true, '');
670 $this->addCheck(DI::l10n()->t('Could not connect to database.'), false, true, '');
679 * Setup the default cache for a new installation
681 * @param Cache $configCache The configuration cache
682 * @param string $basePath The determined basepath
684 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
686 public function setUpCache(Cache $configCache, $basePath)
688 $configCache->set('config', 'php_path' , $this->getPHPPath());
689 $configCache->set('system', 'basepath' , $basePath);