7 use Detection\MobileDetect;
11 use Friendica\Core\Config\ConfigCache;
12 use Friendica\Core\Config\ConfigCacheLoader;
13 use Friendica\Database\DBA;
14 use Friendica\Factory\ConfigFactory;
15 use Friendica\Network\HTTPException\InternalServerErrorException;
16 use Friendica\Util\BasePath;
17 use Psr\Log\LoggerInterface;
23 * @brief Our main application structure for the life of this page.
25 * Primarily deals with the URL that got us here
26 * and tries to make some sense of it, and
27 * stores our page contents and config storage
28 * and anything else that might need to be passed around
29 * before we spit the page out.
34 public $module_loaded = false;
35 public $module_class = null;
36 public $query_string = '';
47 public $error = false;
53 public $interactive = true;
55 public $is_mobile = false;
56 public $is_tablet = false;
57 public $performance = [];
58 public $callstack = [];
59 public $theme_info = [];
61 // Allow themes to control internal parameters
62 // by changing App values in theme.php
64 public $sourcename = '';
65 public $videowidth = 425;
66 public $videoheight = 350;
67 public $force_max_items = 0;
68 public $theme_events_in_profile = true;
70 public $stylesheets = [];
71 public $footerScripts = [];
74 * @var App\Mode The Mode of the Application
79 * @var string The App base path
84 * @var string The App URL path
89 * @var bool true, if the call is from the Friendica APP, otherwise false
91 private $isFriendicaApp;
94 * @var bool true, if the call is from an backend node (f.e. worker)
99 * @var string The name of the current theme
101 private $currentTheme;
104 * @var bool check if request was an AJAX (xmlhttprequest) request
111 public $mobileDetect;
114 * @var LoggerInterface The current logger of this App
119 * @var ConfigCache The cached config
124 * Returns the current config cache of this node
126 * @return ConfigCache
128 public function getConfig()
130 return $this->config;
134 * The basepath of this app
138 public function getBasePath()
140 return $this->basePath;
144 * Register a stylesheet file path to be included in the <head> tag of every page.
145 * Inclusion is done in App->initHead().
146 * The path can be absolute or relative to the Friendica installation base folder.
150 * @param string $path
151 * @throws InternalServerErrorException
153 public function registerStylesheet($path)
155 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
157 $this->stylesheets[] = trim($url, '/');
161 * Register a javascript file path to be included in the <footer> tag of every page.
162 * Inclusion is done in App->initFooter().
163 * The path can be absolute or relative to the Friendica installation base folder.
167 * @param string $path
168 * @throws InternalServerErrorException
170 public function registerFooterScript($path)
172 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
174 $this->footerScripts[] = trim($url, '/');
183 * @brief App constructor.
185 * @param ConfigCache $config The Cached Config
186 * @param LoggerInterface $logger Logger of this application
187 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
189 * @throws Exception if the Basepath is not usable
191 public function __construct(ConfigCache $config, LoggerInterface $logger, $isBackend = true)
193 $this->config = $config;
194 $this->logger = $logger;
195 $this->basePath = $this->config->get('system', 'basepath');
197 if (!BasePath::isDirectoryUsable($this->basePath, false)) {
198 throw new Exception('Basepath ' . $this->basePath . ' isn\'t usable.');
200 $this->basePath = rtrim($this->basePath, DIRECTORY_SEPARATOR);
202 BaseObject::setApp($this);
204 $this->checkBackend($isBackend);
205 $this->checkFriendicaApp();
207 $this->performance['start'] = microtime(true);
208 $this->performance['database'] = 0;
209 $this->performance['database_write'] = 0;
210 $this->performance['cache'] = 0;
211 $this->performance['cache_write'] = 0;
212 $this->performance['network'] = 0;
213 $this->performance['file'] = 0;
214 $this->performance['rendering'] = 0;
215 $this->performance['parser'] = 0;
216 $this->performance['marktime'] = 0;
217 $this->performance['markstart'] = microtime(true);
219 $this->callstack['database'] = [];
220 $this->callstack['database_write'] = [];
221 $this->callstack['cache'] = [];
222 $this->callstack['cache_write'] = [];
223 $this->callstack['network'] = [];
224 $this->callstack['file'] = [];
225 $this->callstack['rendering'] = [];
226 $this->callstack['parser'] = [];
228 $this->mode = new App\Mode($this->basePath);
234 // This has to be quite large to deal with embedded private photos
235 ini_set('pcre.backtrack_limit', 500000);
237 $this->scheme = 'http';
239 if (!empty($_SERVER['HTTPS']) ||
240 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
241 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
242 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
243 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
244 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
246 $this->scheme = 'https';
249 if (!empty($_SERVER['SERVER_NAME'])) {
250 $this->hostname = $_SERVER['SERVER_NAME'];
252 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
253 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
258 get_include_path() . PATH_SEPARATOR
259 . $this->basePath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
260 . $this->basePath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
263 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
264 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
265 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
266 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
269 // removing trailing / - maybe a nginx problem
270 $this->query_string = ltrim($this->query_string, '/');
272 if (!empty($_GET['pagename'])) {
273 $this->cmd = trim($_GET['pagename'], '/\\');
274 } elseif (!empty($_GET['q'])) {
275 $this->cmd = trim($_GET['q'], '/\\');
279 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
281 // unix style "homedir"
282 if (substr($this->cmd, 0, 1) === '~') {
283 $this->cmd = 'profile/' . substr($this->cmd, 1);
286 // Diaspora style profile url
287 if (substr($this->cmd, 0, 2) === 'u/') {
288 $this->cmd = 'profile/' . substr($this->cmd, 2);
292 * Break the URL path into C style argc/argv style arguments for our
293 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
294 * will be 3 (integer) and $this->argv will contain:
300 * There will always be one argument. If provided a naked domain
301 * URL, $this->argv[0] is set to "home".
304 $this->argv = explode('/', $this->cmd);
305 $this->argc = count($this->argv);
306 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
307 $this->module = str_replace('.', '_', $this->argv[0]);
308 $this->module = str_replace('-', '_', $this->module);
311 $this->argv = ['home'];
312 $this->module = 'home';
315 // Detect mobile devices
316 $mobile_detect = new MobileDetect();
318 $this->mobileDetect = $mobile_detect;
320 $this->is_mobile = $mobile_detect->isMobile();
321 $this->is_tablet = $mobile_detect->isTablet();
323 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
325 // Register template engines
326 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
330 * Returns the Mode of the Application
332 * @return App\Mode The Application Mode
334 * @throws InternalServerErrorException when the mode isn't created
336 public function getMode()
338 if (empty($this->mode)) {
339 throw new InternalServerErrorException('Mode of the Application is not defined');
346 * Returns the Logger of the Application
348 * @return LoggerInterface The Logger
349 * @throws InternalServerErrorException when the logger isn't created
351 public function getLogger()
353 if (empty($this->logger)) {
354 throw new InternalServerErrorException('Logger of the Application is not defined');
357 return $this->logger;
361 * Reloads the whole app instance
363 public function reload()
365 Core\Config::init($this->config);
366 Core\PConfig::init($this->config);
368 $this->loadDatabase();
370 $this->getMode()->determine($this->basePath);
372 $this->determineURLPath();
374 if ($this->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
375 $adapterType = $this->config->get('system', 'config_adapter');
376 $adapter = ConfigFactory::createConfig($adapterType, $this->config);
377 Core\Config::setAdapter($adapter);
378 $adapterP = ConfigFactory::createPConfig($adapterType, $this->config);
379 Core\PConfig::setAdapter($adapterP);
383 // again because DB-config could change the config
384 $this->getMode()->determine($this->basePath);
386 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
387 Core\Hook::loadHooks();
388 $loader = new ConfigCacheLoader($this->basePath);
389 Core\Hook::callAll('load_config', $loader);
390 $this->config->loadConfigArray($loader->loadAddonConfig(), true);
393 $this->loadDefaultTimezone();
397 $this->process_id = Core\System::processID('log');
399 Core\Logger::setLogger($this->logger);
403 * Loads the default timezone
405 * Include support for legacy $default_timezone
407 * @global string $default_timezone
409 private function loadDefaultTimezone()
411 if ($this->config->get('system', 'default_timezone')) {
412 $this->timezone = $this->config->get('system', 'default_timezone');
414 global $default_timezone;
415 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
418 if ($this->timezone) {
419 date_default_timezone_set($this->timezone);
424 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
426 private function determineURLPath()
428 /* Relative script path to the web server root
429 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
431 $relative_script_path = '';
432 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
433 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
434 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
435 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
436 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
438 $this->urlPath = $this->config->get('system', 'urlpath');
440 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
441 * QUERY_STRING gives pagename=module/parameter
443 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
445 if (!empty($relative_script_path)) {
447 if (!empty($_SERVER['QUERY_STRING'])) {
448 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
451 $path = trim($relative_script_path, '/');
454 if ($path && $path != $this->urlPath) {
455 $this->urlPath = $path;
460 public function loadDatabase()
462 if (DBA::connected()) {
466 $db_host = $this->config->get('database', 'hostname');
467 $db_user = $this->config->get('database', 'username');
468 $db_pass = $this->config->get('database', 'password');
469 $db_data = $this->config->get('database', 'database');
470 $charset = $this->config->get('database', 'charset');
472 // Use environment variables for mysql if they are set beforehand
473 if (!empty(getenv('MYSQL_HOST'))
474 && !empty(getenv('MYSQL_USERNAME') || !empty(getenv('MYSQL_USER')))
475 && getenv('MYSQL_PASSWORD') !== false
476 && !empty(getenv('MYSQL_DATABASE')))
478 $db_host = getenv('MYSQL_HOST');
479 if (!empty(getenv('MYSQL_PORT'))) {
480 $db_host .= ':' . getenv('MYSQL_PORT');
482 if (!empty(getenv('MYSQL_USERNAME'))) {
483 $db_user = getenv('MYSQL_USERNAME');
485 $db_user = getenv('MYSQL_USER');
487 $db_pass = (string) getenv('MYSQL_PASSWORD');
488 $db_data = getenv('MYSQL_DATABASE');
491 $stamp1 = microtime(true);
493 if (DBA::connect($this->config, $db_host, $db_user, $db_pass, $db_data, $charset)) {
494 // Loads DB_UPDATE_VERSION constant
495 Database\DBStructure::definition($this->basePath, false);
498 unset($db_host, $db_user, $db_pass, $db_data, $charset);
500 $this->saveTimestamp($stamp1, 'network');
503 public function getScheme()
505 return $this->scheme;
509 * @brief Retrieves the Friendica instance base URL
511 * This function assembles the base URL from multiple parts:
512 * - Protocol is determined either by the request or a combination of
513 * system.ssl_policy and the $ssl parameter.
514 * - Host name is determined either by system.hostname or inferred from request
515 * - Path is inferred from SCRIPT_NAME
517 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
519 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
520 * @return string Friendica server base URL
521 * @throws InternalServerErrorException
523 public function getBaseURL($ssl = false)
525 $scheme = $this->scheme;
527 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
531 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
532 // (and also the login link). Anything seen by an outsider will have it turned off.
534 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
542 if (Core\Config::get('config', 'hostname') != '') {
543 $this->hostname = Core\Config::get('config', 'hostname');
546 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
550 * @brief Initializes the baseurl components
552 * Clears the baseurl cache to prevent inconsistencies
555 * @throws InternalServerErrorException
557 public function setBaseURL($url)
559 $parsed = @parse_url($url);
562 if (!empty($parsed)) {
563 if (!empty($parsed['scheme'])) {
564 $this->scheme = $parsed['scheme'];
567 if (!empty($parsed['host'])) {
568 $hostname = $parsed['host'];
571 if (!empty($parsed['port'])) {
572 $hostname .= ':' . $parsed['port'];
574 if (!empty($parsed['path'])) {
575 $this->urlPath = trim($parsed['path'], '\\/');
578 if (file_exists($this->basePath . '/.htpreconfig.php')) {
579 include $this->basePath . '/.htpreconfig.php';
582 if (Core\Config::get('config', 'hostname') != '') {
583 $this->hostname = Core\Config::get('config', 'hostname');
586 if (!isset($this->hostname) || ($this->hostname == '')) {
587 $this->hostname = $hostname;
592 public function getHostName()
594 if (Core\Config::get('config', 'hostname') != '') {
595 $this->hostname = Core\Config::get('config', 'hostname');
598 return $this->hostname;
601 public function getURLPath()
603 return $this->urlPath;
607 * Initializes App->page['htmlhead'].
612 * - Registered stylesheets (through App->registerStylesheet())
613 * - Infinite scroll data
614 * - head.tpl template
616 public function initHead()
618 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
620 // If the update is 'deactivated' set it to the highest integer number (~24 days)
622 $interval = 2147483647;
625 if ($interval < 10000) {
629 // compose the page title from the sitename and the
630 // current module called
631 if (!$this->module == '') {
632 $this->page['title'] = $this->config->get('config', 'sitename') . ' (' . $this->module . ')';
634 $this->page['title'] = $this->config->get('config', 'sitename');
637 if (!empty(Core\Renderer::$theme['stylesheet'])) {
638 $stylesheet = Core\Renderer::$theme['stylesheet'];
640 $stylesheet = $this->getCurrentThemeStylesheetPath();
643 $this->registerStylesheet($stylesheet);
645 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
646 if ($shortcut_icon == '') {
647 $shortcut_icon = 'images/friendica-32.png';
650 $touch_icon = Core\Config::get('system', 'touch_icon');
651 if ($touch_icon == '') {
652 $touch_icon = 'images/friendica-128.png';
655 Core\Hook::callAll('head', $this->page['htmlhead']);
657 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
658 /* put the head template at the beginning of page['htmlhead']
659 * since the code added by the modules frequently depends on it
662 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
663 '$baseurl' => $this->getBaseURL(),
664 '$local_user' => local_user(),
665 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
666 '$delitem' => Core\L10n::t('Delete this item?'),
667 '$showmore' => Core\L10n::t('show more'),
668 '$showfewer' => Core\L10n::t('show fewer'),
669 '$update_interval' => $interval,
670 '$shortcut_icon' => $shortcut_icon,
671 '$touch_icon' => $touch_icon,
672 '$block_public' => intval(Core\Config::get('system', 'block_public')),
673 '$stylesheets' => $this->stylesheets,
674 ]) . $this->page['htmlhead'];
678 * Initializes App->page['footer'].
681 * - Javascript homebase
682 * - Mobile toggle link
683 * - Registered footer scripts (through App->registerFooterScript())
684 * - footer.tpl template
686 public function initFooter()
688 // If you're just visiting, let javascript take you home
689 if (!empty($_SESSION['visitor_home'])) {
690 $homebase = $_SESSION['visitor_home'];
691 } elseif (local_user()) {
692 $homebase = 'profile/' . $this->user['nickname'];
695 if (isset($homebase)) {
696 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
700 * Add a "toggle mobile" link if we're using a mobile device
702 if ($this->is_mobile || $this->is_tablet) {
703 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
704 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
706 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
708 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
709 '$toggle_link' => $link,
710 '$toggle_text' => Core\L10n::t('toggle mobile')
714 Core\Hook::callAll('footer', $this->page['footer']);
716 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
717 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
718 '$baseurl' => $this->getBaseURL(),
719 '$footerScripts' => $this->footerScripts,
720 ]) . $this->page['footer'];
724 * @brief Removes the base url from an url. This avoids some mixed content problems.
726 * @param string $origURL
728 * @return string The cleaned url
729 * @throws InternalServerErrorException
731 public function removeBaseURL($origURL)
733 // Remove the hostname from the url if it is an internal link
734 $nurl = Util\Strings::normaliseLink($origURL);
735 $base = Util\Strings::normaliseLink($this->getBaseURL());
736 $url = str_replace($base . '/', '', $nurl);
738 // if it is an external link return the orignal value
739 if ($url == Util\Strings::normaliseLink($origURL)) {
747 * Saves a timestamp for a value - f.e. a call
748 * Necessary for profiling Friendica
750 * @param int $timestamp the Timestamp
751 * @param string $value A value to profile
753 public function saveTimestamp($timestamp, $value)
755 $profiler = $this->config->get('system', 'profiler');
757 if (!isset($profiler) || !$profiler) {
761 $duration = (float) (microtime(true) - $timestamp);
763 if (!isset($this->performance[$value])) {
764 // Prevent ugly E_NOTICE
765 $this->performance[$value] = 0;
768 $this->performance[$value] += (float) $duration;
769 $this->performance['marktime'] += (float) $duration;
771 $callstack = Core\System::callstack();
773 if (!isset($this->callstack[$value][$callstack])) {
774 // Prevent ugly E_NOTICE
775 $this->callstack[$value][$callstack] = 0;
778 $this->callstack[$value][$callstack] += (float) $duration;
782 * Returns the current UserAgent as a String
784 * @return string the UserAgent as a String
785 * @throws InternalServerErrorException
787 public function getUserAgent()
790 FRIENDICA_PLATFORM . " '" .
791 FRIENDICA_CODENAME . "' " .
792 FRIENDICA_VERSION . '-' .
793 DB_UPDATE_VERSION . '; ' .
798 * Checks, if the call is from the Friendica App
801 * The friendica client has problems with the GUID in the notify. this is some workaround
803 private function checkFriendicaApp()
806 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
810 * Is the call via the Friendica app? (not a "normale" call)
812 * @return bool true if it's from the Friendica app
814 public function isFriendicaApp()
816 return $this->isFriendicaApp;
820 * @brief Checks if the site is called via a backend process
822 * This isn't a perfect solution. But we need this check very early.
823 * So we cannot wait until the modules are loaded.
825 * @param string $backend true, if the backend flag was set during App initialization
828 private function checkBackend($backend) {
851 // Check if current module is in backend or backend flag is set
852 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
856 * Returns true, if the call is from a backend node (f.e. from a worker)
858 * @return bool Is it a known backend?
860 public function isBackend()
862 return $this->isBackend;
866 * @brief Checks if the maximum number of database processes is reached
868 * @return bool Is the limit reached?
870 public function isMaxProcessesReached()
872 // Deactivated, needs more investigating if this check really makes sense
876 * Commented out to suppress static analyzer issues
878 if ($this->is_backend()) {
879 $process = 'backend';
880 $max_processes = Core\Config::get('system', 'max_processes_backend');
881 if (intval($max_processes) == 0) {
885 $process = 'frontend';
886 $max_processes = Core\Config::get('system', 'max_processes_frontend');
887 if (intval($max_processes) == 0) {
892 $processlist = DBA::processlist();
893 if ($processlist['list'] != '') {
894 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
896 if ($processlist['amount'] > $max_processes) {
897 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
906 * @brief Checks if the minimal memory is reached
908 * @return bool Is the memory limit reached?
909 * @throws InternalServerErrorException
911 public function isMinMemoryReached()
913 $min_memory = Core\Config::get('system', 'min_memory', 0);
914 if ($min_memory == 0) {
918 if (!is_readable('/proc/meminfo')) {
922 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
925 foreach ($memdata as $line) {
926 $data = explode(':', $line);
927 if (count($data) != 2) {
930 list($key, $val) = $data;
931 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
932 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
935 if (!isset($meminfo['MemFree'])) {
939 $free = $meminfo['MemFree'];
941 $reached = ($free < $min_memory);
944 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
951 * @brief Checks if the maximum load is reached
953 * @return bool Is the load reached?
954 * @throws InternalServerErrorException
956 public function isMaxLoadReached()
958 if ($this->isBackend()) {
959 $process = 'backend';
960 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
961 if ($maxsysload < 1) {
965 $process = 'frontend';
966 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
967 if ($maxsysload < 1) {
972 $load = Core\System::currentLoad();
974 if (intval($load) > $maxsysload) {
975 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
983 * Executes a child process with 'proc_open'
985 * @param string $command The command to execute
986 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
987 * @throws InternalServerErrorException
989 public function proc_run($command, $args)
991 if (!function_exists('proc_open')) {
995 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
997 foreach ($args as $key => $value) {
998 if (!is_null($value) && is_bool($value) && !$value) {
1002 $cmdline .= ' --' . $key;
1003 if (!is_null($value) && !is_bool($value)) {
1004 $cmdline .= ' ' . $value;
1008 if ($this->isMinMemoryReached()) {
1012 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1013 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
1015 $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
1017 if (!is_resource($resource)) {
1018 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1021 proc_close($resource);
1025 * Generates the site's default sender email address
1028 * @throws InternalServerErrorException
1030 public function getSenderEmailAddress()
1032 $sender_email = Core\Config::get('config', 'sender_email');
1033 if (empty($sender_email)) {
1034 $hostname = $this->getHostName();
1035 if (strpos($hostname, ':')) {
1036 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1039 $sender_email = 'noreply@' . $hostname;
1042 return $sender_email;
1046 * Returns the current theme name.
1048 * @return string the name of the current theme
1049 * @throws InternalServerErrorException
1051 public function getCurrentTheme()
1053 if ($this->getMode()->isInstall()) {
1057 if (!$this->currentTheme) {
1058 $this->computeCurrentTheme();
1061 return $this->currentTheme;
1064 public function setCurrentTheme($theme)
1066 $this->currentTheme = $theme;
1070 * Computes the current theme name based on the node settings, the user settings and the device type
1074 private function computeCurrentTheme()
1076 $system_theme = Core\Config::get('system', 'theme');
1077 if (!$system_theme) {
1078 throw new Exception(Core\L10n::t('No system theme config value set.'));
1082 $this->currentTheme = $system_theme;
1084 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1087 // Find the theme that belongs to the user whose stuff we are looking at
1088 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1089 // Allow folks to override user themes and always use their own on their own site.
1090 // This works only if the user is on the same server
1091 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1092 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1093 $page_theme = $user['theme'];
1097 $user_theme = Core\Session::get('theme', $system_theme);
1099 // Specific mobile theme override
1100 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1101 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1102 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1104 // --- means same mobile theme as desktop
1105 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1106 $user_theme = $user_mobile_theme;
1111 $theme_name = $page_theme;
1113 $theme_name = $user_theme;
1117 && in_array($theme_name, $allowed_themes)
1118 && (file_exists('view/theme/' . $theme_name . '/style.css')
1119 || file_exists('view/theme/' . $theme_name . '/style.php'))
1121 $this->currentTheme = $theme_name;
1126 * @brief Return full URL to theme which is currently in effect.
1128 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1131 * @throws InternalServerErrorException
1133 public function getCurrentThemeStylesheetPath()
1135 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1139 * Check if request was an AJAX (xmlhttprequest) request.
1141 * @return boolean true if it was an AJAX request
1143 public function isAjax()
1145 return $this->isAjax;
1149 * Returns the value of a argv key
1150 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1152 * @param int $position the position of the argument
1153 * @param mixed $default the default value if not found
1155 * @return mixed returns the value of the argument
1157 public function getArgumentValue($position, $default = '')
1159 if (array_key_exists($position, $this->argv)) {
1160 return $this->argv[$position];
1167 * Sets the base url for use in cmdline programs which don't have
1168 * $_SERVER variables
1170 public function checkURL()
1172 $url = Core\Config::get('system', 'url');
1174 // if the url isn't set or the stored url is radically different
1175 // than the currently visited url, store the current value accordingly.
1176 // "Radically different" ignores common variations such as http vs https
1177 // and www.example.com vs example.com.
1178 // We will only change the url to an ip address if there is no existing setting
1180 if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1181 Core\Config::set('system', 'url', $this->getBaseURL());
1186 * Frontend App script
1188 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1189 * request and a representation of the response.
1191 * This probably should change to limit the size of this monster method.
1193 public function runFrontend()
1195 // Missing DB connection: ERROR
1196 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1197 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1200 // Max Load Average reached: ERROR
1201 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1202 header('Retry-After: 120');
1203 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1205 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1208 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1209 Core\System::httpExit(404);
1212 if (!$this->getMode()->isInstall()) {
1213 // Force SSL redirection
1214 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1215 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1216 && strpos($this->getBaseURL(), 'https://') === 0
1217 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1218 header('HTTP/1.1 302 Moved Temporarily');
1219 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1223 Core\Session::init();
1224 Core\Hook::callAll('init_1');
1227 // Exclude the backend processes from the session management
1228 if (!$this->isBackend()) {
1229 $stamp1 = microtime(true);
1231 $this->saveTimestamp($stamp1, 'parser');
1232 Core\L10n::setSessionVariable();
1233 Core\L10n::setLangFromSession();
1236 Core\Worker::executeIfIdle();
1240 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1241 $this->query_string = Model\Profile::stripZrls($this->query_string);
1242 if (!local_user()) {
1243 // Only continue when the given profile link seems valid
1244 // Valid profile links contain a path with "/profile/" and no query parameters
1245 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1246 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1247 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1248 $_SESSION['my_url'] = $_GET['zrl'];
1249 $_SESSION['authenticated'] = 0;
1251 Model\Profile::zrlInit($this);
1253 // Someone came with an invalid parameter, maybe as a DDoS attempt
1254 // We simply stop processing here
1255 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1256 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1261 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1262 $token = $_GET['owt'];
1263 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1264 Model\Profile::openWebAuthInit($token);
1267 Module\Login::sessionAuth();
1269 if (empty($_SESSION['authenticated'])) {
1270 header('X-Account-Management-Status: none');
1273 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1274 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1275 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1278 * check_config() is responsible for running update scripts. These automatically
1279 * update the DB schema whenever we push a new one out. It also checks to see if
1280 * any addons have been added or removed and reacts accordingly.
1283 // in install mode, any url loads install module
1284 // but we need "view" module for stylesheet
1285 if ($this->getMode()->isInstall() && $this->module != 'view') {
1286 $this->module = 'install';
1287 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1288 $this->module = 'maintenance';
1291 Core\Update::check($this->basePath, false);
1292 Core\Addon::loadAddons();
1293 Core\Hook::loadHooks();
1304 'right_aside' => '',
1309 if (strlen($this->module)) {
1310 // Compatibility with the Android Diaspora client
1311 if ($this->module == 'stream') {
1312 $this->internalRedirect('network?f=&order=post');
1315 if ($this->module == 'conversations') {
1316 $this->internalRedirect('message');
1319 if ($this->module == 'commented') {
1320 $this->internalRedirect('network?f=&order=comment');
1323 if ($this->module == 'liked') {
1324 $this->internalRedirect('network?f=&order=comment');
1327 if ($this->module == 'activity') {
1328 $this->internalRedirect('network/?f=&conv=1');
1331 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1332 $this->internalRedirect('bookmarklet');
1335 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1336 $this->internalRedirect('settings');
1339 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1340 $this->internalRedirect('search');
1343 // Compatibility with the Firefox App
1344 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1345 $this->module = "login";
1348 $privateapps = Core\Config::get('config', 'private_addons', false);
1349 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1350 //Check if module is an app and if public access to apps is allowed or not
1351 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1352 info(Core\L10n::t("You must be logged in to use addons. "));
1354 include_once "addon/{$this->module}/{$this->module}.php";
1355 if (function_exists($this->module . '_module')) {
1356 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1357 $this->module_class = 'Friendica\\LegacyModule';
1358 $this->module_loaded = true;
1363 // Controller class routing
1364 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1365 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1366 $this->module_loaded = true;
1369 /* If not, next look for a 'standard' program module in the 'mod' directory
1370 * We emulate a Module class through the LegacyModule class
1372 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1373 LegacyModule::setModuleFile("mod/{$this->module}.php");
1374 $this->module_class = 'Friendica\\LegacyModule';
1375 $this->module_loaded = true;
1378 /* The URL provided does not resolve to a valid module.
1380 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1381 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1382 * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
1383 * this will often succeed and eventually do the right thing.
1385 * Otherwise we are going to emit a 404 not found.
1387 if (! $this->module_loaded) {
1388 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1389 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1393 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1394 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1395 $this->internalRedirect($_SERVER['REQUEST_URI']);
1398 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1400 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1401 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1402 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1403 '$message' => Core\L10n::t('Page not found.')
1410 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1411 if ($this->module_loaded) {
1412 $this->page['page_title'] = $this->module;
1415 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1417 call_user_func([$this->module_class, 'init']);
1419 // "rawContent" is especially meant for technical endpoints.
1420 // This endpoint doesn't need any theme initialization or other comparable stuff.
1421 if (!$this->error) {
1422 call_user_func([$this->module_class, 'rawContent']);
1426 // Load current theme info after module has been initialized as theme could have been set in module
1427 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1428 if (file_exists($theme_info_file)) {
1429 require_once $theme_info_file;
1432 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1433 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1437 if ($this->module_loaded) {
1438 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1439 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1440 call_user_func([$this->module_class, 'post']);
1443 if (! $this->error) {
1444 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1445 call_user_func([$this->module_class, 'afterpost']);
1448 if (! $this->error) {
1449 $arr = ['content' => $content];
1450 Core\Hook::callAll($this->module . '_mod_content', $arr);
1451 $content = $arr['content'];
1452 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1453 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1454 $content .= $arr['content'];
1458 // initialise content region
1459 if ($this->getMode()->isNormal()) {
1460 Core\Hook::callAll('page_content_top', $this->page['content']);
1463 $this->page['content'] .= $content;
1465 /* Create the page head after setting the language
1466 * and getting any auth credentials.
1468 * Moved initHead() and initFooter() to after
1469 * all the module functions have executed so that all
1470 * theme choices made by the modules can take effect.
1474 /* Build the page ending -- this is stuff that goes right before
1475 * the closing </body> tag
1477 $this->initFooter();
1479 /* now that we've been through the module content, see if the page reported
1480 * a permission problem and if so, a 403 response would seem to be in order.
1482 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1483 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1486 // Report anything which needs to be communicated in the notification area (before the main body)
1487 Core\Hook::callAll('page_end', $this->page['content']);
1489 // Add the navigation (menu) template
1490 if ($this->module != 'install' && $this->module != 'maintenance') {
1491 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1492 $this->page['nav'] = Content\Nav::build($this);
1495 // Build the page - now that we have all the components
1496 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1497 $doc = new DOMDocument();
1499 $target = new DOMDocument();
1500 $target->loadXML("<root></root>");
1502 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1504 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1505 @$doc->loadHTML($content);
1507 $xpath = new DOMXPath($doc);
1509 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1511 foreach ($list as $item) {
1512 $item = $target->importNode($item, true);
1514 // And then append it to the target
1515 $target->documentElement->appendChild($item);
1518 if ($_GET["mode"] == "raw") {
1519 header("Content-type: text/html; charset=utf-8");
1521 echo substr($target->saveHTML(), 6, -8);
1527 $page = $this->page;
1528 $profile = $this->profile;
1530 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1531 header("Content-type: text/html; charset=utf-8");
1533 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1534 header("Strict-Transport-Security: max-age=31536000");
1537 // Some security stuff
1538 header('X-Content-Type-Options: nosniff');
1539 header('X-XSS-Protection: 1; mode=block');
1540 header('X-Permitted-Cross-Domain-Policies: none');
1541 header('X-Frame-Options: sameorigin');
1543 // Things like embedded OSM maps don't work, when this is enabled
1544 // header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https: data:; media-src 'self' https:; child-src 'self' https:; object-src 'none'");
1546 /* We use $_GET["mode"] for special page templates. So we will check if we have
1547 * to load another page template than the default one.
1548 * The page templates are located in /view/php/ or in the theme directory.
1550 if (isset($_GET["mode"])) {
1551 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1554 // If there is no page template use the default page template
1555 if (empty($template)) {
1556 $template = Core\Theme::getPathForFile("default.php");
1559 // Theme templates expect $a as an App instance
1562 // Used as is in view/php/default.php
1563 $lang = Core\L10n::getCurrentLang();
1565 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1566 require_once $template;
1570 * Redirects to another module relative to the current Friendica base.
1571 * If you want to redirect to a external URL, use System::externalRedirectTo()
1573 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1574 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1576 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1578 public function internalRedirect($toUrl = '', $ssl = false)
1580 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1581 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1584 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1585 Core\System::externalRedirect($redirectTo);
1589 * Automatically redirects to relative or absolute URL
1590 * Should only be used if it isn't clear if the URL is either internal or external
1592 * @param string $toUrl The target URL
1593 * @throws InternalServerErrorException
1595 public function redirect($toUrl)
1597 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1598 Core\System::externalRedirect($toUrl);
1600 $this->internalRedirect($toUrl);