7 use Detection\MobileDetect;
11 use Friendica\Database\DBA;
12 use Friendica\Network\HTTPException\InternalServerErrorException;
14 require_once 'boot.php';
15 require_once 'include/text.php';
21 * @brief Our main application structure for the life of this page.
23 * Primarily deals with the URL that got us here
24 * and tries to make some sense of it, and
25 * stores our page contents and config storage
26 * and anything else that might need to be passed around
27 * before we spit the page out.
32 public $module_loaded = false;
33 public $module_class = null;
34 public $query_string = '';
46 public $error = false;
52 public $interactive = true;
54 public $is_mobile = false;
55 public $is_tablet = false;
56 public $performance = [];
57 public $callstack = [];
58 public $theme_info = [];
60 // Allow themes to control internal parameters
61 // by changing App values in theme.php
63 public $sourcename = '';
64 public $videowidth = 425;
65 public $videoheight = 350;
66 public $force_max_items = 0;
67 public $theme_events_in_profile = true;
69 public $stylesheets = [];
70 public $footerScripts = [];
73 * @var App\Mode The Mode of the Application
78 * @var string The App base path
83 * @var string The App URL path
88 * @var bool true, if the call is from the Friendica APP, otherwise false
90 private $isFriendicaApp;
93 * @var bool true, if the call is from an backend node (f.e. worker)
98 * @var string The name of the current theme
100 private $currentTheme;
103 * @var bool check if request was an AJAX (xmlhttprequest) request
108 * Register a stylesheet file path to be included in the <head> tag of every page.
109 * Inclusion is done in App->initHead().
110 * The path can be absolute or relative to the Friendica installation base folder.
114 * @param string $path
116 public function registerStylesheet($path)
118 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
120 $this->stylesheets[] = trim($url, '/');
124 * Register a javascript file path to be included in the <footer> tag of every page.
125 * Inclusion is done in App->initFooter().
126 * The path can be absolute or relative to the Friendica installation base folder.
130 * @param string $path
132 public function registerFooterScript($path)
134 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
136 $this->footerScripts[] = trim($url, '/');
140 * @brief An array for all theme-controllable parameters
142 * Mostly unimplemented yet. Only options 'template_engine' and
148 'videoheight' => 350,
149 'force_max_items' => 0,
151 'template_engine' => 'smarty3',
155 * @brief An array of registered template engines ('name'=>'class name')
157 public $template_engines = [];
160 * @brief An array of instanced template engines ('name'=>'instance')
162 public $template_engine_instance = [];
177 * @brief App constructor.
179 * @param string $basePath Path to the app base folder
180 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
182 * @throws Exception if the Basepath is not usable
184 public function __construct($basePath, $isBackend = true)
186 if (!static::isDirectoryUsable($basePath, false)) {
187 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
190 BaseObject::setApp($this);
192 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
193 $this->checkBackend($isBackend);
194 $this->checkFriendicaApp();
196 $this->performance['start'] = microtime(true);
197 $this->performance['database'] = 0;
198 $this->performance['database_write'] = 0;
199 $this->performance['cache'] = 0;
200 $this->performance['cache_write'] = 0;
201 $this->performance['network'] = 0;
202 $this->performance['file'] = 0;
203 $this->performance['rendering'] = 0;
204 $this->performance['parser'] = 0;
205 $this->performance['marktime'] = 0;
206 $this->performance['markstart'] = microtime(true);
208 $this->callstack['database'] = [];
209 $this->callstack['database_write'] = [];
210 $this->callstack['cache'] = [];
211 $this->callstack['cache_write'] = [];
212 $this->callstack['network'] = [];
213 $this->callstack['file'] = [];
214 $this->callstack['rendering'] = [];
215 $this->callstack['parser'] = [];
217 $this->mode = new App\Mode($basePath);
223 // This has to be quite large to deal with embedded private photos
224 ini_set('pcre.backtrack_limit', 500000);
226 $this->scheme = 'http';
228 if (!empty($_SERVER['HTTPS']) ||
229 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
230 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
231 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
232 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
233 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
235 $this->scheme = 'https';
238 if (!empty($_SERVER['SERVER_NAME'])) {
239 $this->hostname = $_SERVER['SERVER_NAME'];
241 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
242 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
247 get_include_path() . PATH_SEPARATOR
248 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
249 . $this->getBasePath(). DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
250 . $this->getBasePath());
252 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
253 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
254 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
255 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
258 // removing trailing / - maybe a nginx problem
259 $this->query_string = ltrim($this->query_string, '/');
261 if (!empty($_GET['pagename'])) {
262 $this->cmd = trim($_GET['pagename'], '/\\');
263 } elseif (!empty($_GET['q'])) {
264 $this->cmd = trim($_GET['q'], '/\\');
268 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
270 // unix style "homedir"
271 if (substr($this->cmd, 0, 1) === '~') {
272 $this->cmd = 'profile/' . substr($this->cmd, 1);
275 // Diaspora style profile url
276 if (substr($this->cmd, 0, 2) === 'u/') {
277 $this->cmd = 'profile/' . substr($this->cmd, 2);
281 * Break the URL path into C style argc/argv style arguments for our
282 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
283 * will be 3 (integer) and $this->argv will contain:
289 * There will always be one argument. If provided a naked domain
290 * URL, $this->argv[0] is set to "home".
293 $this->argv = explode('/', $this->cmd);
294 $this->argc = count($this->argv);
295 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
296 $this->module = str_replace('.', '_', $this->argv[0]);
297 $this->module = str_replace('-', '_', $this->module);
300 $this->argv = ['home'];
301 $this->module = 'home';
304 // Detect mobile devices
305 $mobile_detect = new MobileDetect();
306 $this->is_mobile = $mobile_detect->isMobile();
307 $this->is_tablet = $mobile_detect->isTablet();
309 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
311 // Register template engines
312 $this->registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
316 * Returns the Mode of the Application
318 * @return App\Mode The Application Mode
320 * @throws InternalServerErrorException when the mode isn't created
322 public function getMode()
324 if (empty($this->mode)) {
325 throw new InternalServerErrorException('Mode of the Application is not defined');
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');
361 * Load the configuration files
363 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
364 * expected local.ini.php
366 private function loadConfigFiles()
368 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
369 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
371 // Legacy .htconfig.php support
372 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
374 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
377 // Legacy .htconfig.php support
378 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php')) {
381 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php';
383 $this->setConfigValue('database', 'hostname', $db_host);
384 $this->setConfigValue('database', 'username', $db_user);
385 $this->setConfigValue('database', 'password', $db_pass);
386 $this->setConfigValue('database', 'database', $db_data);
387 if (isset($a->config['system']['db_charset'])) {
388 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
391 unset($db_host, $db_user, $db_pass, $db_data);
393 if (isset($default_timezone)) {
394 $this->setConfigValue('system', 'default_timezone', $default_timezone);
395 unset($default_timezone);
398 if (isset($pidfile)) {
399 $this->setConfigValue('system', 'pidfile', $pidfile);
404 $this->setConfigValue('system', 'language', $lang);
409 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
410 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
415 * Tries to load the specified configuration file into the App->config array.
416 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
418 * The config format is INI and the template for configuration files is the following:
420 * <?php return <<<INI
428 * @param string $filepath
429 * @param bool $overwrite Force value overwrite if the config key already exists
432 public function loadConfigFile($filepath, $overwrite = false)
434 if (!file_exists($filepath)) {
435 throw new Exception('Error parsing non-existent config file ' . $filepath);
438 $contents = include($filepath);
440 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
442 if ($config === false) {
443 throw new Exception('Error parsing config file ' . $filepath);
446 foreach ($config as $category => $values) {
447 foreach ($values as $key => $value) {
449 $this->setConfigValue($category, $key, $value);
451 $this->setDefaultConfigValue($category, $key, $value);
458 * Loads addons configuration files
460 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
461 * again to overwrite potential local addon configuration.
463 private function loadAddonConfig()
465 // Loads addons default config
466 Core\Addon::callHooks('load_config');
468 // Load the local addon config file to overwritten default addon config values
469 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
470 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
475 * Loads the default timezone
477 * Include support for legacy $default_timezone
479 * @global string $default_timezone
481 private function loadDefaultTimezone()
483 if ($this->getConfigValue('system', 'default_timezone')) {
484 $this->timezone = $this->getConfigValue('system', 'default_timezone');
486 global $default_timezone;
487 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
490 if ($this->timezone) {
491 date_default_timezone_set($this->timezone);
496 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
498 private function determineURLPath()
500 /* Relative script path to the web server root
501 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
503 $relative_script_path = '';
504 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
505 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
506 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
507 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
509 $this->urlPath = $this->getConfigValue('system', 'urlpath');
511 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
512 * QUERY_STRING gives pagename=module/parameter
514 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
516 if (!empty($relative_script_path)) {
518 if (!empty($_SERVER['QUERY_STRING'])) {
519 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
522 $path = trim($relative_script_path, '/');
525 if ($path && $path != $this->urlPath) {
526 $this->urlPath = $path;
531 public function loadDatabase()
533 if (DBA::connected()) {
537 $db_host = $this->getConfigValue('database', 'hostname');
538 $db_user = $this->getConfigValue('database', 'username');
539 $db_pass = $this->getConfigValue('database', 'password');
540 $db_data = $this->getConfigValue('database', 'database');
541 $charset = $this->getConfigValue('database', 'charset');
543 // Use environment variables for mysql if they are set beforehand
544 if (!empty(getenv('MYSQL_HOST'))
545 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
546 && getenv('MYSQL_PASSWORD') !== false
547 && !empty(getenv('MYSQL_DATABASE')))
549 $db_host = getenv('MYSQL_HOST');
550 if (!empty(getenv('MYSQL_PORT'))) {
551 $db_host .= ':' . getenv('MYSQL_PORT');
553 if (!empty(getenv('MYSQL_USERNAME'))) {
554 $db_user = getenv('MYSQL_USERNAME');
556 $db_user = getenv('MYSQL_USER');
558 $db_pass = (string) getenv('MYSQL_PASSWORD');
559 $db_data = getenv('MYSQL_DATABASE');
562 $stamp1 = microtime(true);
564 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
565 // Loads DB_UPDATE_VERSION constant
566 Database\DBStructure::definition(false);
569 unset($db_host, $db_user, $db_pass, $db_data, $charset);
571 $this->saveTimestamp($stamp1, 'network');
575 * @brief Returns the base filesystem path of the App
577 * It first checks for the internal variable, then for DOCUMENT_ROOT and
582 public function getBasePath()
584 $basepath = $this->basePath;
587 $basepath = Core\Config::get('system', 'basepath');
590 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
591 $basepath = $_SERVER['DOCUMENT_ROOT'];
594 if (!$basepath && !empty($_SERVER['PWD'])) {
595 $basepath = $_SERVER['PWD'];
598 return self::getRealPath($basepath);
602 * @brief Returns a normalized file path
604 * This is a wrapper for the "realpath" function.
605 * That function cannot detect the real path when some folders aren't readable.
606 * Since this could happen with some hosters we need to handle this.
608 * @param string $path The path that is about to be normalized
609 * @return string normalized path - when possible
611 public static function getRealPath($path)
613 $normalized = realpath($path);
615 if (!is_bool($normalized)) {
622 public function getScheme()
624 return $this->scheme;
628 * @brief Retrieves the Friendica instance base URL
630 * This function assembles the base URL from multiple parts:
631 * - Protocol is determined either by the request or a combination of
632 * system.ssl_policy and the $ssl parameter.
633 * - Host name is determined either by system.hostname or inferred from request
634 * - Path is inferred from SCRIPT_NAME
636 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
638 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
639 * @return string Friendica server base URL
641 public function getBaseURL($ssl = false)
643 $scheme = $this->scheme;
645 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
649 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
650 // (and also the login link). Anything seen by an outsider will have it turned off.
652 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
660 if (Core\Config::get('config', 'hostname') != '') {
661 $this->hostname = Core\Config::get('config', 'hostname');
664 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
668 * @brief Initializes the baseurl components
670 * Clears the baseurl cache to prevent inconsistencies
674 public function setBaseURL($url)
676 $parsed = @parse_url($url);
679 if (!empty($parsed)) {
680 if (!empty($parsed['scheme'])) {
681 $this->scheme = $parsed['scheme'];
684 if (!empty($parsed['host'])) {
685 $hostname = $parsed['host'];
688 if (!empty($parsed['port'])) {
689 $hostname .= ':' . $parsed['port'];
691 if (!empty($parsed['path'])) {
692 $this->urlPath = trim($parsed['path'], '\\/');
695 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
696 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
699 if (Core\Config::get('config', 'hostname') != '') {
700 $this->hostname = Core\Config::get('config', 'hostname');
703 if (!isset($this->hostname) || ($this->hostname == '')) {
704 $this->hostname = $hostname;
709 public function getHostName()
711 if (Core\Config::get('config', 'hostname') != '') {
712 $this->hostname = Core\Config::get('config', 'hostname');
715 return $this->hostname;
718 public function getURLPath()
720 return $this->urlPath;
724 * Initializes App->page['htmlhead'].
729 * - Registered stylesheets (through App->registerStylesheet())
730 * - Infinite scroll data
731 * - head.tpl template
733 public function initHead()
735 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
737 // If the update is 'deactivated' set it to the highest integer number (~24 days)
739 $interval = 2147483647;
742 if ($interval < 10000) {
746 // compose the page title from the sitename and the
747 // current module called
748 if (!$this->module == '') {
749 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
751 $this->page['title'] = $this->config['sitename'];
754 if (!empty($this->theme['stylesheet'])) {
755 $stylesheet = $this->theme['stylesheet'];
757 $stylesheet = $this->getCurrentThemeStylesheetPath();
760 $this->registerStylesheet($stylesheet);
762 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
763 if ($shortcut_icon == '') {
764 $shortcut_icon = 'images/friendica-32.png';
767 $touch_icon = Core\Config::get('system', 'touch_icon');
768 if ($touch_icon == '') {
769 $touch_icon = 'images/friendica-128.png';
772 Core\Addon::callHooks('head', $this->page['htmlhead']);
774 $tpl = get_markup_template('head.tpl');
775 /* put the head template at the beginning of page['htmlhead']
776 * since the code added by the modules frequently depends on it
779 $this->page['htmlhead'] = replace_macros($tpl, [
780 '$baseurl' => $this->getBaseURL(),
781 '$local_user' => local_user(),
782 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
783 '$delitem' => Core\L10n::t('Delete this item?'),
784 '$showmore' => Core\L10n::t('show more'),
785 '$showfewer' => Core\L10n::t('show fewer'),
786 '$update_interval' => $interval,
787 '$shortcut_icon' => $shortcut_icon,
788 '$touch_icon' => $touch_icon,
789 '$block_public' => intval(Core\Config::get('system', 'block_public')),
790 '$stylesheets' => $this->stylesheets,
791 ]) . $this->page['htmlhead'];
795 * Initializes App->page['footer'].
798 * - Javascript homebase
799 * - Mobile toggle link
800 * - Registered footer scripts (through App->registerFooterScript())
801 * - footer.tpl template
803 public function initFooter()
805 // If you're just visiting, let javascript take you home
806 if (!empty($_SESSION['visitor_home'])) {
807 $homebase = $_SESSION['visitor_home'];
808 } elseif (local_user()) {
809 $homebase = 'profile/' . $this->user['nickname'];
812 if (isset($homebase)) {
813 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
817 * Add a "toggle mobile" link if we're using a mobile device
819 if ($this->is_mobile || $this->is_tablet) {
820 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
821 $link = 'toggle_mobile?address=' . curPageURL();
823 $link = 'toggle_mobile?off=1&address=' . curPageURL();
825 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
826 '$toggle_link' => $link,
827 '$toggle_text' => Core\L10n::t('toggle mobile')
831 Core\Addon::callHooks('footer', $this->page['footer']);
833 $tpl = get_markup_template('footer.tpl');
834 $this->page['footer'] = replace_macros($tpl, [
835 '$baseurl' => $this->getBaseURL(),
836 '$footerScripts' => $this->footerScripts,
837 ]) . $this->page['footer'];
841 * @brief Removes the base url from an url. This avoids some mixed content problems.
843 * @param string $origURL
845 * @return string The cleaned url
847 public function removeBaseURL($origURL)
849 // Remove the hostname from the url if it is an internal link
850 $nurl = normalise_link($origURL);
851 $base = normalise_link($this->getBaseURL());
852 $url = str_replace($base . '/', '', $nurl);
854 // if it is an external link return the orignal value
855 if ($url == normalise_link($origURL)) {
863 * @brief Register template engine class
865 * @param string $class
867 private function registerTemplateEngine($class)
869 $v = get_class_vars($class);
870 if (!empty($v['name'])) {
872 $this->template_engines[$name] = $class;
874 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
880 * @brief Return template engine instance.
882 * If $name is not defined, return engine defined by theme,
885 * @return object Template Engine instance
887 public function getTemplateEngine()
889 $template_engine = defaults($this->theme, 'template_engine', 'smarty3');
891 if (isset($this->template_engines[$template_engine])) {
892 if (isset($this->template_engine_instance[$template_engine])) {
893 return $this->template_engine_instance[$template_engine];
895 $class = $this->template_engines[$template_engine];
897 $this->template_engine_instance[$template_engine] = $obj;
902 echo "template engine <tt>$template_engine</tt> is not registered!\n";
907 * @brief Returns the active template engine.
909 * @return string the active template engine
911 public function getActiveTemplateEngine()
913 return $this->theme['template_engine'];
917 * sets the active template engine
919 * @param string $engine the template engine (default is Smarty3)
921 public function setActiveTemplateEngine($engine = 'smarty3')
923 $this->theme['template_engine'] = $engine;
927 * Gets the right delimiter for a template engine
933 * @param string $engine The template engine (default is Smarty3)
935 * @return string the right delimiter
937 public function getTemplateLeftDelimiter($engine = 'smarty3')
939 return $this->ldelim[$engine];
943 * Gets the left delimiter for a template engine
949 * @param string $engine The template engine (default is Smarty3)
951 * @return string the left delimiter
953 public function getTemplateRightDelimiter($engine = 'smarty3')
955 return $this->rdelim[$engine];
959 * Saves a timestamp for a value - f.e. a call
960 * Necessary for profiling Friendica
962 * @param int $timestamp the Timestamp
963 * @param string $value A value to profile
965 public function saveTimestamp($timestamp, $value)
967 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
971 $duration = (float) (microtime(true) - $timestamp);
973 if (!isset($this->performance[$value])) {
974 // Prevent ugly E_NOTICE
975 $this->performance[$value] = 0;
978 $this->performance[$value] += (float) $duration;
979 $this->performance['marktime'] += (float) $duration;
981 $callstack = Core\System::callstack();
983 if (!isset($this->callstack[$value][$callstack])) {
984 // Prevent ugly E_NOTICE
985 $this->callstack[$value][$callstack] = 0;
988 $this->callstack[$value][$callstack] += (float) $duration;
992 * Returns the current UserAgent as a String
994 * @return string the UserAgent as a String
996 public function getUserAgent()
999 FRIENDICA_PLATFORM . " '" .
1000 FRIENDICA_CODENAME . "' " .
1001 FRIENDICA_VERSION . '-' .
1002 DB_UPDATE_VERSION . '; ' .
1003 $this->getBaseURL();
1007 * Checks, if the call is from the Friendica App
1010 * The friendica client has problems with the GUID in the notify. this is some workaround
1012 private function checkFriendicaApp()
1015 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1019 * Is the call via the Friendica app? (not a "normale" call)
1021 * @return bool true if it's from the Friendica app
1023 public function isFriendicaApp()
1025 return $this->isFriendicaApp;
1029 * @brief Checks if the site is called via a backend process
1031 * This isn't a perfect solution. But we need this check very early.
1032 * So we cannot wait until the modules are loaded.
1034 * @param string $backend true, if the backend flag was set during App initialization
1037 private function checkBackend($backend) {
1038 static $backends = [
1060 // Check if current module is in backend or backend flag is set
1061 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1065 * Returns true, if the call is from a backend node (f.e. from a worker)
1067 * @return bool Is it a known backend?
1069 public function isBackend()
1071 return $this->isBackend;
1075 * @brief Checks if the maximum number of database processes is reached
1077 * @return bool Is the limit reached?
1079 public function isMaxProcessesReached()
1081 // Deactivated, needs more investigating if this check really makes sense
1085 * Commented out to suppress static analyzer issues
1087 if ($this->is_backend()) {
1088 $process = 'backend';
1089 $max_processes = Core\Config::get('system', 'max_processes_backend');
1090 if (intval($max_processes) == 0) {
1094 $process = 'frontend';
1095 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1096 if (intval($max_processes) == 0) {
1097 $max_processes = 20;
1101 $processlist = DBA::processlist();
1102 if ($processlist['list'] != '') {
1103 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1105 if ($processlist['amount'] > $max_processes) {
1106 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1115 * @brief Checks if the minimal memory is reached
1117 * @return bool Is the memory limit reached?
1119 public function isMinMemoryReached()
1121 $min_memory = Core\Config::get('system', 'min_memory', 0);
1122 if ($min_memory == 0) {
1126 if (!is_readable('/proc/meminfo')) {
1130 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1133 foreach ($memdata as $line) {
1134 $data = explode(':', $line);
1135 if (count($data) != 2) {
1138 list($key, $val) = $data;
1139 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1140 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1143 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1147 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1149 $reached = ($free < $min_memory);
1152 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1159 * @brief Checks if the maximum load is reached
1161 * @return bool Is the load reached?
1163 public function isMaxLoadReached()
1165 if ($this->isBackend()) {
1166 $process = 'backend';
1167 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1168 if ($maxsysload < 1) {
1172 $process = 'frontend';
1173 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1174 if ($maxsysload < 1) {
1179 $load = Core\System::currentLoad();
1181 if (intval($load) > $maxsysload) {
1182 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1190 * Executes a child process with 'proc_open'
1192 * @param string $command The command to execute
1193 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1195 public function proc_run($command, $args)
1197 if (!function_exists('proc_open')) {
1201 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1203 foreach ($args as $key => $value) {
1204 if (!is_null($value) && is_bool($value) && !$value) {
1208 $cmdline .= ' --' . $key;
1209 if (!is_null($value) && !is_bool($value)) {
1210 $cmdline .= ' ' . $value;
1214 if ($this->isMinMemoryReached()) {
1218 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1219 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1221 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1223 if (!is_resource($resource)) {
1224 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1227 proc_close($resource);
1231 * @brief Returns the system user that is executing the script
1233 * This mostly returns something like "www-data".
1235 * @return string system username
1237 private static function getSystemUser()
1239 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1243 $processUser = posix_getpwuid(posix_geteuid());
1244 return $processUser['name'];
1248 * @brief Checks if a given directory is usable for the system
1250 * @return boolean the directory is usable
1252 public static function isDirectoryUsable($directory, $check_writable = true)
1254 if ($directory == '') {
1255 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1259 if (!file_exists($directory)) {
1260 logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1264 if (is_file($directory)) {
1265 logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1269 if (!is_dir($directory)) {
1270 logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1274 if ($check_writable && !is_writable($directory)) {
1275 logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1283 * @param string $cat Config category
1284 * @param string $k Config key
1285 * @param mixed $default Default value if it isn't set
1287 * @return string Returns the value of the Config entry
1289 public function getConfigValue($cat, $k, $default = null)
1293 if ($cat === 'config') {
1294 if (isset($this->config[$k])) {
1295 $return = $this->config[$k];
1298 if (isset($this->config[$cat][$k])) {
1299 $return = $this->config[$cat][$k];
1307 * Sets a default value in the config cache. Ignores already existing keys.
1309 * @param string $cat Config category
1310 * @param string $k Config key
1311 * @param mixed $v Default value to set
1313 private function setDefaultConfigValue($cat, $k, $v)
1315 if (!isset($this->config[$cat][$k])) {
1316 $this->setConfigValue($cat, $k, $v);
1321 * Sets a value in the config cache. Accepts raw output from the config table
1323 * @param string $cat Config category
1324 * @param string $k Config key
1325 * @param mixed $v Value to set
1327 public function setConfigValue($cat, $k, $v)
1329 // Only arrays are serialized in database, so we have to unserialize sparingly
1330 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1332 if ($cat === 'config') {
1333 $this->config[$k] = $value;
1335 if (!isset($this->config[$cat])) {
1336 $this->config[$cat] = [];
1339 $this->config[$cat][$k] = $value;
1344 * Deletes a value from the config cache
1346 * @param string $cat Config category
1347 * @param string $k Config key
1349 public function deleteConfigValue($cat, $k)
1351 if ($cat === 'config') {
1352 if (isset($this->config[$k])) {
1353 unset($this->config[$k]);
1356 if (isset($this->config[$cat][$k])) {
1357 unset($this->config[$cat][$k]);
1364 * Retrieves a value from the user config cache
1366 * @param int $uid User Id
1367 * @param string $cat Config category
1368 * @param string $k Config key
1369 * @param mixed $default Default value if key isn't set
1371 * @return string The value of the config entry
1373 public function getPConfigValue($uid, $cat, $k, $default = null)
1377 if (isset($this->config[$uid][$cat][$k])) {
1378 $return = $this->config[$uid][$cat][$k];
1385 * Sets a value in the user config cache
1387 * Accepts raw output from the pconfig table
1389 * @param int $uid User Id
1390 * @param string $cat Config category
1391 * @param string $k Config key
1392 * @param mixed $v Value to set
1394 public function setPConfigValue($uid, $cat, $k, $v)
1396 // Only arrays are serialized in database, so we have to unserialize sparingly
1397 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1399 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1400 $this->config[$uid] = [];
1403 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1404 $this->config[$uid][$cat] = [];
1407 $this->config[$uid][$cat][$k] = $value;
1411 * Deletes a value from the user config cache
1413 * @param int $uid User Id
1414 * @param string $cat Config category
1415 * @param string $k Config key
1417 public function deletePConfigValue($uid, $cat, $k)
1419 if (isset($this->config[$uid][$cat][$k])) {
1420 unset($this->config[$uid][$cat][$k]);
1425 * Generates the site's default sender email address
1429 public function getSenderEmailAddress()
1431 $sender_email = Core\Config::get('config', 'sender_email');
1432 if (empty($sender_email)) {
1433 $hostname = $this->getHostName();
1434 if (strpos($hostname, ':')) {
1435 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1438 $sender_email = 'noreply@' . $hostname;
1441 return $sender_email;
1445 * Returns the current theme name.
1447 * @return string the name of the current theme
1449 public function getCurrentTheme()
1451 if ($this->getMode()->isInstall()) {
1455 //// @TODO Compute the current theme only once (this behavior has
1456 /// already been implemented, but it didn't work well -
1457 /// https://github.com/friendica/friendica/issues/5092)
1458 $this->computeCurrentTheme();
1460 return $this->currentTheme;
1464 * Computes the current theme name based on the node settings, the user settings and the device type
1468 private function computeCurrentTheme()
1470 $system_theme = Core\Config::get('system', 'theme');
1471 if (!$system_theme) {
1472 throw new Exception(Core\L10n::t('No system theme config value set.'));
1476 $this->currentTheme = $system_theme;
1478 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1481 // Find the theme that belongs to the user whose stuff we are looking at
1482 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1483 // Allow folks to override user themes and always use their own on their own site.
1484 // This works only if the user is on the same server
1485 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1486 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1487 $page_theme = $user['theme'];
1491 $user_theme = Core\Session::get('theme', $system_theme);
1493 // Specific mobile theme override
1494 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1495 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1496 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1498 // --- means same mobile theme as desktop
1499 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1500 $user_theme = $user_mobile_theme;
1505 $theme_name = $page_theme;
1507 $theme_name = $user_theme;
1511 && in_array($theme_name, $allowed_themes)
1512 && (file_exists('view/theme/' . $theme_name . '/style.css')
1513 || file_exists('view/theme/' . $theme_name . '/style.php'))
1515 $this->currentTheme = $theme_name;
1520 * @brief Return full URL to theme which is currently in effect.
1522 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1526 public function getCurrentThemeStylesheetPath()
1528 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1532 * Check if request was an AJAX (xmlhttprequest) request.
1534 * @return boolean true if it was an AJAX request
1536 public function isAjax()
1538 return $this->isAjax;
1542 * Returns the value of a argv key
1543 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1545 * @param int $position the position of the argument
1546 * @param mixed $default the default value if not found
1548 * @return mixed returns the value of the argument
1550 public function getArgumentValue($position, $default = '')
1552 if (array_key_exists($position, $this->argv)) {
1553 return $this->argv[$position];
1560 * Sets the base url for use in cmdline programs which don't have
1561 * $_SERVER variables
1563 public function checkURL()
1565 $url = Core\Config::get('system', 'url');
1567 // if the url isn't set or the stored url is radically different
1568 // than the currently visited url, store the current value accordingly.
1569 // "Radically different" ignores common variations such as http vs https
1570 // and www.example.com vs example.com.
1571 // We will only change the url to an ip address if there is no existing setting
1573 if (empty($url) || (!link_compare($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1574 Core\Config::set('system', 'url', $this->getBaseURL());
1579 * Frontend App script
1581 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1582 * request and a representation of the response.
1584 * This probably should change to limit the size of this monster method.
1586 public function runFrontend()
1588 // Missing DB connection: ERROR
1589 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1590 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1593 // Max Load Average reached: ERROR
1594 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1595 header('Retry-After: 120');
1596 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1598 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1601 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1602 Core\System::httpExit(404);
1605 if (!$this->getMode()->isInstall()) {
1606 // Force SSL redirection
1607 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1608 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1609 && strpos($this->getBaseURL(), 'https://') === 0
1610 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1611 header('HTTP/1.1 302 Moved Temporarily');
1612 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1616 Core\Session::init();
1617 Core\Addon::callHooks('init_1');
1620 // Exclude the backend processes from the session management
1621 if (!$this->isBackend()) {
1622 $stamp1 = microtime(true);
1624 $this->saveTimestamp($stamp1, 'parser');
1625 Core\L10n::setSessionVariable();
1626 Core\L10n::setLangFromSession();
1629 Core\Worker::executeIfIdle();
1633 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1634 $this->query_string = Model\Profile::stripZrls($this->query_string);
1635 if (!local_user()) {
1636 // Only continue when the given profile link seems valid
1637 // Valid profile links contain a path with "/profile/" and no query parameters
1638 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1639 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1640 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1641 $_SESSION['my_url'] = $_GET['zrl'];
1642 $_SESSION['authenticated'] = 0;
1644 Model\Profile::zrlInit($this);
1646 // Someone came with an invalid parameter, maybe as a DDoS attempt
1647 // We simply stop processing here
1648 logger("Invalid ZRL parameter " . $_GET['zrl'], LOGGER_DEBUG);
1649 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1654 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1655 $token = $_GET['owt'];
1656 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1657 Model\Profile::openWebAuthInit($token);
1660 Module\Login::sessionAuth();
1662 if (empty($_SESSION['authenticated'])) {
1663 header('X-Account-Management-Status: none');
1666 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1667 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1668 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1671 * check_config() is responsible for running update scripts. These automatically
1672 * update the DB schema whenever we push a new one out. It also checks to see if
1673 * any addons have been added or removed and reacts accordingly.
1676 // in install mode, any url loads install module
1677 // but we need "view" module for stylesheet
1678 if ($this->getMode()->isInstall() && $this->module != 'view') {
1679 $this->module = 'install';
1680 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1681 $this->module = 'maintenance';
1685 Core\Addon::loadAddons();
1686 Core\Hook::loadHooks();
1697 'right_aside' => '',
1702 if (strlen($this->module)) {
1703 // Compatibility with the Android Diaspora client
1704 if ($this->module == 'stream') {
1705 $this->internalRedirect('network?f=&order=post');
1708 if ($this->module == 'conversations') {
1709 $this->internalRedirect('message');
1712 if ($this->module == 'commented') {
1713 $this->internalRedirect('network?f=&order=comment');
1716 if ($this->module == 'liked') {
1717 $this->internalRedirect('network?f=&order=comment');
1720 if ($this->module == 'activity') {
1721 $this->internalRedirect('network/?f=&conv=1');
1724 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1725 $this->internalRedirect('bookmarklet');
1728 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1729 $this->internalRedirect('settings');
1732 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1733 $this->internalRedirect('search');
1736 // Compatibility with the Firefox App
1737 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1738 $this->module = "login";
1741 $privateapps = Core\Config::get('config', 'private_addons', false);
1742 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1743 //Check if module is an app and if public access to apps is allowed or not
1744 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1745 info(Core\L10n::t("You must be logged in to use addons. "));
1747 include_once "addon/{$this->module}/{$this->module}.php";
1748 if (function_exists($this->module . '_module')) {
1749 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1750 $this->module_class = 'Friendica\\LegacyModule';
1751 $this->module_loaded = true;
1756 // Controller class routing
1757 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1758 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1759 $this->module_loaded = true;
1762 /* If not, next look for a 'standard' program module in the 'mod' directory
1763 * We emulate a Module class through the LegacyModule class
1765 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1766 LegacyModule::setModuleFile("mod/{$this->module}.php");
1767 $this->module_class = 'Friendica\\LegacyModule';
1768 $this->module_loaded = true;
1771 /* The URL provided does not resolve to a valid module.
1773 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1774 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1775 * 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
1776 * this will often succeed and eventually do the right thing.
1778 * Otherwise we are going to emit a 404 not found.
1780 if (! $this->module_loaded) {
1781 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1782 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1786 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1787 logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1788 $this->internalRedirect($_SERVER['REQUEST_URI']);
1791 logger('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], LOGGER_DEBUG);
1793 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1794 $tpl = get_markup_template("404.tpl");
1795 $this->page['content'] = replace_macros($tpl, [
1796 '$message' => Core\L10n::t('Page not found.')
1801 // Load current theme info
1802 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1803 if (file_exists($theme_info_file)) {
1804 require_once $theme_info_file;
1807 // initialise content region
1808 if ($this->getMode()->isNormal()) {
1809 Core\Addon::callHooks('page_content_top', $this->page['content']);
1812 // Call module functions
1813 if ($this->module_loaded) {
1814 $this->page['page_title'] = $this->module;
1817 Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1819 call_user_func([$this->module_class, 'init']);
1821 // "rawContent" is especially meant for technical endpoints.
1822 // This endpoint doesn't need any theme initialization or other comparable stuff.
1823 if (!$this->error) {
1824 call_user_func([$this->module_class, 'rawContent']);
1827 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1828 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1832 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1833 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1834 call_user_func([$this->module_class, 'post']);
1837 if (! $this->error) {
1838 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1839 call_user_func([$this->module_class, 'afterpost']);
1842 if (! $this->error) {
1843 $arr = ['content' => $this->page['content']];
1844 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1845 $this->page['content'] = $arr['content'];
1846 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1847 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1848 $this->page['content'] .= $arr['content'];
1851 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded')) {
1852 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded';
1857 /* Create the page head after setting the language
1858 * and getting any auth credentials.
1860 * Moved initHead() and initFooter() to after
1861 * all the module functions have executed so that all
1862 * theme choices made by the modules can take effect.
1866 /* Build the page ending -- this is stuff that goes right before
1867 * the closing </body> tag
1869 $this->initFooter();
1871 /* now that we've been through the module content, see if the page reported
1872 * a permission problem and if so, a 403 response would seem to be in order.
1874 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1875 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1878 // Report anything which needs to be communicated in the notification area (before the main body)
1879 Core\Addon::callHooks('page_end', $this->page['content']);
1881 // Add the navigation (menu) template
1882 if ($this->module != 'install' && $this->module != 'maintenance') {
1883 $this->page['htmlhead'] .= replace_macros(get_markup_template('nav_head.tpl'), []);
1884 $this->page['nav'] = Content\Nav::build($this);
1887 // Build the page - now that we have all the components
1888 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1889 $doc = new DOMDocument();
1891 $target = new DOMDocument();
1892 $target->loadXML("<root></root>");
1894 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1896 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1897 @$doc->loadHTML($content);
1899 $xpath = new DOMXPath($doc);
1901 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1903 foreach ($list as $item) {
1904 $item = $target->importNode($item, true);
1906 // And then append it to the target
1907 $target->documentElement->appendChild($item);
1911 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1912 header("Content-type: text/html; charset=utf-8");
1914 echo substr($target->saveHTML(), 6, -8);
1919 $page = $this->page;
1920 $profile = $this->profile;
1922 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1923 header("Content-type: text/html; charset=utf-8");
1925 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1926 header("Strict-Transport-Security: max-age=31536000");
1929 // Some security stuff
1930 header('X-Content-Type-Options: nosniff');
1931 header('X-XSS-Protection: 1; mode=block');
1932 header('X-Permitted-Cross-Domain-Policies: none');
1933 header('X-Frame-Options: sameorigin');
1935 // Things like embedded OSM maps don't work, when this is enabled
1936 // 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'");
1938 /* We use $_GET["mode"] for special page templates. So we will check if we have
1939 * to load another page template than the default one.
1940 * The page templates are located in /view/php/ or in the theme directory.
1942 if (isset($_GET["mode"])) {
1943 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1946 // If there is no page template use the default page template
1947 if (empty($template)) {
1948 $template = Core\Theme::getPathForFile("default.php");
1951 // Theme templates expect $a as an App instance
1954 // Used as is in view/php/default.php
1955 $lang = Core\L10n::getCurrentLang();
1957 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1958 require_once $template;
1962 * Redirects to another module relative to the current Friendica base.
1963 * If you want to redirect to a external URL, use System::externalRedirectTo()
1965 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1966 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1968 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1970 public function internalRedirect($toUrl = '', $ssl = false)
1972 if (filter_var($toUrl, FILTER_VALIDATE_URL)) {
1973 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1976 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1977 Core\System::externalRedirect($redirectTo);
1981 * Automatically redirects to relative or absolute URL
1982 * Should only be used if it isn't clear if the URL is either internal or external
1984 * @param string $toUrl The target URL
1987 public function redirect($toUrl)
1989 if (filter_var($toUrl, FILTER_VALIDATE_URL)) {
1990 Core\System::externalRedirect($toUrl);
1992 $this->internalRedirect($toUrl);