3 * @copyright Copyright (C) 2020, Friendica
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\Network;
32 use Friendica\Util\Strings;
35 * Contains methods for installation purpose of Friendica
39 // Default values for the install page
40 const DEFAULT_LANG = 'en';
41 const DEFAULT_TZ = 'America/Los_Angeles';
42 const DEFAULT_HOST = 'localhost';
45 * @var array the check outcomes
50 * @var string The path to the PHP binary
52 private $phppath = null;
55 * Returns all checks made
57 * @return array the checks
59 public function getChecks()
65 * Returns the PHP path
67 * @return string the PHP Path
68 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
70 public function getPHPPath()
72 // if not set, determine the PHP path
73 if (!isset($this->phppath)) {
78 return $this->phppath;
84 public function resetChecks()
90 * Install constructor.
93 public function __construct()
99 * Checks the current installation environment. There are optional and mandatory checks.
101 * @param string $baseurl The baseurl of Friendica
102 * @param string $phpath Optional path to the PHP binary
104 * @return bool if the check succeed
105 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
107 public function checkEnvironment($baseurl, $phpath = null)
111 if (isset($phpath)) {
112 if (!$this->checkPHP($phpath)) {
117 if (!$this->checkFunctions()) {
121 if (!$this->checkImagick()) {
125 if (!$this->checkLocalIni()) {
129 if (!$this->checkSmarty3()) {
133 if (!$this->checkKeys()) {
137 if (!$this->checkHtAccess($baseurl)) {
145 * Executes the installation of Friendica in the given environment.
146 * - Creates `config/local.config.php`
147 * - Installs Database Structure
149 * @param Cache $configCache The config cache with all config relevant information
151 * @return bool true if the config was created, otherwise false
152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154 public function createConfig(Cache $configCache)
156 $basepath = $configCache->get('system', 'basepath');
158 $tpl = Renderer::getMarkupTemplate('local.config.tpl');
159 $txt = Renderer::replaceMacros($tpl, [
160 '$dbhost' => $configCache->get('database', 'hostname'),
161 '$dbuser' => $configCache->get('database', 'username'),
162 '$dbpass' => $configCache->get('database', 'password'),
163 '$dbdata' => $configCache->get('database', 'database'),
165 '$phpath' => $configCache->get('config', 'php_path'),
166 '$adminmail' => $configCache->get('config', 'admin_email'),
167 '$hostname' => $configCache->get('config', 'hostname'),
169 '$urlpath' => $configCache->get('system', 'urlpath'),
170 '$baseurl' => $configCache->get('system', 'url'),
171 '$sslpolicy' => $configCache->get('system', 'ssl_policy'),
172 '$basepath' => $basepath,
173 '$timezone' => $configCache->get('system', 'default_timezone'),
174 '$language' => $configCache->get('system', 'language'),
177 $result = file_put_contents($basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.config.php', $txt);
180 $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'));
187 * Installs the DB-Scheme for Friendica
189 * @param string $basePath The base path of this application
191 * @return bool true if the installation was successful, otherwise false
194 public function installDatabase($basePath)
196 $result = DBStructure::update($basePath, false, true, true);
199 $txt = DI::l10n()->t('You may need to import the file "database.sql" manually using phpmyadmin or mysql.') . EOL;
200 $txt .= DI::l10n()->t('Please see the file "INSTALL.txt".');
202 $this->addCheck($txt, false, true, htmlentities($result, ENT_COMPAT, 'UTF-8'));
211 * Adds new checks to the array $checks
213 * @param string $title The title of the current check
214 * @param bool $status 1 = check passed, 0 = check not passed
215 * @param bool $required 1 = check is mandatory, 0 = check is optional
216 * @param string $help A help-string for the current check
217 * @param string $error_msg Optional. A error message, if the current check failed
219 private function addCheck($title, $status, $required, $help, $error_msg = "")
221 array_push($this->checks, [
224 'required' => $required,
226 'error_msg' => $error_msg,
233 * Checks the PHP environment.
235 * - Checks if a PHP binary is available
236 * - Checks if it is the CLI version
237 * - Checks if "register_argc_argv" is enabled
239 * @param string $phppath Optional. The Path to the PHP-Binary
240 * @param bool $required Optional. If set to true, the PHP-Binary has to exist (Default false)
242 * @return bool false if something required failed
243 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
245 public function checkPHP($phppath = null, $required = false)
249 if (!isset($phppath)) {
253 $passed = file_exists($phppath);
255 $phppath = trim(shell_exec('which ' . $phppath));
256 $passed = strlen($phppath);
261 $help .= DI::l10n()->t('Could not find a command line version of PHP in the web server PATH.') . EOL;
262 $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/master/doc/Install.md#set-up-the-worker'>'Setup the worker'</a>") . EOL;
264 $tpl = Renderer::getMarkupTemplate('field_input.tpl');
265 /// @todo Separate backend Installer class and presentation layer/view
266 $help .= Renderer::replaceMacros($tpl, [
267 '$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.')],
272 $this->addCheck(DI::l10n()->t('Command line PHP') . ($passed ? " (<tt>$phppath</tt>)" : ""), $passed, false, $help);
275 $cmd = "$phppath -v";
276 $result = trim(shell_exec($cmd));
277 $passed2 = (strpos($result, "(cli)") !== false);
278 list($result) = explode("\n", $result);
281 $help .= DI::l10n()->t("PHP executable is not the php cli binary \x28could be cgi-fgci version\x29") . EOL;
282 $help .= DI::l10n()->t('Found PHP version: ') . "<tt>$result</tt>";
284 $this->addCheck(DI::l10n()->t('PHP cli binary'), $passed2, true, $help);
286 // return if it was required
291 $str = Strings::getRandomName(8);
292 $cmd = "$phppath bin/testargs.php $str";
293 $result = trim(shell_exec($cmd));
294 $passed3 = $result == $str;
297 $help .= DI::l10n()->t('The command line version of PHP on your system does not have "register_argc_argv" enabled.') . EOL;
298 $help .= DI::l10n()->t('This is required for message delivery to work.');
300 $this->phppath = $phppath;
303 $this->addCheck(DI::l10n()->t('PHP register_argc_argv'), $passed3, true, $help);
306 // passed2 & passed3 are required if first check passed
307 return $passed2 && $passed3;
313 * Checks the OpenSSL Environment
315 * - Checks, if the command "openssl_pkey_new" is available
317 * @return bool false if something required failed
319 public function checkKeys()
325 if (function_exists('openssl_pkey_new')) {
326 $res = openssl_pkey_new([
327 'digest_alg' => 'sha1',
328 'private_key_bits' => 4096,
329 'encrypt_key' => false
335 $help .= DI::l10n()->t('Error: the "openssl_pkey_new" function on this system is not able to generate encryption keys') . EOL;
336 $help .= DI::l10n()->t('If running under Windows, please see "http://www.php.net/manual/en/openssl.installation.php".');
339 $this->addCheck(DI::l10n()->t('Generate encryption keys'), $res, true, $help);
345 * PHP basic function check
347 * @param string $name The name of the function
348 * @param string $title The (localized) title of the function
349 * @param string $help The (localized) help of the function
350 * @param boolean $required If true, this check is required
352 * @return bool false, if the check failed
354 private function checkFunction($name, $title, $help, $required)
358 if (!function_exists($name)) {
362 $this->addCheck($title, $status, $required, $currHelp);
364 return $status || (!$status && !$required);
368 * PHP functions Check
370 * Checks the following PHP functions
381 * @return bool false if something required failed
383 public function checkFunctions()
389 if (function_exists('apache_get_modules')) {
390 if (!in_array('mod_rewrite', apache_get_modules())) {
391 $help = DI::l10n()->t('Error: Apache webserver mod-rewrite module is required but not installed.');
396 $this->addCheck(DI::l10n()->t('Apache mod_rewrite module'), $status, true, $help);
400 if (!function_exists('mysqli_connect') && !class_exists('pdo')) {
402 $help = DI::l10n()->t('Error: PDO or MySQLi PHP module required but not installed.');
405 if (!function_exists('mysqli_connect') && class_exists('pdo') && !in_array('mysql', \PDO::getAvailableDrivers())) {
407 $help = DI::l10n()->t('Error: The MySQL driver for PDO is not installed.');
411 $this->addCheck(DI::l10n()->t('PDO or MySQLi PHP module'), $status, true, $help);
413 // check for XML DOM Documents being able to be generated
418 } catch (Exception $e) {
419 $help = DI::l10n()->t('Error, XML PHP module required but not installed.');
423 $this->addCheck(DI::l10n()->t('XML PHP module'), $status, true, $help);
425 $status = $this->checkFunction('curl_init',
426 DI::l10n()->t('libCurl PHP module'),
427 DI::l10n()->t('Error: libCURL PHP module required but not installed.'),
430 $returnVal = $returnVal ? $status : false;
432 $status = $this->checkFunction('imagecreatefromjpeg',
433 DI::l10n()->t('GD graphics PHP module'),
434 DI::l10n()->t('Error: GD graphics PHP module with JPEG support required but not installed.'),
437 $returnVal = $returnVal ? $status : false;
439 $status = $this->checkFunction('openssl_public_encrypt',
440 DI::l10n()->t('OpenSSL PHP module'),
441 DI::l10n()->t('Error: openssl PHP module required but not installed.'),
444 $returnVal = $returnVal ? $status : false;
446 $status = $this->checkFunction('mb_strlen',
447 DI::l10n()->t('mb_string PHP module'),
448 DI::l10n()->t('Error: mb_string PHP module required but not installed.'),
451 $returnVal = $returnVal ? $status : false;
453 $status = $this->checkFunction('iconv_strlen',
454 DI::l10n()->t('iconv PHP module'),
455 DI::l10n()->t('Error: iconv PHP module required but not installed.'),
458 $returnVal = $returnVal ? $status : false;
460 $status = $this->checkFunction('posix_kill',
461 DI::l10n()->t('POSIX PHP module'),
462 DI::l10n()->t('Error: POSIX PHP module required but not installed.'),
465 $returnVal = $returnVal ? $status : false;
467 $status = $this->checkFunction('json_encode',
468 DI::l10n()->t('JSON PHP module'),
469 DI::l10n()->t('Error: JSON PHP module required but not installed.'),
472 $returnVal = $returnVal ? $status : false;
474 $status = $this->checkFunction('finfo_open',
475 DI::l10n()->t('File Information PHP module'),
476 DI::l10n()->t('Error: File Information PHP module required but not installed.'),
479 $returnVal = $returnVal ? $status : false;
485 * "config/local.config.php" - Check
487 * Checks if it's possible to create the "config/local.config.php"
489 * @return bool false if something required failed
491 public function checkLocalIni()
495 if ((file_exists('config/local.config.php') && !is_writable('config/local.config.php')) ||
496 (!file_exists('config/local.config.php') && !is_writable('.'))) {
499 $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;
500 $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;
501 $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;
502 $help .= DI::l10n()->t('You can alternatively skip this procedure and perform a manual installation. Please see the file "INSTALL.txt" for instructions.') . EOL;
505 $this->addCheck(DI::l10n()->t('config/local.config.php is writable'), $status, false, $help);
507 // Local INI File is not required
512 * Smarty3 Template Check
514 * Checks, if the directory of Smarty3 is writable
516 * @return bool false if something required failed
518 public function checkSmarty3()
522 if (!is_writable('view/smarty3')) {
525 $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;
526 $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;
527 $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;
528 $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;
531 $this->addCheck(DI::l10n()->t('view/smarty3 is writable'), $status, true, $help);
537 * ".htaccess" - Check
539 * Checks, if "url_rewrite" is enabled in the ".htaccess" file
541 * @param string $baseurl The baseurl of the app
542 * @return bool false if something required failed
543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
545 public function checkHtAccess($baseurl)
550 if (function_exists('curl_init')) {
551 $fetchResult = Network::fetchUrlFull($baseurl . "/install/testrewrite");
553 $url = Strings::normaliseLink($baseurl . "/install/testrewrite");
554 if ($fetchResult->getReturnCode() != 204) {
555 $fetchResult = Network::fetchUrlFull($url);
558 if ($fetchResult->getReturnCode() != 204) {
560 $help = DI::l10n()->t('Url rewrite in .htaccess is not working. Make sure you copied .htaccess-dist to .htaccess.');
562 $error_msg['head'] = DI::l10n()->t('Error message from Curl when fetching');
563 $error_msg['url'] = $fetchResult->getRedirectUrl();
564 $error_msg['msg'] = $fetchResult->getError();
567 $this->addCheck(DI::l10n()->t('Url rewrite is working'), $status, true, $help, $error_msg);
569 // cannot check modrewrite if libcurl is not installed
570 /// @TODO Maybe issue warning here?
579 * Checks, if the imagick module is available
581 * @return bool false if something required failed
583 public function checkImagick()
588 if (class_exists('Imagick')) {
590 $supported = Images::supportedTypes();
591 if (array_key_exists('image/gif', $supported)) {
596 $this->addCheck(DI::l10n()->t('ImageMagick PHP extension is not installed'), $imagick, false, "");
598 $this->addCheck(DI::l10n()->t('ImageMagick PHP extension is installed'), $imagick, false, "");
600 $this->addCheck(DI::l10n()->t('ImageMagick supports GIF'), $gif, false, "");
604 // Imagick is not required
609 * Checking the Database connection and if it is available for the current installation
611 * @param Database $dba
613 * @return bool true if the check was successful, otherwise false
616 public function checkDB(Database $dba)
620 if ($dba->isConnected()) {
621 if (DBStructure::existsTable('user')) {
622 $this->addCheck(DI::l10n()->t('Database already in use.'), false, true, '');
627 $this->addCheck(DI::l10n()->t('Could not connect to database.'), false, true, '');
636 * Setup the default cache for a new installation
638 * @param Cache $configCache The configuration cache
639 * @param string $basePath The determined basepath
641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
643 public function setUpCache(Cache $configCache, $basePath)
645 $configCache->set('config', 'php_path' , $this->getPHPPath());
646 $configCache->set('system', 'basepath' , $basePath);