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\Model\Profile;
16 use Friendica\Network\HTTPException\InternalServerErrorException;
17 use Friendica\Util\HTTPSignature;
18 use Friendica\Util\Profiler;
19 use Psr\Log\LoggerInterface;
25 * @brief Our main application structure for the life of this page.
27 * Primarily deals with the URL that got us here
28 * and tries to make some sense of it, and
29 * stores our page contents and config storage
30 * and anything else that might need to be passed around
31 * before we spit the page out.
36 public $module_loaded = false;
37 public $module_class = null;
38 public $query_string = '';
49 public $error = false;
55 public $interactive = true;
57 public $is_mobile = false;
58 public $is_tablet = false;
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 Configuration The config
119 * @var LoggerInterface The logger
124 * @var Profiler The profiler of this app
129 * Returns the current config cache of this node
131 * @return IConfigCache
133 public function getConfigCache()
135 return $this->config->getCache();
139 * The basepath of this app
143 public function getBasePath()
145 return $this->basePath;
149 * The Logger of this app
151 * @return LoggerInterface
153 public function getLogger()
155 return $this->logger;
159 * The profiler of this app
163 public function getProfiler()
165 return $this->profiler;
169 * Register a stylesheet file path to be included in the <head> tag of every page.
170 * Inclusion is done in App->initHead().
171 * The path can be absolute or relative to the Friendica installation base folder.
175 * @param string $path
176 * @throws InternalServerErrorException
178 public function registerStylesheet($path)
180 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
182 $this->stylesheets[] = trim($url, '/');
186 * Register a javascript file path to be included in the <footer> tag of every page.
187 * Inclusion is done in App->initFooter().
188 * The path can be absolute or relative to the Friendica installation base folder.
192 * @param string $path
193 * @throws InternalServerErrorException
195 public function registerFooterScript($path)
197 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
199 $this->footerScripts[] = trim($url, '/');
207 * @brief App constructor.
209 * @param string $basePath The basedir of the app
210 * @param Configuration $config The Configuration
211 * @param LoggerInterface $logger The current app logger
212 * @param Profiler $profiler The profiler of this application
213 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
215 * @throws Exception if the Basepath is not usable
217 public function __construct($basePath, Configuration $config, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
219 BaseObject::setApp($this);
221 $this->logger = $logger;
222 $this->config = $config;
223 $this->profiler = $profiler;
224 $cfgBasePath = $this->config->get('system', 'basepath');
225 $this->basePath = !empty($cfgBasePath) ? $cfgBasePath : $basePath;
227 if (!Core\System::isDirectoryUsable($this->basePath, false)) {
228 throw new Exception('Basepath \'' . $this->basePath . '\' isn\'t usable.');
230 $this->basePath = rtrim($this->basePath, DIRECTORY_SEPARATOR);
232 $this->checkBackend($isBackend);
233 $this->checkFriendicaApp();
235 $this->profiler->reset();
237 $this->mode = new App\Mode($this->basePath);
243 // This has to be quite large to deal with embedded private photos
244 ini_set('pcre.backtrack_limit', 500000);
246 $this->scheme = 'http';
248 if (!empty($_SERVER['HTTPS']) ||
249 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
250 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
251 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
252 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
253 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
255 $this->scheme = 'https';
258 if (!empty($_SERVER['SERVER_NAME'])) {
259 $this->hostname = $_SERVER['SERVER_NAME'];
261 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
262 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
267 get_include_path() . PATH_SEPARATOR
268 . $this->basePath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
269 . $this->basePath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
272 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
273 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
274 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
275 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
278 // removing trailing / - maybe a nginx problem
279 $this->query_string = ltrim($this->query_string, '/');
281 if (!empty($_GET['pagename'])) {
282 $this->cmd = trim($_GET['pagename'], '/\\');
283 } elseif (!empty($_GET['q'])) {
284 $this->cmd = trim($_GET['q'], '/\\');
288 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
290 // unix style "homedir"
291 if (substr($this->cmd, 0, 1) === '~') {
292 $this->cmd = 'profile/' . substr($this->cmd, 1);
295 // Diaspora style profile url
296 if (substr($this->cmd, 0, 2) === 'u/') {
297 $this->cmd = 'profile/' . substr($this->cmd, 2);
301 * Break the URL path into C style argc/argv style arguments for our
302 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
303 * will be 3 (integer) and $this->argv will contain:
309 * There will always be one argument. If provided a naked domain
310 * URL, $this->argv[0] is set to "home".
313 $this->argv = explode('/', $this->cmd);
314 $this->argc = count($this->argv);
315 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
316 $this->module = str_replace('.', '_', $this->argv[0]);
317 $this->module = str_replace('-', '_', $this->module);
320 $this->argv = ['home'];
321 $this->module = 'home';
324 // Detect mobile devices
325 $mobile_detect = new MobileDetect();
327 $this->mobileDetect = $mobile_detect;
329 $this->is_mobile = $mobile_detect->isMobile();
330 $this->is_tablet = $mobile_detect->isTablet();
332 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
334 // Register template engines
335 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
339 * Returns the Mode of the Application
341 * @return App\Mode The Application Mode
343 * @throws InternalServerErrorException when the mode isn't created
345 public function getMode()
347 if (empty($this->mode)) {
348 throw new InternalServerErrorException('Mode of the Application is not defined');
355 * Reloads the whole app instance
357 public function reload()
359 $this->determineURLPath();
361 $this->getMode()->determine($this->basePath);
363 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
364 $loader = new ConfigCacheLoader($this->basePath);
365 $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
367 $this->profiler->update(
368 $this->config->get('system', 'profiler', false),
369 $this->config->get('rendertime', 'callstack', false));
371 Core\Hook::loadHooks();
372 Core\Hook::callAll('load_config', $loader);
375 $this->loadDefaultTimezone();
381 * Loads the default timezone
383 * Include support for legacy $default_timezone
385 * @global string $default_timezone
387 private function loadDefaultTimezone()
389 if ($this->config->get('system', 'default_timezone')) {
390 $this->timezone = $this->config->get('system', 'default_timezone');
392 global $default_timezone;
393 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
396 if ($this->timezone) {
397 date_default_timezone_set($this->timezone);
402 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
404 private function determineURLPath()
407 * The automatic path detection in this function is currently deactivated,
408 * see issue https://github.com/friendica/friendica/issues/6679
410 * The problem is that the function seems to be confused with some url.
411 * These then confuses the detection which changes the url path.
414 /* Relative script path to the web server root
415 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
418 $relative_script_path = '';
419 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
420 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
421 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
422 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
423 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
425 $this->urlPath = $this->config->get('system', 'urlpath');
427 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
428 * QUERY_STRING gives pagename=module/parameter
430 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
433 if (!empty($relative_script_path)) {
435 if (!empty($_SERVER['QUERY_STRING'])) {
436 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
439 $path = trim($relative_script_path, '/');
442 if ($path && $path != $this->urlPath) {
443 $this->urlPath = $path;
449 public function getScheme()
451 return $this->scheme;
455 * @brief Retrieves the Friendica instance base URL
457 * This function assembles the base URL from multiple parts:
458 * - Protocol is determined either by the request or a combination of
459 * system.ssl_policy and the $ssl parameter.
460 * - Host name is determined either by system.hostname or inferred from request
461 * - Path is inferred from SCRIPT_NAME
463 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
465 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
466 * @return string Friendica server base URL
467 * @throws InternalServerErrorException
469 public function getBaseURL($ssl = false)
471 $scheme = $this->scheme;
473 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
477 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
478 // (and also the login link). Anything seen by an outsider will have it turned off.
480 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
488 if (Core\Config::get('config', 'hostname') != '') {
489 $this->hostname = Core\Config::get('config', 'hostname');
492 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
496 * @brief Initializes the baseurl components
498 * Clears the baseurl cache to prevent inconsistencies
501 * @throws InternalServerErrorException
503 public function setBaseURL($url)
505 $parsed = @parse_url($url);
508 if (!empty($parsed)) {
509 if (!empty($parsed['scheme'])) {
510 $this->scheme = $parsed['scheme'];
513 if (!empty($parsed['host'])) {
514 $hostname = $parsed['host'];
517 if (!empty($parsed['port'])) {
518 $hostname .= ':' . $parsed['port'];
520 if (!empty($parsed['path'])) {
521 $this->urlPath = trim($parsed['path'], '\\/');
524 if (file_exists($this->basePath . '/.htpreconfig.php')) {
525 include $this->basePath . '/.htpreconfig.php';
528 if (Core\Config::get('config', 'hostname') != '') {
529 $this->hostname = Core\Config::get('config', 'hostname');
532 if (!isset($this->hostname) || ($this->hostname == '')) {
533 $this->hostname = $hostname;
538 public function getHostName()
540 if (Core\Config::get('config', 'hostname') != '') {
541 $this->hostname = Core\Config::get('config', 'hostname');
544 return $this->hostname;
547 public function getURLPath()
549 return $this->urlPath;
553 * Initializes App->page['htmlhead'].
558 * - Registered stylesheets (through App->registerStylesheet())
559 * - Infinite scroll data
560 * - head.tpl template
562 public function initHead()
564 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
566 // If the update is 'deactivated' set it to the highest integer number (~24 days)
568 $interval = 2147483647;
571 if ($interval < 10000) {
575 // Default title: current module called
576 if (empty($this->page['title']) && $this->module) {
577 $this->page['title'] = ucfirst($this->module);
580 // Prepend the sitename to the page title
581 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
583 if (!empty(Core\Renderer::$theme['stylesheet'])) {
584 $stylesheet = Core\Renderer::$theme['stylesheet'];
586 $stylesheet = $this->getCurrentThemeStylesheetPath();
589 $this->registerStylesheet($stylesheet);
591 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
592 if ($shortcut_icon == '') {
593 $shortcut_icon = 'images/friendica-32.png';
596 $touch_icon = Core\Config::get('system', 'touch_icon');
597 if ($touch_icon == '') {
598 $touch_icon = 'images/friendica-128.png';
601 Core\Hook::callAll('head', $this->page['htmlhead']);
603 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
604 /* put the head template at the beginning of page['htmlhead']
605 * since the code added by the modules frequently depends on it
608 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
609 '$baseurl' => $this->getBaseURL(),
610 '$local_user' => local_user(),
611 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
612 '$delitem' => Core\L10n::t('Delete this item?'),
613 '$update_interval' => $interval,
614 '$shortcut_icon' => $shortcut_icon,
615 '$touch_icon' => $touch_icon,
616 '$block_public' => intval(Core\Config::get('system', 'block_public')),
617 '$stylesheets' => $this->stylesheets,
618 ]) . $this->page['htmlhead'];
622 * Initializes App->page['footer'].
625 * - Javascript homebase
626 * - Mobile toggle link
627 * - Registered footer scripts (through App->registerFooterScript())
628 * - footer.tpl template
630 public function initFooter()
632 // If you're just visiting, let javascript take you home
633 if (!empty($_SESSION['visitor_home'])) {
634 $homebase = $_SESSION['visitor_home'];
635 } elseif (local_user()) {
636 $homebase = 'profile/' . $this->user['nickname'];
639 if (isset($homebase)) {
640 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
644 * Add a "toggle mobile" link if we're using a mobile device
646 if ($this->is_mobile || $this->is_tablet) {
647 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
648 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
650 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
652 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
653 '$toggle_link' => $link,
654 '$toggle_text' => Core\L10n::t('toggle mobile')
658 Core\Hook::callAll('footer', $this->page['footer']);
660 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
661 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
662 '$baseurl' => $this->getBaseURL(),
663 '$footerScripts' => $this->footerScripts,
664 ]) . $this->page['footer'];
668 * @brief Removes the base url from an url. This avoids some mixed content problems.
670 * @param string $origURL
672 * @return string The cleaned url
673 * @throws InternalServerErrorException
675 public function removeBaseURL($origURL)
677 // Remove the hostname from the url if it is an internal link
678 $nurl = Util\Strings::normaliseLink($origURL);
679 $base = Util\Strings::normaliseLink($this->getBaseURL());
680 $url = str_replace($base . '/', '', $nurl);
682 // if it is an external link return the orignal value
683 if ($url == Util\Strings::normaliseLink($origURL)) {
691 * Returns the current UserAgent as a String
693 * @return string the UserAgent as a String
694 * @throws InternalServerErrorException
696 public function getUserAgent()
699 FRIENDICA_PLATFORM . " '" .
700 FRIENDICA_CODENAME . "' " .
701 FRIENDICA_VERSION . '-' .
702 DB_UPDATE_VERSION . '; ' .
707 * Checks, if the call is from the Friendica App
710 * The friendica client has problems with the GUID in the notify. this is some workaround
712 private function checkFriendicaApp()
715 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
719 * Is the call via the Friendica app? (not a "normale" call)
721 * @return bool true if it's from the Friendica app
723 public function isFriendicaApp()
725 return $this->isFriendicaApp;
729 * @brief Checks if the site is called via a backend process
731 * This isn't a perfect solution. But we need this check very early.
732 * So we cannot wait until the modules are loaded.
734 * @param string $backend true, if the backend flag was set during App initialization
737 private function checkBackend($backend) {
760 // Check if current module is in backend or backend flag is set
761 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
765 * Returns true, if the call is from a backend node (f.e. from a worker)
767 * @return bool Is it a known backend?
769 public function isBackend()
771 return $this->isBackend;
775 * @brief Checks if the maximum number of database processes is reached
777 * @return bool Is the limit reached?
779 public function isMaxProcessesReached()
781 // Deactivated, needs more investigating if this check really makes sense
785 * Commented out to suppress static analyzer issues
787 if ($this->is_backend()) {
788 $process = 'backend';
789 $max_processes = Core\Config::get('system', 'max_processes_backend');
790 if (intval($max_processes) == 0) {
794 $process = 'frontend';
795 $max_processes = Core\Config::get('system', 'max_processes_frontend');
796 if (intval($max_processes) == 0) {
801 $processlist = DBA::processlist();
802 if ($processlist['list'] != '') {
803 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
805 if ($processlist['amount'] > $max_processes) {
806 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
815 * @brief Checks if the minimal memory is reached
817 * @return bool Is the memory limit reached?
818 * @throws InternalServerErrorException
820 public function isMinMemoryReached()
822 $min_memory = Core\Config::get('system', 'min_memory', 0);
823 if ($min_memory == 0) {
827 if (!is_readable('/proc/meminfo')) {
831 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
834 foreach ($memdata as $line) {
835 $data = explode(':', $line);
836 if (count($data) != 2) {
839 list($key, $val) = $data;
840 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
841 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
844 if (!isset($meminfo['MemFree'])) {
848 $free = $meminfo['MemFree'];
850 $reached = ($free < $min_memory);
853 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
860 * @brief Checks if the maximum load is reached
862 * @return bool Is the load reached?
863 * @throws InternalServerErrorException
865 public function isMaxLoadReached()
867 if ($this->isBackend()) {
868 $process = 'backend';
869 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
870 if ($maxsysload < 1) {
874 $process = 'frontend';
875 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
876 if ($maxsysload < 1) {
881 $load = Core\System::currentLoad();
883 if (intval($load) > $maxsysload) {
884 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
892 * Executes a child process with 'proc_open'
894 * @param string $command The command to execute
895 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
896 * @throws InternalServerErrorException
898 public function proc_run($command, $args)
900 if (!function_exists('proc_open')) {
904 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
906 foreach ($args as $key => $value) {
907 if (!is_null($value) && is_bool($value) && !$value) {
911 $cmdline .= ' --' . $key;
912 if (!is_null($value) && !is_bool($value)) {
913 $cmdline .= ' ' . $value;
917 if ($this->isMinMemoryReached()) {
921 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
922 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
924 $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
926 if (!is_resource($resource)) {
927 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
930 proc_close($resource);
934 * Generates the site's default sender email address
937 * @throws InternalServerErrorException
939 public function getSenderEmailAddress()
941 $sender_email = Core\Config::get('config', 'sender_email');
942 if (empty($sender_email)) {
943 $hostname = $this->getHostName();
944 if (strpos($hostname, ':')) {
945 $hostname = substr($hostname, 0, strpos($hostname, ':'));
948 $sender_email = 'noreply@' . $hostname;
951 return $sender_email;
955 * Returns the current theme name.
957 * @return string the name of the current theme
958 * @throws InternalServerErrorException
960 public function getCurrentTheme()
962 if ($this->getMode()->isInstall()) {
966 if (!$this->currentTheme) {
967 $this->computeCurrentTheme();
970 return $this->currentTheme;
973 public function setCurrentTheme($theme)
975 $this->currentTheme = $theme;
979 * Computes the current theme name based on the node settings, the user settings and the device type
983 private function computeCurrentTheme()
985 $system_theme = Core\Config::get('system', 'theme');
986 if (!$system_theme) {
987 throw new Exception(Core\L10n::t('No system theme config value set.'));
991 $this->currentTheme = $system_theme;
993 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
996 // Find the theme that belongs to the user whose stuff we are looking at
997 if ($this->profile_uid && ($this->profile_uid != local_user())) {
998 // Allow folks to override user themes and always use their own on their own site.
999 // This works only if the user is on the same server
1000 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1001 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1002 $page_theme = $user['theme'];
1006 $user_theme = Core\Session::get('theme', $system_theme);
1008 // Specific mobile theme override
1009 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1010 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1011 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1013 // --- means same mobile theme as desktop
1014 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1015 $user_theme = $user_mobile_theme;
1020 $theme_name = $page_theme;
1022 $theme_name = $user_theme;
1026 && in_array($theme_name, $allowed_themes)
1027 && (file_exists('view/theme/' . $theme_name . '/style.css')
1028 || file_exists('view/theme/' . $theme_name . '/style.php'))
1030 $this->currentTheme = $theme_name;
1035 * @brief Return full URL to theme which is currently in effect.
1037 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1040 * @throws InternalServerErrorException
1042 public function getCurrentThemeStylesheetPath()
1044 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1048 * Check if request was an AJAX (xmlhttprequest) request.
1050 * @return boolean true if it was an AJAX request
1052 public function isAjax()
1054 return $this->isAjax;
1058 * Returns the value of a argv key
1059 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1061 * @param int $position the position of the argument
1062 * @param mixed $default the default value if not found
1064 * @return mixed returns the value of the argument
1066 public function getArgumentValue($position, $default = '')
1068 if (array_key_exists($position, $this->argv)) {
1069 return $this->argv[$position];
1076 * Sets the base url for use in cmdline programs which don't have
1077 * $_SERVER variables
1079 public function checkURL()
1081 $url = Core\Config::get('system', 'url');
1083 // if the url isn't set or the stored url is radically different
1084 // than the currently visited url, store the current value accordingly.
1085 // "Radically different" ignores common variations such as http vs https
1086 // and www.example.com vs example.com.
1087 // We will only change the url to an ip address if there is no existing setting
1089 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()))) {
1090 Core\Config::set('system', 'url', $this->getBaseURL());
1095 * Frontend App script
1097 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1098 * request and a representation of the response.
1100 * This probably should change to limit the size of this monster method.
1102 public function runFrontend()
1104 // Missing DB connection: ERROR
1105 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1106 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1109 // Max Load Average reached: ERROR
1110 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1111 header('Retry-After: 120');
1112 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1114 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1117 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1118 Core\System::httpExit(404);
1121 if (!$this->getMode()->isInstall()) {
1122 // Force SSL redirection
1123 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1124 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1125 && strpos($this->getBaseURL(), 'https://') === 0
1126 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1127 header('HTTP/1.1 302 Moved Temporarily');
1128 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1132 Core\Session::init();
1133 Core\Hook::callAll('init_1');
1136 // Exclude the backend processes from the session management
1137 if (!$this->isBackend()) {
1138 $stamp1 = microtime(true);
1140 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1141 Core\L10n::setSessionVariable();
1142 Core\L10n::setLangFromSession();
1145 Core\Worker::executeIfIdle();
1148 if ($this->getMode()->isNormal()) {
1149 $requester = HTTPSignature::getSigner('', $_SERVER);
1150 if (!empty($requester)) {
1151 Profile::addVisitorCookieForHandle($requester);
1156 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1157 $this->query_string = Model\Profile::stripZrls($this->query_string);
1158 if (!local_user()) {
1159 // Only continue when the given profile link seems valid
1160 // Valid profile links contain a path with "/profile/" and no query parameters
1161 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1162 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1163 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1164 $_SESSION['my_url'] = $_GET['zrl'];
1165 $_SESSION['authenticated'] = 0;
1167 Model\Profile::zrlInit($this);
1169 // Someone came with an invalid parameter, maybe as a DDoS attempt
1170 // We simply stop processing here
1171 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1172 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1177 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1178 $token = $_GET['owt'];
1179 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1180 Model\Profile::openWebAuthInit($token);
1183 Module\Login::sessionAuth();
1185 if (empty($_SESSION['authenticated'])) {
1186 header('X-Account-Management-Status: none');
1189 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1190 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1191 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1194 * check_config() is responsible for running update scripts. These automatically
1195 * update the DB schema whenever we push a new one out. It also checks to see if
1196 * any addons have been added or removed and reacts accordingly.
1199 // in install mode, any url loads install module
1200 // but we need "view" module for stylesheet
1201 if ($this->getMode()->isInstall() && $this->module != 'view') {
1202 $this->module = 'install';
1203 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1204 $this->module = 'maintenance';
1207 Core\Update::check($this->basePath, false);
1208 Core\Addon::loadAddons();
1209 Core\Hook::loadHooks();
1220 'right_aside' => '',
1225 if (strlen($this->module)) {
1226 // Compatibility with the Android Diaspora client
1227 if ($this->module == 'stream') {
1228 $this->internalRedirect('network?f=&order=post');
1231 if ($this->module == 'conversations') {
1232 $this->internalRedirect('message');
1235 if ($this->module == 'commented') {
1236 $this->internalRedirect('network?f=&order=comment');
1239 if ($this->module == 'liked') {
1240 $this->internalRedirect('network?f=&order=comment');
1243 if ($this->module == 'activity') {
1244 $this->internalRedirect('network/?f=&conv=1');
1247 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1248 $this->internalRedirect('bookmarklet');
1251 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1252 $this->internalRedirect('settings');
1255 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1256 $this->internalRedirect('search');
1259 // Compatibility with the Firefox App
1260 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1261 $this->module = "login";
1264 $privateapps = Core\Config::get('config', 'private_addons', false);
1265 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1266 //Check if module is an app and if public access to apps is allowed or not
1267 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1268 info(Core\L10n::t("You must be logged in to use addons. "));
1270 include_once "addon/{$this->module}/{$this->module}.php";
1271 if (function_exists($this->module . '_module')) {
1272 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1273 $this->module_class = 'Friendica\\LegacyModule';
1274 $this->module_loaded = true;
1279 // Controller class routing
1280 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1281 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1282 $this->module_loaded = true;
1285 /* If not, next look for a 'standard' program module in the 'mod' directory
1286 * We emulate a Module class through the LegacyModule class
1288 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1289 LegacyModule::setModuleFile("mod/{$this->module}.php");
1290 $this->module_class = 'Friendica\\LegacyModule';
1291 $this->module_loaded = true;
1294 /* The URL provided does not resolve to a valid module.
1296 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1297 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1298 * 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
1299 * this will often succeed and eventually do the right thing.
1301 * Otherwise we are going to emit a 404 not found.
1303 if (! $this->module_loaded) {
1304 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1305 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1309 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1310 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1311 $this->internalRedirect($_SERVER['REQUEST_URI']);
1314 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1316 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1317 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1318 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1319 '$message' => Core\L10n::t('Page not found.')
1326 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1327 if ($this->module_loaded) {
1328 $this->page['page_title'] = $this->module;
1331 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1333 call_user_func([$this->module_class, 'init']);
1335 // "rawContent" is especially meant for technical endpoints.
1336 // This endpoint doesn't need any theme initialization or other comparable stuff.
1337 if (!$this->error) {
1338 call_user_func([$this->module_class, 'rawContent']);
1342 // Load current theme info after module has been initialized as theme could have been set in module
1343 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1344 if (file_exists($theme_info_file)) {
1345 require_once $theme_info_file;
1348 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1349 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1353 if ($this->module_loaded) {
1354 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1355 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1356 call_user_func([$this->module_class, 'post']);
1359 if (! $this->error) {
1360 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1361 call_user_func([$this->module_class, 'afterpost']);
1364 if (! $this->error) {
1365 $arr = ['content' => $content];
1366 Core\Hook::callAll($this->module . '_mod_content', $arr);
1367 $content = $arr['content'];
1368 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1369 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1370 $content .= $arr['content'];
1374 // initialise content region
1375 if ($this->getMode()->isNormal()) {
1376 Core\Hook::callAll('page_content_top', $this->page['content']);
1379 $this->page['content'] .= $content;
1381 /* Create the page head after setting the language
1382 * and getting any auth credentials.
1384 * Moved initHead() and initFooter() to after
1385 * all the module functions have executed so that all
1386 * theme choices made by the modules can take effect.
1390 /* Build the page ending -- this is stuff that goes right before
1391 * the closing </body> tag
1393 $this->initFooter();
1395 /* now that we've been through the module content, see if the page reported
1396 * a permission problem and if so, a 403 response would seem to be in order.
1398 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1399 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1402 // Report anything which needs to be communicated in the notification area (before the main body)
1403 Core\Hook::callAll('page_end', $this->page['content']);
1405 // Add the navigation (menu) template
1406 if ($this->module != 'install' && $this->module != 'maintenance') {
1407 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1408 $this->page['nav'] = Content\Nav::build($this);
1411 // Build the page - now that we have all the components
1412 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1413 $doc = new DOMDocument();
1415 $target = new DOMDocument();
1416 $target->loadXML("<root></root>");
1418 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1420 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1421 @$doc->loadHTML($content);
1423 $xpath = new DOMXPath($doc);
1425 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1427 foreach ($list as $item) {
1428 $item = $target->importNode($item, true);
1430 // And then append it to the target
1431 $target->documentElement->appendChild($item);
1434 if ($_GET["mode"] == "raw") {
1435 header("Content-type: text/html; charset=utf-8");
1437 echo substr($target->saveHTML(), 6, -8);
1443 $page = $this->page;
1444 $profile = $this->profile;
1446 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1447 header("Content-type: text/html; charset=utf-8");
1449 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1450 header("Strict-Transport-Security: max-age=31536000");
1453 // Some security stuff
1454 header('X-Content-Type-Options: nosniff');
1455 header('X-XSS-Protection: 1; mode=block');
1456 header('X-Permitted-Cross-Domain-Policies: none');
1457 header('X-Frame-Options: sameorigin');
1459 // Things like embedded OSM maps don't work, when this is enabled
1460 // 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'");
1462 /* We use $_GET["mode"] for special page templates. So we will check if we have
1463 * to load another page template than the default one.
1464 * The page templates are located in /view/php/ or in the theme directory.
1466 if (isset($_GET["mode"])) {
1467 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1470 // If there is no page template use the default page template
1471 if (empty($template)) {
1472 $template = Core\Theme::getPathForFile("default.php");
1475 // Theme templates expect $a as an App instance
1478 // Used as is in view/php/default.php
1479 $lang = Core\L10n::getCurrentLang();
1481 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1482 require_once $template;
1486 * Redirects to another module relative to the current Friendica base.
1487 * If you want to redirect to a external URL, use System::externalRedirectTo()
1489 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1490 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1492 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1494 public function internalRedirect($toUrl = '', $ssl = false)
1496 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1497 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1500 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1501 Core\System::externalRedirect($redirectTo);
1505 * Automatically redirects to relative or absolute URL
1506 * Should only be used if it isn't clear if the URL is either internal or external
1508 * @param string $toUrl The target URL
1509 * @throws InternalServerErrorException
1511 public function redirect($toUrl)
1513 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1514 Core\System::externalRedirect($toUrl);
1516 $this->internalRedirect($toUrl);