7 use Detection\MobileDetect;
11 use Friendica\Core\Config\Cache\ConfigCacheLoader;
12 use Friendica\Core\Config\Cache\IConfigCache;
13 use Friendica\Core\Config\Configuration;
14 use Friendica\Database\DBA;
15 use Friendica\Network\HTTPException\InternalServerErrorException;
16 use Friendica\Util\Profiler;
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 $theme_info = [];
59 // Allow themes to control internal parameters
60 // by changing App values in theme.php
62 public $sourcename = '';
63 public $videowidth = 425;
64 public $videoheight = 350;
65 public $force_max_items = 0;
66 public $theme_events_in_profile = true;
68 public $stylesheets = [];
69 public $footerScripts = [];
72 * @var App\Mode The Mode of the Application
77 * @var string The App base path
82 * @var string The App URL path
87 * @var bool true, if the call is from the Friendica APP, otherwise false
89 private $isFriendicaApp;
92 * @var bool true, if the call is from an backend node (f.e. worker)
97 * @var string The name of the current theme
99 private $currentTheme;
102 * @var bool check if request was an AJAX (xmlhttprequest) request
109 public $mobileDetect;
112 * @var Configuration The config
117 * @var LoggerInterface The logger
122 * @var Profiler The profiler of this app
127 * Returns the current config cache of this node
129 * @return IConfigCache
131 public function getConfigCache()
133 return $this->config->getCache();
137 * The basepath of this app
141 public function getBasePath()
143 return $this->basePath;
147 * The Logger of this app
149 * @return LoggerInterface
151 public function getLogger()
153 return $this->logger;
157 * The profiler of this app
161 public function getProfiler()
163 return $this->profiler;
167 * Register a stylesheet file path to be included in the <head> tag of every page.
168 * Inclusion is done in App->initHead().
169 * The path can be absolute or relative to the Friendica installation base folder.
173 * @param string $path
174 * @throws InternalServerErrorException
176 public function registerStylesheet($path)
178 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
180 $this->stylesheets[] = trim($url, '/');
184 * Register a javascript file path to be included in the <footer> tag of every page.
185 * Inclusion is done in App->initFooter().
186 * The path can be absolute or relative to the Friendica installation base folder.
190 * @param string $path
191 * @throws InternalServerErrorException
193 public function registerFooterScript($path)
195 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
197 $this->footerScripts[] = trim($url, '/');
206 * @brief App constructor.
208 * @param Configuration $config The Configuration
209 * @param LoggerInterface $logger The current app logger
210 * @param Profiler $profiler The profiler of this application
211 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
213 * @throws Exception if the Basepath is not usable
215 public function __construct(Configuration $config, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
217 BaseObject::setApp($this);
219 $this->logger = $logger;
220 $this->config = $config;
221 $this->profiler = $profiler;
222 $this->basePath = $this->config->getCache()->get('system', 'basepath');
224 if (!Core\System::isDirectoryUsable($this->basePath, false)) {
225 throw new Exception('Basepath \'' . $this->basePath . '\' isn\'t usable.');
227 $this->basePath = rtrim($this->basePath, DIRECTORY_SEPARATOR);
229 $this->checkBackend($isBackend);
230 $this->checkFriendicaApp();
232 $this->profiler->reset();
234 $this->mode = new App\Mode($this->basePath);
240 // This has to be quite large to deal with embedded private photos
241 ini_set('pcre.backtrack_limit', 500000);
243 $this->scheme = 'http';
245 if (!empty($_SERVER['HTTPS']) ||
246 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
247 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
248 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
249 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
250 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
252 $this->scheme = 'https';
255 if (!empty($_SERVER['SERVER_NAME'])) {
256 $this->hostname = $_SERVER['SERVER_NAME'];
258 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
259 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
264 get_include_path() . PATH_SEPARATOR
265 . $this->basePath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
266 . $this->basePath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
269 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
270 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
271 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
272 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
275 // removing trailing / - maybe a nginx problem
276 $this->query_string = ltrim($this->query_string, '/');
278 if (!empty($_GET['pagename'])) {
279 $this->cmd = trim($_GET['pagename'], '/\\');
280 } elseif (!empty($_GET['q'])) {
281 $this->cmd = trim($_GET['q'], '/\\');
285 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
287 // unix style "homedir"
288 if (substr($this->cmd, 0, 1) === '~') {
289 $this->cmd = 'profile/' . substr($this->cmd, 1);
292 // Diaspora style profile url
293 if (substr($this->cmd, 0, 2) === 'u/') {
294 $this->cmd = 'profile/' . substr($this->cmd, 2);
298 * Break the URL path into C style argc/argv style arguments for our
299 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
300 * will be 3 (integer) and $this->argv will contain:
306 * There will always be one argument. If provided a naked domain
307 * URL, $this->argv[0] is set to "home".
310 $this->argv = explode('/', $this->cmd);
311 $this->argc = count($this->argv);
312 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
313 $this->module = str_replace('.', '_', $this->argv[0]);
314 $this->module = str_replace('-', '_', $this->module);
317 $this->argv = ['home'];
318 $this->module = 'home';
321 // Detect mobile devices
322 $mobile_detect = new MobileDetect();
324 $this->mobileDetect = $mobile_detect;
326 $this->is_mobile = $mobile_detect->isMobile();
327 $this->is_tablet = $mobile_detect->isTablet();
329 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
331 // Register template engines
332 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
336 * Returns the Mode of the Application
338 * @return App\Mode The Application Mode
340 * @throws InternalServerErrorException when the mode isn't created
342 public function getMode()
344 if (empty($this->mode)) {
345 throw new InternalServerErrorException('Mode of the Application is not defined');
352 * Reloads the whole app instance
354 public function reload()
356 $this->determineURLPath();
358 $this->getMode()->determine($this->basePath);
360 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
361 Core\Hook::loadHooks();
362 $loader = new ConfigCacheLoader($this->basePath);
363 Core\Hook::callAll('load_config', $loader);
364 $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
367 $this->loadDefaultTimezone();
371 $this->process_id = Core\System::processID('log');
375 * Loads the default timezone
377 * Include support for legacy $default_timezone
379 * @global string $default_timezone
381 private function loadDefaultTimezone()
383 if ($this->config->get('system', 'default_timezone')) {
384 $this->timezone = $this->config->get('system', 'default_timezone');
386 global $default_timezone;
387 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
390 if ($this->timezone) {
391 date_default_timezone_set($this->timezone);
396 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
398 private function determineURLPath()
400 /* Relative script path to the web server root
401 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
403 $relative_script_path = '';
404 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
405 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
406 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
407 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
408 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
410 $this->urlPath = $this->config->get('system', 'urlpath');
412 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
413 * QUERY_STRING gives pagename=module/parameter
415 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
417 if (!empty($relative_script_path)) {
419 if (!empty($_SERVER['QUERY_STRING'])) {
420 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
423 $path = trim($relative_script_path, '/');
426 if ($path && $path != $this->urlPath) {
427 $this->urlPath = $path;
432 public function getScheme()
434 return $this->scheme;
438 * @brief Retrieves the Friendica instance base URL
440 * This function assembles the base URL from multiple parts:
441 * - Protocol is determined either by the request or a combination of
442 * system.ssl_policy and the $ssl parameter.
443 * - Host name is determined either by system.hostname or inferred from request
444 * - Path is inferred from SCRIPT_NAME
446 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
448 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
449 * @return string Friendica server base URL
450 * @throws InternalServerErrorException
452 public function getBaseURL($ssl = false)
454 $scheme = $this->scheme;
456 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
460 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
461 // (and also the login link). Anything seen by an outsider will have it turned off.
463 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
471 if (Core\Config::get('config', 'hostname') != '') {
472 $this->hostname = Core\Config::get('config', 'hostname');
475 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
479 * @brief Initializes the baseurl components
481 * Clears the baseurl cache to prevent inconsistencies
484 * @throws InternalServerErrorException
486 public function setBaseURL($url)
488 $parsed = @parse_url($url);
491 if (!empty($parsed)) {
492 if (!empty($parsed['scheme'])) {
493 $this->scheme = $parsed['scheme'];
496 if (!empty($parsed['host'])) {
497 $hostname = $parsed['host'];
500 if (!empty($parsed['port'])) {
501 $hostname .= ':' . $parsed['port'];
503 if (!empty($parsed['path'])) {
504 $this->urlPath = trim($parsed['path'], '\\/');
507 if (file_exists($this->basePath . '/.htpreconfig.php')) {
508 include $this->basePath . '/.htpreconfig.php';
511 if (Core\Config::get('config', 'hostname') != '') {
512 $this->hostname = Core\Config::get('config', 'hostname');
515 if (!isset($this->hostname) || ($this->hostname == '')) {
516 $this->hostname = $hostname;
521 public function getHostName()
523 if (Core\Config::get('config', 'hostname') != '') {
524 $this->hostname = Core\Config::get('config', 'hostname');
527 return $this->hostname;
530 public function getURLPath()
532 return $this->urlPath;
536 * Initializes App->page['htmlhead'].
541 * - Registered stylesheets (through App->registerStylesheet())
542 * - Infinite scroll data
543 * - head.tpl template
545 public function initHead()
547 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
549 // If the update is 'deactivated' set it to the highest integer number (~24 days)
551 $interval = 2147483647;
554 if ($interval < 10000) {
558 // compose the page title from the sitename and the
559 // current module called
560 if (!$this->module == '') {
561 $this->page['title'] = $this->config->get('config', 'sitename') . ' (' . $this->module . ')';
563 $this->page['title'] = $this->config->get('config', 'sitename');
566 if (!empty(Core\Renderer::$theme['stylesheet'])) {
567 $stylesheet = Core\Renderer::$theme['stylesheet'];
569 $stylesheet = $this->getCurrentThemeStylesheetPath();
572 $this->registerStylesheet($stylesheet);
574 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
575 if ($shortcut_icon == '') {
576 $shortcut_icon = 'images/friendica-32.png';
579 $touch_icon = Core\Config::get('system', 'touch_icon');
580 if ($touch_icon == '') {
581 $touch_icon = 'images/friendica-128.png';
584 Core\Hook::callAll('head', $this->page['htmlhead']);
586 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
587 /* put the head template at the beginning of page['htmlhead']
588 * since the code added by the modules frequently depends on it
591 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
592 '$baseurl' => $this->getBaseURL(),
593 '$local_user' => local_user(),
594 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
595 '$delitem' => Core\L10n::t('Delete this item?'),
596 '$update_interval' => $interval,
597 '$shortcut_icon' => $shortcut_icon,
598 '$touch_icon' => $touch_icon,
599 '$block_public' => intval(Core\Config::get('system', 'block_public')),
600 '$stylesheets' => $this->stylesheets,
601 ]) . $this->page['htmlhead'];
605 * Initializes App->page['footer'].
608 * - Javascript homebase
609 * - Mobile toggle link
610 * - Registered footer scripts (through App->registerFooterScript())
611 * - footer.tpl template
613 public function initFooter()
615 // If you're just visiting, let javascript take you home
616 if (!empty($_SESSION['visitor_home'])) {
617 $homebase = $_SESSION['visitor_home'];
618 } elseif (local_user()) {
619 $homebase = 'profile/' . $this->user['nickname'];
622 if (isset($homebase)) {
623 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
627 * Add a "toggle mobile" link if we're using a mobile device
629 if ($this->is_mobile || $this->is_tablet) {
630 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
631 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
633 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
635 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
636 '$toggle_link' => $link,
637 '$toggle_text' => Core\L10n::t('toggle mobile')
641 Core\Hook::callAll('footer', $this->page['footer']);
643 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
644 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
645 '$baseurl' => $this->getBaseURL(),
646 '$footerScripts' => $this->footerScripts,
647 ]) . $this->page['footer'];
651 * @brief Removes the base url from an url. This avoids some mixed content problems.
653 * @param string $origURL
655 * @return string The cleaned url
656 * @throws InternalServerErrorException
658 public function removeBaseURL($origURL)
660 // Remove the hostname from the url if it is an internal link
661 $nurl = Util\Strings::normaliseLink($origURL);
662 $base = Util\Strings::normaliseLink($this->getBaseURL());
663 $url = str_replace($base . '/', '', $nurl);
665 // if it is an external link return the orignal value
666 if ($url == Util\Strings::normaliseLink($origURL)) {
674 * Returns the current UserAgent as a String
676 * @return string the UserAgent as a String
677 * @throws InternalServerErrorException
679 public function getUserAgent()
682 FRIENDICA_PLATFORM . " '" .
683 FRIENDICA_CODENAME . "' " .
684 FRIENDICA_VERSION . '-' .
685 DB_UPDATE_VERSION . '; ' .
690 * Checks, if the call is from the Friendica App
693 * The friendica client has problems with the GUID in the notify. this is some workaround
695 private function checkFriendicaApp()
698 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
702 * Is the call via the Friendica app? (not a "normale" call)
704 * @return bool true if it's from the Friendica app
706 public function isFriendicaApp()
708 return $this->isFriendicaApp;
712 * @brief Checks if the site is called via a backend process
714 * This isn't a perfect solution. But we need this check very early.
715 * So we cannot wait until the modules are loaded.
717 * @param string $backend true, if the backend flag was set during App initialization
720 private function checkBackend($backend) {
743 // Check if current module is in backend or backend flag is set
744 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
748 * Returns true, if the call is from a backend node (f.e. from a worker)
750 * @return bool Is it a known backend?
752 public function isBackend()
754 return $this->isBackend;
758 * @brief Checks if the maximum number of database processes is reached
760 * @return bool Is the limit reached?
762 public function isMaxProcessesReached()
764 // Deactivated, needs more investigating if this check really makes sense
768 * Commented out to suppress static analyzer issues
770 if ($this->is_backend()) {
771 $process = 'backend';
772 $max_processes = Core\Config::get('system', 'max_processes_backend');
773 if (intval($max_processes) == 0) {
777 $process = 'frontend';
778 $max_processes = Core\Config::get('system', 'max_processes_frontend');
779 if (intval($max_processes) == 0) {
784 $processlist = DBA::processlist();
785 if ($processlist['list'] != '') {
786 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
788 if ($processlist['amount'] > $max_processes) {
789 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
798 * @brief Checks if the minimal memory is reached
800 * @return bool Is the memory limit reached?
801 * @throws InternalServerErrorException
803 public function isMinMemoryReached()
805 $min_memory = Core\Config::get('system', 'min_memory', 0);
806 if ($min_memory == 0) {
810 if (!is_readable('/proc/meminfo')) {
814 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
817 foreach ($memdata as $line) {
818 $data = explode(':', $line);
819 if (count($data) != 2) {
822 list($key, $val) = $data;
823 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
824 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
827 if (!isset($meminfo['MemFree'])) {
831 $free = $meminfo['MemFree'];
833 $reached = ($free < $min_memory);
836 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
843 * @brief Checks if the maximum load is reached
845 * @return bool Is the load reached?
846 * @throws InternalServerErrorException
848 public function isMaxLoadReached()
850 if ($this->isBackend()) {
851 $process = 'backend';
852 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
853 if ($maxsysload < 1) {
857 $process = 'frontend';
858 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
859 if ($maxsysload < 1) {
864 $load = Core\System::currentLoad();
866 if (intval($load) > $maxsysload) {
867 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
875 * Executes a child process with 'proc_open'
877 * @param string $command The command to execute
878 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
879 * @throws InternalServerErrorException
881 public function proc_run($command, $args)
883 if (!function_exists('proc_open')) {
887 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
889 foreach ($args as $key => $value) {
890 if (!is_null($value) && is_bool($value) && !$value) {
894 $cmdline .= ' --' . $key;
895 if (!is_null($value) && !is_bool($value)) {
896 $cmdline .= ' ' . $value;
900 if ($this->isMinMemoryReached()) {
904 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
905 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
907 $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
909 if (!is_resource($resource)) {
910 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
913 proc_close($resource);
917 * Generates the site's default sender email address
920 * @throws InternalServerErrorException
922 public function getSenderEmailAddress()
924 $sender_email = Core\Config::get('config', 'sender_email');
925 if (empty($sender_email)) {
926 $hostname = $this->getHostName();
927 if (strpos($hostname, ':')) {
928 $hostname = substr($hostname, 0, strpos($hostname, ':'));
931 $sender_email = 'noreply@' . $hostname;
934 return $sender_email;
938 * Returns the current theme name.
940 * @return string the name of the current theme
941 * @throws InternalServerErrorException
943 public function getCurrentTheme()
945 if ($this->getMode()->isInstall()) {
949 if (!$this->currentTheme) {
950 $this->computeCurrentTheme();
953 return $this->currentTheme;
956 public function setCurrentTheme($theme)
958 $this->currentTheme = $theme;
962 * Computes the current theme name based on the node settings, the user settings and the device type
966 private function computeCurrentTheme()
968 $system_theme = Core\Config::get('system', 'theme');
969 if (!$system_theme) {
970 throw new Exception(Core\L10n::t('No system theme config value set.'));
974 $this->currentTheme = $system_theme;
976 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
979 // Find the theme that belongs to the user whose stuff we are looking at
980 if ($this->profile_uid && ($this->profile_uid != local_user())) {
981 // Allow folks to override user themes and always use their own on their own site.
982 // This works only if the user is on the same server
983 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
984 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
985 $page_theme = $user['theme'];
989 $user_theme = Core\Session::get('theme', $system_theme);
991 // Specific mobile theme override
992 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
993 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
994 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
996 // --- means same mobile theme as desktop
997 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
998 $user_theme = $user_mobile_theme;
1003 $theme_name = $page_theme;
1005 $theme_name = $user_theme;
1009 && in_array($theme_name, $allowed_themes)
1010 && (file_exists('view/theme/' . $theme_name . '/style.css')
1011 || file_exists('view/theme/' . $theme_name . '/style.php'))
1013 $this->currentTheme = $theme_name;
1018 * @brief Return full URL to theme which is currently in effect.
1020 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1023 * @throws InternalServerErrorException
1025 public function getCurrentThemeStylesheetPath()
1027 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1031 * Check if request was an AJAX (xmlhttprequest) request.
1033 * @return boolean true if it was an AJAX request
1035 public function isAjax()
1037 return $this->isAjax;
1041 * Returns the value of a argv key
1042 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1044 * @param int $position the position of the argument
1045 * @param mixed $default the default value if not found
1047 * @return mixed returns the value of the argument
1049 public function getArgumentValue($position, $default = '')
1051 if (array_key_exists($position, $this->argv)) {
1052 return $this->argv[$position];
1059 * Sets the base url for use in cmdline programs which don't have
1060 * $_SERVER variables
1062 public function checkURL()
1064 $url = Core\Config::get('system', 'url');
1066 // if the url isn't set or the stored url is radically different
1067 // than the currently visited url, store the current value accordingly.
1068 // "Radically different" ignores common variations such as http vs https
1069 // and www.example.com vs example.com.
1070 // We will only change the url to an ip address if there is no existing setting
1072 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()))) {
1073 Core\Config::set('system', 'url', $this->getBaseURL());
1078 * Frontend App script
1080 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1081 * request and a representation of the response.
1083 * This probably should change to limit the size of this monster method.
1085 public function runFrontend()
1087 // Missing DB connection: ERROR
1088 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1089 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1092 // Max Load Average reached: ERROR
1093 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1094 header('Retry-After: 120');
1095 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1097 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1100 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1101 Core\System::httpExit(404);
1104 if (!$this->getMode()->isInstall()) {
1105 // Force SSL redirection
1106 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1107 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1108 && strpos($this->getBaseURL(), 'https://') === 0
1109 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1110 header('HTTP/1.1 302 Moved Temporarily');
1111 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1115 Core\Session::init();
1116 Core\Hook::callAll('init_1');
1119 // Exclude the backend processes from the session management
1120 if (!$this->isBackend()) {
1121 $stamp1 = microtime(true);
1123 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1124 Core\L10n::setSessionVariable();
1125 Core\L10n::setLangFromSession();
1128 Core\Worker::executeIfIdle();
1132 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1133 $this->query_string = Model\Profile::stripZrls($this->query_string);
1134 if (!local_user()) {
1135 // Only continue when the given profile link seems valid
1136 // Valid profile links contain a path with "/profile/" and no query parameters
1137 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1138 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1139 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1140 $_SESSION['my_url'] = $_GET['zrl'];
1141 $_SESSION['authenticated'] = 0;
1143 Model\Profile::zrlInit($this);
1145 // Someone came with an invalid parameter, maybe as a DDoS attempt
1146 // We simply stop processing here
1147 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1148 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1153 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1154 $token = $_GET['owt'];
1155 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1156 Model\Profile::openWebAuthInit($token);
1159 Module\Login::sessionAuth();
1161 if (empty($_SESSION['authenticated'])) {
1162 header('X-Account-Management-Status: none');
1165 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1166 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1167 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1170 * check_config() is responsible for running update scripts. These automatically
1171 * update the DB schema whenever we push a new one out. It also checks to see if
1172 * any addons have been added or removed and reacts accordingly.
1175 // in install mode, any url loads install module
1176 // but we need "view" module for stylesheet
1177 if ($this->getMode()->isInstall() && $this->module != 'view') {
1178 $this->module = 'install';
1179 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1180 $this->module = 'maintenance';
1183 Core\Update::check($this->basePath, false);
1184 Core\Addon::loadAddons();
1185 Core\Hook::loadHooks();
1196 'right_aside' => '',
1201 if (strlen($this->module)) {
1202 // Compatibility with the Android Diaspora client
1203 if ($this->module == 'stream') {
1204 $this->internalRedirect('network?f=&order=post');
1207 if ($this->module == 'conversations') {
1208 $this->internalRedirect('message');
1211 if ($this->module == 'commented') {
1212 $this->internalRedirect('network?f=&order=comment');
1215 if ($this->module == 'liked') {
1216 $this->internalRedirect('network?f=&order=comment');
1219 if ($this->module == 'activity') {
1220 $this->internalRedirect('network/?f=&conv=1');
1223 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1224 $this->internalRedirect('bookmarklet');
1227 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1228 $this->internalRedirect('settings');
1231 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1232 $this->internalRedirect('search');
1235 // Compatibility with the Firefox App
1236 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1237 $this->module = "login";
1240 $privateapps = Core\Config::get('config', 'private_addons', false);
1241 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1242 //Check if module is an app and if public access to apps is allowed or not
1243 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1244 info(Core\L10n::t("You must be logged in to use addons. "));
1246 include_once "addon/{$this->module}/{$this->module}.php";
1247 if (function_exists($this->module . '_module')) {
1248 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1249 $this->module_class = 'Friendica\\LegacyModule';
1250 $this->module_loaded = true;
1255 // Controller class routing
1256 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1257 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1258 $this->module_loaded = true;
1261 /* If not, next look for a 'standard' program module in the 'mod' directory
1262 * We emulate a Module class through the LegacyModule class
1264 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1265 LegacyModule::setModuleFile("mod/{$this->module}.php");
1266 $this->module_class = 'Friendica\\LegacyModule';
1267 $this->module_loaded = true;
1270 /* The URL provided does not resolve to a valid module.
1272 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1273 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1274 * 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
1275 * this will often succeed and eventually do the right thing.
1277 * Otherwise we are going to emit a 404 not found.
1279 if (! $this->module_loaded) {
1280 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1281 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1285 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1286 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1287 $this->internalRedirect($_SERVER['REQUEST_URI']);
1290 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1292 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1293 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1294 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1295 '$message' => Core\L10n::t('Page not found.')
1302 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1303 if ($this->module_loaded) {
1304 $this->page['page_title'] = $this->module;
1307 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1309 call_user_func([$this->module_class, 'init']);
1311 // "rawContent" is especially meant for technical endpoints.
1312 // This endpoint doesn't need any theme initialization or other comparable stuff.
1313 if (!$this->error) {
1314 call_user_func([$this->module_class, 'rawContent']);
1318 // Load current theme info after module has been initialized as theme could have been set in module
1319 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1320 if (file_exists($theme_info_file)) {
1321 require_once $theme_info_file;
1324 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1325 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1329 if ($this->module_loaded) {
1330 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1331 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1332 call_user_func([$this->module_class, 'post']);
1335 if (! $this->error) {
1336 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1337 call_user_func([$this->module_class, 'afterpost']);
1340 if (! $this->error) {
1341 $arr = ['content' => $content];
1342 Core\Hook::callAll($this->module . '_mod_content', $arr);
1343 $content = $arr['content'];
1344 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1345 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1346 $content .= $arr['content'];
1350 // initialise content region
1351 if ($this->getMode()->isNormal()) {
1352 Core\Hook::callAll('page_content_top', $this->page['content']);
1355 $this->page['content'] .= $content;
1357 /* Create the page head after setting the language
1358 * and getting any auth credentials.
1360 * Moved initHead() and initFooter() to after
1361 * all the module functions have executed so that all
1362 * theme choices made by the modules can take effect.
1366 /* Build the page ending -- this is stuff that goes right before
1367 * the closing </body> tag
1369 $this->initFooter();
1371 /* now that we've been through the module content, see if the page reported
1372 * a permission problem and if so, a 403 response would seem to be in order.
1374 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1375 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1378 // Report anything which needs to be communicated in the notification area (before the main body)
1379 Core\Hook::callAll('page_end', $this->page['content']);
1381 // Add the navigation (menu) template
1382 if ($this->module != 'install' && $this->module != 'maintenance') {
1383 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1384 $this->page['nav'] = Content\Nav::build($this);
1387 // Build the page - now that we have all the components
1388 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1389 $doc = new DOMDocument();
1391 $target = new DOMDocument();
1392 $target->loadXML("<root></root>");
1394 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1396 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1397 @$doc->loadHTML($content);
1399 $xpath = new DOMXPath($doc);
1401 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1403 foreach ($list as $item) {
1404 $item = $target->importNode($item, true);
1406 // And then append it to the target
1407 $target->documentElement->appendChild($item);
1410 if ($_GET["mode"] == "raw") {
1411 header("Content-type: text/html; charset=utf-8");
1413 echo substr($target->saveHTML(), 6, -8);
1419 $page = $this->page;
1420 $profile = $this->profile;
1422 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1423 header("Content-type: text/html; charset=utf-8");
1425 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1426 header("Strict-Transport-Security: max-age=31536000");
1429 // Some security stuff
1430 header('X-Content-Type-Options: nosniff');
1431 header('X-XSS-Protection: 1; mode=block');
1432 header('X-Permitted-Cross-Domain-Policies: none');
1433 header('X-Frame-Options: sameorigin');
1435 // Things like embedded OSM maps don't work, when this is enabled
1436 // 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'");
1438 /* We use $_GET["mode"] for special page templates. So we will check if we have
1439 * to load another page template than the default one.
1440 * The page templates are located in /view/php/ or in the theme directory.
1442 if (isset($_GET["mode"])) {
1443 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1446 // If there is no page template use the default page template
1447 if (empty($template)) {
1448 $template = Core\Theme::getPathForFile("default.php");
1451 // Theme templates expect $a as an App instance
1454 // Used as is in view/php/default.php
1455 $lang = Core\L10n::getCurrentLang();
1457 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1458 require_once $template;
1462 * Redirects to another module relative to the current Friendica base.
1463 * If you want to redirect to a external URL, use System::externalRedirectTo()
1465 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1466 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1468 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1470 public function internalRedirect($toUrl = '', $ssl = false)
1472 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1473 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1476 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1477 Core\System::externalRedirect($redirectTo);
1481 * Automatically redirects to relative or absolute URL
1482 * Should only be used if it isn't clear if the URL is either internal or external
1484 * @param string $toUrl The target URL
1485 * @throws InternalServerErrorException
1487 public function redirect($toUrl)
1489 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1490 Core\System::externalRedirect($toUrl);
1492 $this->internalRedirect($toUrl);