7 use Detection\MobileDetect;
11 use Friendica\Core\Logger;
12 use Friendica\Database\DBA;
13 use Friendica\Network\HTTPException\InternalServerErrorException;
14 use Psr\Log\LoggerInterface;
20 * @brief Our main application structure for the life of this page.
22 * Primarily deals with the URL that got us here
23 * and tries to make some sense of it, and
24 * stores our page contents and config storage
25 * and anything else that might need to be passed around
26 * before we spit the page out.
31 public $module_loaded = false;
32 public $module_class = null;
33 public $query_string = '';
45 public $error = false;
51 public $interactive = true;
53 public $is_mobile = false;
54 public $is_tablet = false;
55 public $performance = [];
56 public $callstack = [];
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 LoggerInterface The current logger of this App
117 * Register a stylesheet file path to be included in the <head> tag of every page.
118 * Inclusion is done in App->initHead().
119 * The path can be absolute or relative to the Friendica installation base folder.
123 * @param string $path
124 * @throws InternalServerErrorException
126 public function registerStylesheet($path)
128 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
130 $this->stylesheets[] = trim($url, '/');
134 * Register a javascript file path to be included in the <footer> tag of every page.
135 * Inclusion is done in App->initFooter().
136 * The path can be absolute or relative to the Friendica installation base folder.
140 * @param string $path
141 * @throws InternalServerErrorException
143 public function registerFooterScript($path)
145 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
147 $this->footerScripts[] = trim($url, '/');
156 * @brief App constructor.
158 * @param string $basePath Path to the app base folder
159 * @param LoggerInterface $logger Logger of this application
160 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
162 * @throws Exception if the Basepath is not usable
164 public function __construct($basePath, LoggerInterface $logger, $isBackend = true)
166 $this->logger = $logger;
168 if (!static::isDirectoryUsable($basePath, false)) {
169 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
172 BaseObject::setApp($this);
174 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
175 $this->checkBackend($isBackend);
176 $this->checkFriendicaApp();
178 $this->performance['start'] = microtime(true);
179 $this->performance['database'] = 0;
180 $this->performance['database_write'] = 0;
181 $this->performance['cache'] = 0;
182 $this->performance['cache_write'] = 0;
183 $this->performance['network'] = 0;
184 $this->performance['file'] = 0;
185 $this->performance['rendering'] = 0;
186 $this->performance['parser'] = 0;
187 $this->performance['marktime'] = 0;
188 $this->performance['markstart'] = microtime(true);
190 $this->callstack['database'] = [];
191 $this->callstack['database_write'] = [];
192 $this->callstack['cache'] = [];
193 $this->callstack['cache_write'] = [];
194 $this->callstack['network'] = [];
195 $this->callstack['file'] = [];
196 $this->callstack['rendering'] = [];
197 $this->callstack['parser'] = [];
199 $this->mode = new App\Mode($basePath);
205 // This has to be quite large to deal with embedded private photos
206 ini_set('pcre.backtrack_limit', 500000);
208 $this->scheme = 'http';
210 if (!empty($_SERVER['HTTPS']) ||
211 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
212 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
213 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
214 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
215 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
217 $this->scheme = 'https';
220 if (!empty($_SERVER['SERVER_NAME'])) {
221 $this->hostname = $_SERVER['SERVER_NAME'];
223 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
224 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
229 get_include_path() . PATH_SEPARATOR
230 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
231 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
232 . $this->getBasePath());
234 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
235 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
236 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
237 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
240 // removing trailing / - maybe a nginx problem
241 $this->query_string = ltrim($this->query_string, '/');
243 if (!empty($_GET['pagename'])) {
244 $this->cmd = trim($_GET['pagename'], '/\\');
245 } elseif (!empty($_GET['q'])) {
246 $this->cmd = trim($_GET['q'], '/\\');
250 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
252 // unix style "homedir"
253 if (substr($this->cmd, 0, 1) === '~') {
254 $this->cmd = 'profile/' . substr($this->cmd, 1);
257 // Diaspora style profile url
258 if (substr($this->cmd, 0, 2) === 'u/') {
259 $this->cmd = 'profile/' . substr($this->cmd, 2);
263 * Break the URL path into C style argc/argv style arguments for our
264 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
265 * will be 3 (integer) and $this->argv will contain:
271 * There will always be one argument. If provided a naked domain
272 * URL, $this->argv[0] is set to "home".
275 $this->argv = explode('/', $this->cmd);
276 $this->argc = count($this->argv);
277 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
278 $this->module = str_replace('.', '_', $this->argv[0]);
279 $this->module = str_replace('-', '_', $this->module);
282 $this->argv = ['home'];
283 $this->module = 'home';
286 // Detect mobile devices
287 $mobile_detect = new MobileDetect();
289 $this->mobileDetect = $mobile_detect;
291 $this->is_mobile = $mobile_detect->isMobile();
292 $this->is_tablet = $mobile_detect->isTablet();
294 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
296 // Register template engines
297 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
301 * Returns the Mode of the Application
303 * @return App\Mode The Application Mode
305 * @throws InternalServerErrorException when the mode isn't created
307 public function getMode()
309 if (empty($this->mode)) {
310 throw new InternalServerErrorException('Mode of the Application is not defined');
317 * Returns the Logger of the Application
319 * @return LoggerInterface The Logger
320 * @throws InternalServerErrorException when the logger isn't created
322 public function getLogger()
324 if (empty($this->logger)) {
325 throw new InternalServerErrorException('Logger of the Application is not defined');
328 return $this->logger;
332 * Reloads the whole app instance
334 public function reload()
336 // The order of the following calls is important to ensure proper initialization
337 $this->loadConfigFiles();
339 $this->loadDatabase();
341 $this->getMode()->determine($this->getBasePath());
343 $this->determineURLPath();
347 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
348 Core\Hook::loadHooks();
350 $this->loadAddonConfig();
353 $this->loadDefaultTimezone();
357 $this->process_id = Core\System::processID('log');
359 Core\Logger::setLogger($this->logger);
363 * Load the configuration files
365 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
366 * expected local.config.php
368 private function loadConfigFiles()
370 $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php');
371 $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php');
373 // Legacy .htconfig.php support
374 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
376 include $this->getBasePath() . '/.htpreconfig.php';
379 // Legacy .htconfig.php support
380 if (file_exists($this->getBasePath() . '/.htconfig.php')) {
383 include $this->getBasePath() . '/.htconfig.php';
385 $this->setConfigValue('database', 'hostname', $db_host);
386 $this->setConfigValue('database', 'username', $db_user);
387 $this->setConfigValue('database', 'password', $db_pass);
388 $this->setConfigValue('database', 'database', $db_data);
389 if (isset($a->config['system']['db_charset'])) {
390 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
393 unset($db_host, $db_user, $db_pass, $db_data);
395 if (isset($default_timezone)) {
396 $this->setConfigValue('system', 'default_timezone', $default_timezone);
397 unset($default_timezone);
400 if (isset($pidfile)) {
401 $this->setConfigValue('system', 'pidfile', $pidfile);
406 $this->setConfigValue('system', 'language', $lang);
411 if (file_exists($this->getBasePath() . '/config/local.config.php')) {
412 $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true);
413 } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) {
414 $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true);
419 * Tries to load the specified legacy configuration file into the App->config array.
420 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
422 * @deprecated since version 2018.12
423 * @param string $filepath
424 * @param bool $overwrite Force value overwrite if the config key already exists
427 public function loadINIConfigFile($filepath, $overwrite = false)
429 if (!file_exists($filepath)) {
430 throw new Exception('Error parsing non-existent INI config file ' . $filepath);
433 $contents = include($filepath);
435 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
437 if ($config === false) {
438 throw new Exception('Error parsing INI config file ' . $filepath);
441 $this->loadConfigArray($config, $overwrite);
445 * Tries to load the specified configuration file into the App->config array.
446 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
448 * The config format is PHP array and the template for configuration files is the following:
456 * @param string $filepath
457 * @param bool $overwrite Force value overwrite if the config key already exists
460 public function loadConfigFile($filepath, $overwrite = false)
462 if (!file_exists($filepath)) {
463 throw new Exception('Error loading non-existent config file ' . $filepath);
466 $config = include($filepath);
468 if (!is_array($config)) {
469 throw new Exception('Error loading config file ' . $filepath);
472 $this->loadConfigArray($config, $overwrite);
476 * Loads addons configuration files
478 * First loads all activated addons default configuration through the load_config hook, then load the local.config.php
479 * again to overwrite potential local addon configuration.
481 private function loadAddonConfig()
483 // Loads addons default config
484 Core\Hook::callAll('load_config');
486 // Load the local addon config file to overwritten default addon config values
487 if (file_exists($this->getBasePath() . '/config/addon.config.php')) {
488 $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true);
489 } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) {
490 $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true);
495 * Tries to load the specified configuration array into the App->config array.
496 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
498 * @param array $config
499 * @param bool $overwrite Force value overwrite if the config key already exists
501 private function loadConfigArray(array $config, $overwrite = false)
503 foreach ($config as $category => $values) {
504 foreach ($values as $key => $value) {
506 $this->setConfigValue($category, $key, $value);
508 $this->setDefaultConfigValue($category, $key, $value);
515 * Loads the default timezone
517 * Include support for legacy $default_timezone
519 * @global string $default_timezone
521 private function loadDefaultTimezone()
523 if ($this->getConfigValue('system', 'default_timezone')) {
524 $this->timezone = $this->getConfigValue('system', 'default_timezone');
526 global $default_timezone;
527 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
530 if ($this->timezone) {
531 date_default_timezone_set($this->timezone);
536 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
538 private function determineURLPath()
540 /* Relative script path to the web server root
541 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
543 $relative_script_path = '';
544 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
545 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
546 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
547 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
548 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
550 $this->urlPath = $this->getConfigValue('system', 'urlpath');
552 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
553 * QUERY_STRING gives pagename=module/parameter
555 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
557 if (!empty($relative_script_path)) {
559 if (!empty($_SERVER['QUERY_STRING'])) {
560 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
563 $path = trim($relative_script_path, '/');
566 if ($path && $path != $this->urlPath) {
567 $this->urlPath = $path;
572 public function loadDatabase()
574 if (DBA::connected()) {
578 $db_host = $this->getConfigValue('database', 'hostname');
579 $db_user = $this->getConfigValue('database', 'username');
580 $db_pass = $this->getConfigValue('database', 'password');
581 $db_data = $this->getConfigValue('database', 'database');
582 $charset = $this->getConfigValue('database', 'charset');
584 // Use environment variables for mysql if they are set beforehand
585 if (!empty(getenv('MYSQL_HOST'))
586 && !empty(getenv('MYSQL_USERNAME') || !empty(getenv('MYSQL_USER')))
587 && getenv('MYSQL_PASSWORD') !== false
588 && !empty(getenv('MYSQL_DATABASE')))
590 $db_host = getenv('MYSQL_HOST');
591 if (!empty(getenv('MYSQL_PORT'))) {
592 $db_host .= ':' . getenv('MYSQL_PORT');
594 if (!empty(getenv('MYSQL_USERNAME'))) {
595 $db_user = getenv('MYSQL_USERNAME');
597 $db_user = getenv('MYSQL_USER');
599 $db_pass = (string) getenv('MYSQL_PASSWORD');
600 $db_data = getenv('MYSQL_DATABASE');
603 $stamp1 = microtime(true);
605 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
606 // Loads DB_UPDATE_VERSION constant
607 Database\DBStructure::definition(false);
610 unset($db_host, $db_user, $db_pass, $db_data, $charset);
612 $this->saveTimestamp($stamp1, 'network');
616 * @brief Returns the base filesystem path of the App
618 * It first checks for the internal variable, then for DOCUMENT_ROOT and
622 * @throws InternalServerErrorException
624 public function getBasePath()
626 $basepath = $this->basePath;
629 $basepath = Core\Config::get('system', 'basepath');
632 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
633 $basepath = $_SERVER['DOCUMENT_ROOT'];
636 if (!$basepath && !empty($_SERVER['PWD'])) {
637 $basepath = $_SERVER['PWD'];
640 return self::getRealPath($basepath);
644 * @brief Returns a normalized file path
646 * This is a wrapper for the "realpath" function.
647 * That function cannot detect the real path when some folders aren't readable.
648 * Since this could happen with some hosters we need to handle this.
650 * @param string $path The path that is about to be normalized
651 * @return string normalized path - when possible
653 public static function getRealPath($path)
655 $normalized = realpath($path);
657 if (!is_bool($normalized)) {
664 public function getScheme()
666 return $this->scheme;
670 * @brief Retrieves the Friendica instance base URL
672 * This function assembles the base URL from multiple parts:
673 * - Protocol is determined either by the request or a combination of
674 * system.ssl_policy and the $ssl parameter.
675 * - Host name is determined either by system.hostname or inferred from request
676 * - Path is inferred from SCRIPT_NAME
678 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
680 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
681 * @return string Friendica server base URL
682 * @throws InternalServerErrorException
684 public function getBaseURL($ssl = false)
686 $scheme = $this->scheme;
688 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
692 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
693 // (and also the login link). Anything seen by an outsider will have it turned off.
695 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
703 if (Core\Config::get('config', 'hostname') != '') {
704 $this->hostname = Core\Config::get('config', 'hostname');
707 return $scheme . '://' . $this->hostname . !empty($this->getURLPath() ? '/' . $this->getURLPath() : '' );
711 * @brief Initializes the baseurl components
713 * Clears the baseurl cache to prevent inconsistencies
716 * @throws InternalServerErrorException
718 public function setBaseURL($url)
720 $parsed = @parse_url($url);
723 if (!empty($parsed)) {
724 if (!empty($parsed['scheme'])) {
725 $this->scheme = $parsed['scheme'];
728 if (!empty($parsed['host'])) {
729 $hostname = $parsed['host'];
732 if (!empty($parsed['port'])) {
733 $hostname .= ':' . $parsed['port'];
735 if (!empty($parsed['path'])) {
736 $this->urlPath = trim($parsed['path'], '\\/');
739 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
740 include $this->getBasePath() . '/.htpreconfig.php';
743 if (Core\Config::get('config', 'hostname') != '') {
744 $this->hostname = Core\Config::get('config', 'hostname');
747 if (!isset($this->hostname) || ($this->hostname == '')) {
748 $this->hostname = $hostname;
753 public function getHostName()
755 if (Core\Config::get('config', 'hostname') != '') {
756 $this->hostname = Core\Config::get('config', 'hostname');
759 return $this->hostname;
762 public function getURLPath()
764 return $this->urlPath;
768 * Initializes App->page['htmlhead'].
773 * - Registered stylesheets (through App->registerStylesheet())
774 * - Infinite scroll data
775 * - head.tpl template
777 public function initHead()
779 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
781 // If the update is 'deactivated' set it to the highest integer number (~24 days)
783 $interval = 2147483647;
786 if ($interval < 10000) {
790 // compose the page title from the sitename and the
791 // current module called
792 if (!$this->module == '') {
793 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
795 $this->page['title'] = $this->config['sitename'];
798 if (!empty(Core\Renderer::$theme['stylesheet'])) {
799 $stylesheet = Core\Renderer::$theme['stylesheet'];
801 $stylesheet = $this->getCurrentThemeStylesheetPath();
804 $this->registerStylesheet($stylesheet);
806 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
807 if ($shortcut_icon == '') {
808 $shortcut_icon = 'images/friendica-32.png';
811 $touch_icon = Core\Config::get('system', 'touch_icon');
812 if ($touch_icon == '') {
813 $touch_icon = 'images/friendica-128.png';
816 Core\Hook::callAll('head', $this->page['htmlhead']);
818 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
819 /* put the head template at the beginning of page['htmlhead']
820 * since the code added by the modules frequently depends on it
823 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
824 '$baseurl' => $this->getBaseURL(),
825 '$local_user' => local_user(),
826 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
827 '$delitem' => Core\L10n::t('Delete this item?'),
828 '$showmore' => Core\L10n::t('show more'),
829 '$showfewer' => Core\L10n::t('show fewer'),
830 '$update_interval' => $interval,
831 '$shortcut_icon' => $shortcut_icon,
832 '$touch_icon' => $touch_icon,
833 '$block_public' => intval(Core\Config::get('system', 'block_public')),
834 '$stylesheets' => $this->stylesheets,
835 ]) . $this->page['htmlhead'];
839 * Initializes App->page['footer'].
842 * - Javascript homebase
843 * - Mobile toggle link
844 * - Registered footer scripts (through App->registerFooterScript())
845 * - footer.tpl template
847 public function initFooter()
849 // If you're just visiting, let javascript take you home
850 if (!empty($_SESSION['visitor_home'])) {
851 $homebase = $_SESSION['visitor_home'];
852 } elseif (local_user()) {
853 $homebase = 'profile/' . $this->user['nickname'];
856 if (isset($homebase)) {
857 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
861 * Add a "toggle mobile" link if we're using a mobile device
863 if ($this->is_mobile || $this->is_tablet) {
864 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
865 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
867 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
869 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
870 '$toggle_link' => $link,
871 '$toggle_text' => Core\L10n::t('toggle mobile')
875 Core\Hook::callAll('footer', $this->page['footer']);
877 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
878 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
879 '$baseurl' => $this->getBaseURL(),
880 '$footerScripts' => $this->footerScripts,
881 ]) . $this->page['footer'];
885 * @brief Removes the base url from an url. This avoids some mixed content problems.
887 * @param string $origURL
889 * @return string The cleaned url
890 * @throws InternalServerErrorException
892 public function removeBaseURL($origURL)
894 // Remove the hostname from the url if it is an internal link
895 $nurl = Util\Strings::normaliseLink($origURL);
896 $base = Util\Strings::normaliseLink($this->getBaseURL());
897 $url = str_replace($base . '/', '', $nurl);
899 // if it is an external link return the orignal value
900 if ($url == Util\Strings::normaliseLink($origURL)) {
908 * Saves a timestamp for a value - f.e. a call
909 * Necessary for profiling Friendica
911 * @param int $timestamp the Timestamp
912 * @param string $value A value to profile
914 public function saveTimestamp($timestamp, $value)
916 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
920 $duration = (float) (microtime(true) - $timestamp);
922 if (!isset($this->performance[$value])) {
923 // Prevent ugly E_NOTICE
924 $this->performance[$value] = 0;
927 $this->performance[$value] += (float) $duration;
928 $this->performance['marktime'] += (float) $duration;
930 $callstack = Core\System::callstack();
932 if (!isset($this->callstack[$value][$callstack])) {
933 // Prevent ugly E_NOTICE
934 $this->callstack[$value][$callstack] = 0;
937 $this->callstack[$value][$callstack] += (float) $duration;
941 * Returns the current UserAgent as a String
943 * @return string the UserAgent as a String
944 * @throws InternalServerErrorException
946 public function getUserAgent()
949 FRIENDICA_PLATFORM . " '" .
950 FRIENDICA_CODENAME . "' " .
951 FRIENDICA_VERSION . '-' .
952 DB_UPDATE_VERSION . '; ' .
957 * Checks, if the call is from the Friendica App
960 * The friendica client has problems with the GUID in the notify. this is some workaround
962 private function checkFriendicaApp()
965 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
969 * Is the call via the Friendica app? (not a "normale" call)
971 * @return bool true if it's from the Friendica app
973 public function isFriendicaApp()
975 return $this->isFriendicaApp;
979 * @brief Checks if the site is called via a backend process
981 * This isn't a perfect solution. But we need this check very early.
982 * So we cannot wait until the modules are loaded.
984 * @param string $backend true, if the backend flag was set during App initialization
987 private function checkBackend($backend) {
1010 // Check if current module is in backend or backend flag is set
1011 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1015 * Returns true, if the call is from a backend node (f.e. from a worker)
1017 * @return bool Is it a known backend?
1019 public function isBackend()
1021 return $this->isBackend;
1025 * @brief Checks if the maximum number of database processes is reached
1027 * @return bool Is the limit reached?
1029 public function isMaxProcessesReached()
1031 // Deactivated, needs more investigating if this check really makes sense
1035 * Commented out to suppress static analyzer issues
1037 if ($this->is_backend()) {
1038 $process = 'backend';
1039 $max_processes = Core\Config::get('system', 'max_processes_backend');
1040 if (intval($max_processes) == 0) {
1044 $process = 'frontend';
1045 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1046 if (intval($max_processes) == 0) {
1047 $max_processes = 20;
1051 $processlist = DBA::processlist();
1052 if ($processlist['list'] != '') {
1053 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
1055 if ($processlist['amount'] > $max_processes) {
1056 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
1065 * @brief Checks if the minimal memory is reached
1067 * @return bool Is the memory limit reached?
1068 * @throws InternalServerErrorException
1070 public function isMinMemoryReached()
1072 $min_memory = Core\Config::get('system', 'min_memory', 0);
1073 if ($min_memory == 0) {
1077 if (!is_readable('/proc/meminfo')) {
1081 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1084 foreach ($memdata as $line) {
1085 $data = explode(':', $line);
1086 if (count($data) != 2) {
1089 list($key, $val) = $data;
1090 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1091 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1094 if (!isset($meminfo['MemFree'])) {
1098 $free = $meminfo['MemFree'];
1100 $reached = ($free < $min_memory);
1103 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1110 * @brief Checks if the maximum load is reached
1112 * @return bool Is the load reached?
1113 * @throws InternalServerErrorException
1115 public function isMaxLoadReached()
1117 if ($this->isBackend()) {
1118 $process = 'backend';
1119 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1120 if ($maxsysload < 1) {
1124 $process = 'frontend';
1125 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1126 if ($maxsysload < 1) {
1131 $load = Core\System::currentLoad();
1133 if (intval($load) > $maxsysload) {
1134 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1142 * Executes a child process with 'proc_open'
1144 * @param string $command The command to execute
1145 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1146 * @throws InternalServerErrorException
1148 public function proc_run($command, $args)
1150 if (!function_exists('proc_open')) {
1154 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1156 foreach ($args as $key => $value) {
1157 if (!is_null($value) && is_bool($value) && !$value) {
1161 $cmdline .= ' --' . $key;
1162 if (!is_null($value) && !is_bool($value)) {
1163 $cmdline .= ' ' . $value;
1167 if ($this->isMinMemoryReached()) {
1171 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1172 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1174 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1176 if (!is_resource($resource)) {
1177 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1180 proc_close($resource);
1184 * @brief Returns the system user that is executing the script
1186 * This mostly returns something like "www-data".
1188 * @return string system username
1190 private static function getSystemUser()
1192 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1196 $processUser = posix_getpwuid(posix_geteuid());
1197 return $processUser['name'];
1201 * @brief Checks if a given directory is usable for the system
1204 * @param bool $check_writable
1205 * @return boolean the directory is usable
1208 public static function isDirectoryUsable($directory, $check_writable = true)
1210 if ($directory == '') {
1211 Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1215 if (!file_exists($directory)) {
1216 Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1220 if (is_file($directory)) {
1221 Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1225 if (!is_dir($directory)) {
1226 Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1230 if ($check_writable && !is_writable($directory)) {
1231 Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1239 * @param string $cat Config category
1240 * @param string $k Config key
1241 * @param mixed $default Default value if it isn't set
1243 * @return string Returns the value of the Config entry
1245 public function getConfigValue($cat, $k, $default = null)
1249 if ($cat === 'config') {
1250 if (isset($this->config[$k])) {
1251 $return = $this->config[$k];
1254 if (isset($this->config[$cat][$k])) {
1255 $return = $this->config[$cat][$k];
1263 * Sets a default value in the config cache. Ignores already existing keys.
1265 * @param string $cat Config category
1266 * @param string $k Config key
1267 * @param mixed $v Default value to set
1269 private function setDefaultConfigValue($cat, $k, $v)
1271 if (!isset($this->config[$cat][$k])) {
1272 $this->setConfigValue($cat, $k, $v);
1277 * Sets a value in the config cache. Accepts raw output from the config table
1279 * @param string $cat Config category
1280 * @param string $k Config key
1281 * @param mixed $v Value to set
1283 public function setConfigValue($cat, $k, $v)
1285 // Only arrays are serialized in database, so we have to unserialize sparingly
1286 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1288 if ($cat === 'config') {
1289 $this->config[$k] = $value;
1291 if (!isset($this->config[$cat])) {
1292 $this->config[$cat] = [];
1295 $this->config[$cat][$k] = $value;
1300 * Deletes a value from the config cache
1302 * @param string $cat Config category
1303 * @param string $k Config key
1305 public function deleteConfigValue($cat, $k)
1307 if ($cat === 'config') {
1308 if (isset($this->config[$k])) {
1309 unset($this->config[$k]);
1312 if (isset($this->config[$cat][$k])) {
1313 unset($this->config[$cat][$k]);
1320 * Retrieves a value from the user config cache
1322 * @param int $uid User Id
1323 * @param string $cat Config category
1324 * @param string $k Config key
1325 * @param mixed $default Default value if key isn't set
1327 * @return string The value of the config entry
1329 public function getPConfigValue($uid, $cat, $k, $default = null)
1333 if (isset($this->config[$uid][$cat][$k])) {
1334 $return = $this->config[$uid][$cat][$k];
1341 * Sets a value in the user config cache
1343 * Accepts raw output from the pconfig table
1345 * @param int $uid User Id
1346 * @param string $cat Config category
1347 * @param string $k Config key
1348 * @param mixed $v Value to set
1350 public function setPConfigValue($uid, $cat, $k, $v)
1352 // Only arrays are serialized in database, so we have to unserialize sparingly
1353 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1355 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1356 $this->config[$uid] = [];
1359 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1360 $this->config[$uid][$cat] = [];
1363 $this->config[$uid][$cat][$k] = $value;
1367 * Deletes a value from the user config cache
1369 * @param int $uid User Id
1370 * @param string $cat Config category
1371 * @param string $k Config key
1373 public function deletePConfigValue($uid, $cat, $k)
1375 if (isset($this->config[$uid][$cat][$k])) {
1376 unset($this->config[$uid][$cat][$k]);
1381 * Generates the site's default sender email address
1384 * @throws InternalServerErrorException
1386 public function getSenderEmailAddress()
1388 $sender_email = Core\Config::get('config', 'sender_email');
1389 if (empty($sender_email)) {
1390 $hostname = $this->getHostName();
1391 if (strpos($hostname, ':')) {
1392 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1395 $sender_email = 'noreply@' . $hostname;
1398 return $sender_email;
1402 * Returns the current theme name.
1404 * @return string the name of the current theme
1405 * @throws InternalServerErrorException
1407 public function getCurrentTheme()
1409 if ($this->getMode()->isInstall()) {
1413 if (!$this->currentTheme) {
1414 $this->computeCurrentTheme();
1417 return $this->currentTheme;
1420 public function setCurrentTheme($theme)
1422 $this->currentTheme = $theme;
1426 * Computes the current theme name based on the node settings, the user settings and the device type
1430 private function computeCurrentTheme()
1432 $system_theme = Core\Config::get('system', 'theme');
1433 if (!$system_theme) {
1434 throw new Exception(Core\L10n::t('No system theme config value set.'));
1438 $this->currentTheme = $system_theme;
1440 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1443 // Find the theme that belongs to the user whose stuff we are looking at
1444 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1445 // Allow folks to override user themes and always use their own on their own site.
1446 // This works only if the user is on the same server
1447 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1448 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1449 $page_theme = $user['theme'];
1453 $user_theme = Core\Session::get('theme', $system_theme);
1455 // Specific mobile theme override
1456 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1457 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1458 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1460 // --- means same mobile theme as desktop
1461 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1462 $user_theme = $user_mobile_theme;
1467 $theme_name = $page_theme;
1469 $theme_name = $user_theme;
1473 && in_array($theme_name, $allowed_themes)
1474 && (file_exists('view/theme/' . $theme_name . '/style.css')
1475 || file_exists('view/theme/' . $theme_name . '/style.php'))
1477 $this->currentTheme = $theme_name;
1482 * @brief Return full URL to theme which is currently in effect.
1484 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1487 * @throws InternalServerErrorException
1489 public function getCurrentThemeStylesheetPath()
1491 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1495 * Check if request was an AJAX (xmlhttprequest) request.
1497 * @return boolean true if it was an AJAX request
1499 public function isAjax()
1501 return $this->isAjax;
1505 * Returns the value of a argv key
1506 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1508 * @param int $position the position of the argument
1509 * @param mixed $default the default value if not found
1511 * @return mixed returns the value of the argument
1513 public function getArgumentValue($position, $default = '')
1515 if (array_key_exists($position, $this->argv)) {
1516 return $this->argv[$position];
1523 * Sets the base url for use in cmdline programs which don't have
1524 * $_SERVER variables
1526 public function checkURL()
1528 $url = Core\Config::get('system', 'url');
1530 // if the url isn't set or the stored url is radically different
1531 // than the currently visited url, store the current value accordingly.
1532 // "Radically different" ignores common variations such as http vs https
1533 // and www.example.com vs example.com.
1534 // We will only change the url to an ip address if there is no existing setting
1536 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()))) {
1537 Core\Config::set('system', 'url', $this->getBaseURL());
1542 * Frontend App script
1544 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1545 * request and a representation of the response.
1547 * This probably should change to limit the size of this monster method.
1549 public function runFrontend()
1551 // Missing DB connection: ERROR
1552 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1553 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1556 // Max Load Average reached: ERROR
1557 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1558 header('Retry-After: 120');
1559 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1561 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1564 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1565 Core\System::httpExit(404);
1568 if (!$this->getMode()->isInstall()) {
1569 // Force SSL redirection
1570 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1571 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1572 && strpos($this->getBaseURL(), 'https://') === 0
1573 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1574 header('HTTP/1.1 302 Moved Temporarily');
1575 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1579 Core\Session::init();
1580 Core\Hook::callAll('init_1');
1583 // Exclude the backend processes from the session management
1584 if (!$this->isBackend()) {
1585 $stamp1 = microtime(true);
1587 $this->saveTimestamp($stamp1, 'parser');
1588 Core\L10n::setSessionVariable();
1589 Core\L10n::setLangFromSession();
1592 Core\Worker::executeIfIdle();
1596 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1597 $this->query_string = Model\Profile::stripZrls($this->query_string);
1598 if (!local_user()) {
1599 // Only continue when the given profile link seems valid
1600 // Valid profile links contain a path with "/profile/" and no query parameters
1601 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1602 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1603 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1604 $_SESSION['my_url'] = $_GET['zrl'];
1605 $_SESSION['authenticated'] = 0;
1607 Model\Profile::zrlInit($this);
1609 // Someone came with an invalid parameter, maybe as a DDoS attempt
1610 // We simply stop processing here
1611 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1612 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1617 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1618 $token = $_GET['owt'];
1619 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1620 Model\Profile::openWebAuthInit($token);
1623 Module\Login::sessionAuth();
1625 if (empty($_SESSION['authenticated'])) {
1626 header('X-Account-Management-Status: none');
1629 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1630 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1631 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1634 * check_config() is responsible for running update scripts. These automatically
1635 * update the DB schema whenever we push a new one out. It also checks to see if
1636 * any addons have been added or removed and reacts accordingly.
1639 // in install mode, any url loads install module
1640 // but we need "view" module for stylesheet
1641 if ($this->getMode()->isInstall() && $this->module != 'view') {
1642 $this->module = 'install';
1643 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1644 $this->module = 'maintenance';
1647 Core\Update::check(false);
1648 Core\Addon::loadAddons();
1649 Core\Hook::loadHooks();
1660 'right_aside' => '',
1665 if (strlen($this->module)) {
1666 // Compatibility with the Android Diaspora client
1667 if ($this->module == 'stream') {
1668 $this->internalRedirect('network?f=&order=post');
1671 if ($this->module == 'conversations') {
1672 $this->internalRedirect('message');
1675 if ($this->module == 'commented') {
1676 $this->internalRedirect('network?f=&order=comment');
1679 if ($this->module == 'liked') {
1680 $this->internalRedirect('network?f=&order=comment');
1683 if ($this->module == 'activity') {
1684 $this->internalRedirect('network/?f=&conv=1');
1687 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1688 $this->internalRedirect('bookmarklet');
1691 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1692 $this->internalRedirect('settings');
1695 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1696 $this->internalRedirect('search');
1699 // Compatibility with the Firefox App
1700 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1701 $this->module = "login";
1704 $privateapps = Core\Config::get('config', 'private_addons', false);
1705 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1706 //Check if module is an app and if public access to apps is allowed or not
1707 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1708 info(Core\L10n::t("You must be logged in to use addons. "));
1710 include_once "addon/{$this->module}/{$this->module}.php";
1711 if (function_exists($this->module . '_module')) {
1712 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1713 $this->module_class = 'Friendica\\LegacyModule';
1714 $this->module_loaded = true;
1719 // Controller class routing
1720 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1721 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1722 $this->module_loaded = true;
1725 /* If not, next look for a 'standard' program module in the 'mod' directory
1726 * We emulate a Module class through the LegacyModule class
1728 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1729 LegacyModule::setModuleFile("mod/{$this->module}.php");
1730 $this->module_class = 'Friendica\\LegacyModule';
1731 $this->module_loaded = true;
1734 /* The URL provided does not resolve to a valid module.
1736 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1737 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1738 * 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
1739 * this will often succeed and eventually do the right thing.
1741 * Otherwise we are going to emit a 404 not found.
1743 if (! $this->module_loaded) {
1744 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1745 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1749 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1750 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1751 $this->internalRedirect($_SERVER['REQUEST_URI']);
1754 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1756 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1757 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1758 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1759 '$message' => Core\L10n::t('Page not found.')
1766 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1767 if ($this->module_loaded) {
1768 $this->page['page_title'] = $this->module;
1771 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1773 call_user_func([$this->module_class, 'init']);
1775 // "rawContent" is especially meant for technical endpoints.
1776 // This endpoint doesn't need any theme initialization or other comparable stuff.
1777 if (!$this->error) {
1778 call_user_func([$this->module_class, 'rawContent']);
1782 // Load current theme info after module has been initialized as theme could have been set in module
1783 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1784 if (file_exists($theme_info_file)) {
1785 require_once $theme_info_file;
1788 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1789 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1793 if ($this->module_loaded) {
1794 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1795 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1796 call_user_func([$this->module_class, 'post']);
1799 if (! $this->error) {
1800 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1801 call_user_func([$this->module_class, 'afterpost']);
1804 if (! $this->error) {
1805 $arr = ['content' => $content];
1806 Core\Hook::callAll($this->module . '_mod_content', $arr);
1807 $content = $arr['content'];
1808 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1809 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1810 $content .= $arr['content'];
1814 // initialise content region
1815 if ($this->getMode()->isNormal()) {
1816 Core\Hook::callAll('page_content_top', $this->page['content']);
1819 $this->page['content'] .= $content;
1821 /* Create the page head after setting the language
1822 * and getting any auth credentials.
1824 * Moved initHead() and initFooter() to after
1825 * all the module functions have executed so that all
1826 * theme choices made by the modules can take effect.
1830 /* Build the page ending -- this is stuff that goes right before
1831 * the closing </body> tag
1833 $this->initFooter();
1835 /* now that we've been through the module content, see if the page reported
1836 * a permission problem and if so, a 403 response would seem to be in order.
1838 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1839 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1842 // Report anything which needs to be communicated in the notification area (before the main body)
1843 Core\Hook::callAll('page_end', $this->page['content']);
1845 // Add the navigation (menu) template
1846 if ($this->module != 'install' && $this->module != 'maintenance') {
1847 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1848 $this->page['nav'] = Content\Nav::build($this);
1851 // Build the page - now that we have all the components
1852 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1853 $doc = new DOMDocument();
1855 $target = new DOMDocument();
1856 $target->loadXML("<root></root>");
1858 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1860 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1861 @$doc->loadHTML($content);
1863 $xpath = new DOMXPath($doc);
1865 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1867 foreach ($list as $item) {
1868 $item = $target->importNode($item, true);
1870 // And then append it to the target
1871 $target->documentElement->appendChild($item);
1875 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1876 header("Content-type: text/html; charset=utf-8");
1878 echo substr($target->saveHTML(), 6, -8);
1883 $page = $this->page;
1884 $profile = $this->profile;
1886 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1887 header("Content-type: text/html; charset=utf-8");
1889 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1890 header("Strict-Transport-Security: max-age=31536000");
1893 // Some security stuff
1894 header('X-Content-Type-Options: nosniff');
1895 header('X-XSS-Protection: 1; mode=block');
1896 header('X-Permitted-Cross-Domain-Policies: none');
1897 header('X-Frame-Options: sameorigin');
1899 // Things like embedded OSM maps don't work, when this is enabled
1900 // 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'");
1902 /* We use $_GET["mode"] for special page templates. So we will check if we have
1903 * to load another page template than the default one.
1904 * The page templates are located in /view/php/ or in the theme directory.
1906 if (isset($_GET["mode"])) {
1907 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1910 // If there is no page template use the default page template
1911 if (empty($template)) {
1912 $template = Core\Theme::getPathForFile("default.php");
1915 // Theme templates expect $a as an App instance
1918 // Used as is in view/php/default.php
1919 $lang = Core\L10n::getCurrentLang();
1921 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1922 require_once $template;
1926 * Redirects to another module relative to the current Friendica base.
1927 * If you want to redirect to a external URL, use System::externalRedirectTo()
1929 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1930 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1932 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1934 public function internalRedirect($toUrl = '', $ssl = false)
1936 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1937 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1940 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1941 Core\System::externalRedirect($redirectTo);
1945 * Automatically redirects to relative or absolute URL
1946 * Should only be used if it isn't clear if the URL is either internal or external
1948 * @param string $toUrl The target URL
1949 * @throws InternalServerErrorException
1951 public function redirect($toUrl)
1953 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1954 Core\System::externalRedirect($toUrl);
1956 $this->internalRedirect($toUrl);