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);
508 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
510 $this->urlPath = $this->getConfigValue('system', 'urlpath');
512 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
513 * QUERY_STRING gives pagename=module/parameter
515 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
517 if (!empty($relative_script_path)) {
519 if (!empty($_SERVER['QUERY_STRING'])) {
520 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
523 $path = trim($relative_script_path, '/');
526 if ($path && $path != $this->urlPath) {
527 $this->urlPath = $path;
532 public function loadDatabase()
534 if (DBA::connected()) {
538 $db_host = $this->getConfigValue('database', 'hostname');
539 $db_user = $this->getConfigValue('database', 'username');
540 $db_pass = $this->getConfigValue('database', 'password');
541 $db_data = $this->getConfigValue('database', 'database');
542 $charset = $this->getConfigValue('database', 'charset');
544 // Use environment variables for mysql if they are set beforehand
545 if (!empty(getenv('MYSQL_HOST'))
546 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
547 && getenv('MYSQL_PASSWORD') !== false
548 && !empty(getenv('MYSQL_DATABASE')))
550 $db_host = getenv('MYSQL_HOST');
551 if (!empty(getenv('MYSQL_PORT'))) {
552 $db_host .= ':' . getenv('MYSQL_PORT');
554 if (!empty(getenv('MYSQL_USERNAME'))) {
555 $db_user = getenv('MYSQL_USERNAME');
557 $db_user = getenv('MYSQL_USER');
559 $db_pass = (string) getenv('MYSQL_PASSWORD');
560 $db_data = getenv('MYSQL_DATABASE');
563 $stamp1 = microtime(true);
565 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
566 // Loads DB_UPDATE_VERSION constant
567 Database\DBStructure::definition(false);
570 unset($db_host, $db_user, $db_pass, $db_data, $charset);
572 $this->saveTimestamp($stamp1, 'network');
576 * @brief Returns the base filesystem path of the App
578 * It first checks for the internal variable, then for DOCUMENT_ROOT and
583 public function getBasePath()
585 $basepath = $this->basePath;
588 $basepath = Core\Config::get('system', 'basepath');
591 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
592 $basepath = $_SERVER['DOCUMENT_ROOT'];
595 if (!$basepath && !empty($_SERVER['PWD'])) {
596 $basepath = $_SERVER['PWD'];
599 return self::getRealPath($basepath);
603 * @brief Returns a normalized file path
605 * This is a wrapper for the "realpath" function.
606 * That function cannot detect the real path when some folders aren't readable.
607 * Since this could happen with some hosters we need to handle this.
609 * @param string $path The path that is about to be normalized
610 * @return string normalized path - when possible
612 public static function getRealPath($path)
614 $normalized = realpath($path);
616 if (!is_bool($normalized)) {
623 public function getScheme()
625 return $this->scheme;
629 * @brief Retrieves the Friendica instance base URL
631 * This function assembles the base URL from multiple parts:
632 * - Protocol is determined either by the request or a combination of
633 * system.ssl_policy and the $ssl parameter.
634 * - Host name is determined either by system.hostname or inferred from request
635 * - Path is inferred from SCRIPT_NAME
637 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
639 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
640 * @return string Friendica server base URL
642 public function getBaseURL($ssl = false)
644 $scheme = $this->scheme;
646 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
650 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
651 // (and also the login link). Anything seen by an outsider will have it turned off.
653 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
661 if (Core\Config::get('config', 'hostname') != '') {
662 $this->hostname = Core\Config::get('config', 'hostname');
665 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
669 * @brief Initializes the baseurl components
671 * Clears the baseurl cache to prevent inconsistencies
675 public function setBaseURL($url)
677 $parsed = @parse_url($url);
680 if (!empty($parsed)) {
681 if (!empty($parsed['scheme'])) {
682 $this->scheme = $parsed['scheme'];
685 if (!empty($parsed['host'])) {
686 $hostname = $parsed['host'];
689 if (!empty($parsed['port'])) {
690 $hostname .= ':' . $parsed['port'];
692 if (!empty($parsed['path'])) {
693 $this->urlPath = trim($parsed['path'], '\\/');
696 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
697 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
700 if (Core\Config::get('config', 'hostname') != '') {
701 $this->hostname = Core\Config::get('config', 'hostname');
704 if (!isset($this->hostname) || ($this->hostname == '')) {
705 $this->hostname = $hostname;
710 public function getHostName()
712 if (Core\Config::get('config', 'hostname') != '') {
713 $this->hostname = Core\Config::get('config', 'hostname');
716 return $this->hostname;
719 public function getURLPath()
721 return $this->urlPath;
725 * Initializes App->page['htmlhead'].
730 * - Registered stylesheets (through App->registerStylesheet())
731 * - Infinite scroll data
732 * - head.tpl template
734 public function initHead()
736 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
738 // If the update is 'deactivated' set it to the highest integer number (~24 days)
740 $interval = 2147483647;
743 if ($interval < 10000) {
747 // compose the page title from the sitename and the
748 // current module called
749 if (!$this->module == '') {
750 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
752 $this->page['title'] = $this->config['sitename'];
755 if (!empty($this->theme['stylesheet'])) {
756 $stylesheet = $this->theme['stylesheet'];
758 $stylesheet = $this->getCurrentThemeStylesheetPath();
761 $this->registerStylesheet($stylesheet);
763 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
764 if ($shortcut_icon == '') {
765 $shortcut_icon = 'images/friendica-32.png';
768 $touch_icon = Core\Config::get('system', 'touch_icon');
769 if ($touch_icon == '') {
770 $touch_icon = 'images/friendica-128.png';
773 Core\Addon::callHooks('head', $this->page['htmlhead']);
775 $tpl = get_markup_template('head.tpl');
776 /* put the head template at the beginning of page['htmlhead']
777 * since the code added by the modules frequently depends on it
780 $this->page['htmlhead'] = replace_macros($tpl, [
781 '$baseurl' => $this->getBaseURL(),
782 '$local_user' => local_user(),
783 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
784 '$delitem' => Core\L10n::t('Delete this item?'),
785 '$showmore' => Core\L10n::t('show more'),
786 '$showfewer' => Core\L10n::t('show fewer'),
787 '$update_interval' => $interval,
788 '$shortcut_icon' => $shortcut_icon,
789 '$touch_icon' => $touch_icon,
790 '$block_public' => intval(Core\Config::get('system', 'block_public')),
791 '$stylesheets' => $this->stylesheets,
792 ]) . $this->page['htmlhead'];
796 * Initializes App->page['footer'].
799 * - Javascript homebase
800 * - Mobile toggle link
801 * - Registered footer scripts (through App->registerFooterScript())
802 * - footer.tpl template
804 public function initFooter()
806 // If you're just visiting, let javascript take you home
807 if (!empty($_SESSION['visitor_home'])) {
808 $homebase = $_SESSION['visitor_home'];
809 } elseif (local_user()) {
810 $homebase = 'profile/' . $this->user['nickname'];
813 if (isset($homebase)) {
814 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
818 * Add a "toggle mobile" link if we're using a mobile device
820 if ($this->is_mobile || $this->is_tablet) {
821 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
822 $link = 'toggle_mobile?address=' . curPageURL();
824 $link = 'toggle_mobile?off=1&address=' . curPageURL();
826 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
827 '$toggle_link' => $link,
828 '$toggle_text' => Core\L10n::t('toggle mobile')
832 Core\Addon::callHooks('footer', $this->page['footer']);
834 $tpl = get_markup_template('footer.tpl');
835 $this->page['footer'] = replace_macros($tpl, [
836 '$baseurl' => $this->getBaseURL(),
837 '$footerScripts' => $this->footerScripts,
838 ]) . $this->page['footer'];
842 * @brief Removes the base url from an url. This avoids some mixed content problems.
844 * @param string $origURL
846 * @return string The cleaned url
848 public function removeBaseURL($origURL)
850 // Remove the hostname from the url if it is an internal link
851 $nurl = normalise_link($origURL);
852 $base = normalise_link($this->getBaseURL());
853 $url = str_replace($base . '/', '', $nurl);
855 // if it is an external link return the orignal value
856 if ($url == normalise_link($origURL)) {
864 * @brief Register template engine class
866 * @param string $class
868 private function registerTemplateEngine($class)
870 $v = get_class_vars($class);
871 if (!empty($v['name'])) {
873 $this->template_engines[$name] = $class;
875 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
881 * @brief Return template engine instance.
883 * If $name is not defined, return engine defined by theme,
886 * @return object Template Engine instance
888 public function getTemplateEngine()
890 $template_engine = defaults($this->theme, 'template_engine', 'smarty3');
892 if (isset($this->template_engines[$template_engine])) {
893 if (isset($this->template_engine_instance[$template_engine])) {
894 return $this->template_engine_instance[$template_engine];
896 $class = $this->template_engines[$template_engine];
898 $this->template_engine_instance[$template_engine] = $obj;
903 echo "template engine <tt>$template_engine</tt> is not registered!\n";
908 * @brief Returns the active template engine.
910 * @return string the active template engine
912 public function getActiveTemplateEngine()
914 return $this->theme['template_engine'];
918 * sets the active template engine
920 * @param string $engine the template engine (default is Smarty3)
922 public function setActiveTemplateEngine($engine = 'smarty3')
924 $this->theme['template_engine'] = $engine;
928 * Gets the right delimiter for a template engine
934 * @param string $engine The template engine (default is Smarty3)
936 * @return string the right delimiter
938 public function getTemplateLeftDelimiter($engine = 'smarty3')
940 return $this->ldelim[$engine];
944 * Gets the left delimiter for a template engine
950 * @param string $engine The template engine (default is Smarty3)
952 * @return string the left delimiter
954 public function getTemplateRightDelimiter($engine = 'smarty3')
956 return $this->rdelim[$engine];
960 * Saves a timestamp for a value - f.e. a call
961 * Necessary for profiling Friendica
963 * @param int $timestamp the Timestamp
964 * @param string $value A value to profile
966 public function saveTimestamp($timestamp, $value)
968 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
972 $duration = (float) (microtime(true) - $timestamp);
974 if (!isset($this->performance[$value])) {
975 // Prevent ugly E_NOTICE
976 $this->performance[$value] = 0;
979 $this->performance[$value] += (float) $duration;
980 $this->performance['marktime'] += (float) $duration;
982 $callstack = Core\System::callstack();
984 if (!isset($this->callstack[$value][$callstack])) {
985 // Prevent ugly E_NOTICE
986 $this->callstack[$value][$callstack] = 0;
989 $this->callstack[$value][$callstack] += (float) $duration;
993 * Returns the current UserAgent as a String
995 * @return string the UserAgent as a String
997 public function getUserAgent()
1000 FRIENDICA_PLATFORM . " '" .
1001 FRIENDICA_CODENAME . "' " .
1002 FRIENDICA_VERSION . '-' .
1003 DB_UPDATE_VERSION . '; ' .
1004 $this->getBaseURL();
1008 * Checks, if the call is from the Friendica App
1011 * The friendica client has problems with the GUID in the notify. this is some workaround
1013 private function checkFriendicaApp()
1016 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1020 * Is the call via the Friendica app? (not a "normale" call)
1022 * @return bool true if it's from the Friendica app
1024 public function isFriendicaApp()
1026 return $this->isFriendicaApp;
1030 * @brief Checks if the site is called via a backend process
1032 * This isn't a perfect solution. But we need this check very early.
1033 * So we cannot wait until the modules are loaded.
1035 * @param string $backend true, if the backend flag was set during App initialization
1038 private function checkBackend($backend) {
1039 static $backends = [
1061 // Check if current module is in backend or backend flag is set
1062 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1066 * Returns true, if the call is from a backend node (f.e. from a worker)
1068 * @return bool Is it a known backend?
1070 public function isBackend()
1072 return $this->isBackend;
1076 * @brief Checks if the maximum number of database processes is reached
1078 * @return bool Is the limit reached?
1080 public function isMaxProcessesReached()
1082 // Deactivated, needs more investigating if this check really makes sense
1086 * Commented out to suppress static analyzer issues
1088 if ($this->is_backend()) {
1089 $process = 'backend';
1090 $max_processes = Core\Config::get('system', 'max_processes_backend');
1091 if (intval($max_processes) == 0) {
1095 $process = 'frontend';
1096 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1097 if (intval($max_processes) == 0) {
1098 $max_processes = 20;
1102 $processlist = DBA::processlist();
1103 if ($processlist['list'] != '') {
1104 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
1106 if ($processlist['amount'] > $max_processes) {
1107 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
1116 * @brief Checks if the minimal memory is reached
1118 * @return bool Is the memory limit reached?
1120 public function isMinMemoryReached()
1122 $min_memory = Core\Config::get('system', 'min_memory', 0);
1123 if ($min_memory == 0) {
1127 if (!is_readable('/proc/meminfo')) {
1131 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1134 foreach ($memdata as $line) {
1135 $data = explode(':', $line);
1136 if (count($data) != 2) {
1139 list($key, $val) = $data;
1140 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1141 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1144 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1148 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1150 $reached = ($free < $min_memory);
1153 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1160 * @brief Checks if the maximum load is reached
1162 * @return bool Is the load reached?
1164 public function isMaxLoadReached()
1166 if ($this->isBackend()) {
1167 $process = 'backend';
1168 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1169 if ($maxsysload < 1) {
1173 $process = 'frontend';
1174 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1175 if ($maxsysload < 1) {
1180 $load = Core\System::currentLoad();
1182 if (intval($load) > $maxsysload) {
1183 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1191 * Executes a child process with 'proc_open'
1193 * @param string $command The command to execute
1194 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1196 public function proc_run($command, $args)
1198 if (!function_exists('proc_open')) {
1202 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1204 foreach ($args as $key => $value) {
1205 if (!is_null($value) && is_bool($value) && !$value) {
1209 $cmdline .= ' --' . $key;
1210 if (!is_null($value) && !is_bool($value)) {
1211 $cmdline .= ' ' . $value;
1215 if ($this->isMinMemoryReached()) {
1219 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1220 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1222 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1224 if (!is_resource($resource)) {
1225 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1228 proc_close($resource);
1232 * @brief Returns the system user that is executing the script
1234 * This mostly returns something like "www-data".
1236 * @return string system username
1238 private static function getSystemUser()
1240 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1244 $processUser = posix_getpwuid(posix_geteuid());
1245 return $processUser['name'];
1249 * @brief Checks if a given directory is usable for the system
1251 * @return boolean the directory is usable
1253 public static function isDirectoryUsable($directory, $check_writable = true)
1255 if ($directory == '') {
1256 Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1260 if (!file_exists($directory)) {
1261 Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1265 if (is_file($directory)) {
1266 Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1270 if (!is_dir($directory)) {
1271 Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1275 if ($check_writable && !is_writable($directory)) {
1276 Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1284 * @param string $cat Config category
1285 * @param string $k Config key
1286 * @param mixed $default Default value if it isn't set
1288 * @return string Returns the value of the Config entry
1290 public function getConfigValue($cat, $k, $default = null)
1294 if ($cat === 'config') {
1295 if (isset($this->config[$k])) {
1296 $return = $this->config[$k];
1299 if (isset($this->config[$cat][$k])) {
1300 $return = $this->config[$cat][$k];
1308 * Sets a default value in the config cache. Ignores already existing keys.
1310 * @param string $cat Config category
1311 * @param string $k Config key
1312 * @param mixed $v Default value to set
1314 private function setDefaultConfigValue($cat, $k, $v)
1316 if (!isset($this->config[$cat][$k])) {
1317 $this->setConfigValue($cat, $k, $v);
1322 * Sets a value in the config cache. Accepts raw output from the config table
1324 * @param string $cat Config category
1325 * @param string $k Config key
1326 * @param mixed $v Value to set
1328 public function setConfigValue($cat, $k, $v)
1330 // Only arrays are serialized in database, so we have to unserialize sparingly
1331 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1333 if ($cat === 'config') {
1334 $this->config[$k] = $value;
1336 if (!isset($this->config[$cat])) {
1337 $this->config[$cat] = [];
1340 $this->config[$cat][$k] = $value;
1345 * Deletes a value from the config cache
1347 * @param string $cat Config category
1348 * @param string $k Config key
1350 public function deleteConfigValue($cat, $k)
1352 if ($cat === 'config') {
1353 if (isset($this->config[$k])) {
1354 unset($this->config[$k]);
1357 if (isset($this->config[$cat][$k])) {
1358 unset($this->config[$cat][$k]);
1365 * Retrieves a value from the user config cache
1367 * @param int $uid User Id
1368 * @param string $cat Config category
1369 * @param string $k Config key
1370 * @param mixed $default Default value if key isn't set
1372 * @return string The value of the config entry
1374 public function getPConfigValue($uid, $cat, $k, $default = null)
1378 if (isset($this->config[$uid][$cat][$k])) {
1379 $return = $this->config[$uid][$cat][$k];
1386 * Sets a value in the user config cache
1388 * Accepts raw output from the pconfig table
1390 * @param int $uid User Id
1391 * @param string $cat Config category
1392 * @param string $k Config key
1393 * @param mixed $v Value to set
1395 public function setPConfigValue($uid, $cat, $k, $v)
1397 // Only arrays are serialized in database, so we have to unserialize sparingly
1398 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1400 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1401 $this->config[$uid] = [];
1404 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1405 $this->config[$uid][$cat] = [];
1408 $this->config[$uid][$cat][$k] = $value;
1412 * Deletes a value from the user config cache
1414 * @param int $uid User Id
1415 * @param string $cat Config category
1416 * @param string $k Config key
1418 public function deletePConfigValue($uid, $cat, $k)
1420 if (isset($this->config[$uid][$cat][$k])) {
1421 unset($this->config[$uid][$cat][$k]);
1426 * Generates the site's default sender email address
1430 public function getSenderEmailAddress()
1432 $sender_email = Core\Config::get('config', 'sender_email');
1433 if (empty($sender_email)) {
1434 $hostname = $this->getHostName();
1435 if (strpos($hostname, ':')) {
1436 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1439 $sender_email = 'noreply@' . $hostname;
1442 return $sender_email;
1446 * Returns the current theme name.
1448 * @return string the name of the current theme
1450 public function getCurrentTheme()
1452 if ($this->getMode()->isInstall()) {
1456 //// @TODO Compute the current theme only once (this behavior has
1457 /// already been implemented, but it didn't work well -
1458 /// https://github.com/friendica/friendica/issues/5092)
1459 $this->computeCurrentTheme();
1461 return $this->currentTheme;
1465 * Computes the current theme name based on the node settings, the user settings and the device type
1469 private function computeCurrentTheme()
1471 $system_theme = Core\Config::get('system', 'theme');
1472 if (!$system_theme) {
1473 throw new Exception(Core\L10n::t('No system theme config value set.'));
1477 $this->currentTheme = $system_theme;
1479 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1482 // Find the theme that belongs to the user whose stuff we are looking at
1483 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1484 // Allow folks to override user themes and always use their own on their own site.
1485 // This works only if the user is on the same server
1486 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1487 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1488 $page_theme = $user['theme'];
1492 $user_theme = Core\Session::get('theme', $system_theme);
1494 // Specific mobile theme override
1495 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1496 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1497 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1499 // --- means same mobile theme as desktop
1500 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1501 $user_theme = $user_mobile_theme;
1506 $theme_name = $page_theme;
1508 $theme_name = $user_theme;
1512 && in_array($theme_name, $allowed_themes)
1513 && (file_exists('view/theme/' . $theme_name . '/style.css')
1514 || file_exists('view/theme/' . $theme_name . '/style.php'))
1516 $this->currentTheme = $theme_name;
1521 * @brief Return full URL to theme which is currently in effect.
1523 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1527 public function getCurrentThemeStylesheetPath()
1529 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1533 * Check if request was an AJAX (xmlhttprequest) request.
1535 * @return boolean true if it was an AJAX request
1537 public function isAjax()
1539 return $this->isAjax;
1543 * Returns the value of a argv key
1544 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1546 * @param int $position the position of the argument
1547 * @param mixed $default the default value if not found
1549 * @return mixed returns the value of the argument
1551 public function getArgumentValue($position, $default = '')
1553 if (array_key_exists($position, $this->argv)) {
1554 return $this->argv[$position];
1561 * Sets the base url for use in cmdline programs which don't have
1562 * $_SERVER variables
1564 public function checkURL()
1566 $url = Core\Config::get('system', 'url');
1568 // if the url isn't set or the stored url is radically different
1569 // than the currently visited url, store the current value accordingly.
1570 // "Radically different" ignores common variations such as http vs https
1571 // and www.example.com vs example.com.
1572 // We will only change the url to an ip address if there is no existing setting
1574 if (empty($url) || (!link_compare($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1575 Core\Config::set('system', 'url', $this->getBaseURL());
1580 * Frontend App script
1582 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1583 * request and a representation of the response.
1585 * This probably should change to limit the size of this monster method.
1587 public function runFrontend()
1589 // Missing DB connection: ERROR
1590 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1591 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1594 // Max Load Average reached: ERROR
1595 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1596 header('Retry-After: 120');
1597 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1599 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1602 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1603 Core\System::httpExit(404);
1606 if (!$this->getMode()->isInstall()) {
1607 // Force SSL redirection
1608 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1609 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1610 && strpos($this->getBaseURL(), 'https://') === 0
1611 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1612 header('HTTP/1.1 302 Moved Temporarily');
1613 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1617 Core\Session::init();
1618 Core\Addon::callHooks('init_1');
1621 // Exclude the backend processes from the session management
1622 if (!$this->isBackend()) {
1623 $stamp1 = microtime(true);
1625 $this->saveTimestamp($stamp1, 'parser');
1626 Core\L10n::setSessionVariable();
1627 Core\L10n::setLangFromSession();
1630 Core\Worker::executeIfIdle();
1634 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1635 $this->query_string = Model\Profile::stripZrls($this->query_string);
1636 if (!local_user()) {
1637 // Only continue when the given profile link seems valid
1638 // Valid profile links contain a path with "/profile/" and no query parameters
1639 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1640 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1641 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1642 $_SESSION['my_url'] = $_GET['zrl'];
1643 $_SESSION['authenticated'] = 0;
1645 Model\Profile::zrlInit($this);
1647 // Someone came with an invalid parameter, maybe as a DDoS attempt
1648 // We simply stop processing here
1649 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1650 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1655 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1656 $token = $_GET['owt'];
1657 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1658 Model\Profile::openWebAuthInit($token);
1661 Module\Login::sessionAuth();
1663 if (empty($_SESSION['authenticated'])) {
1664 header('X-Account-Management-Status: none');
1667 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1668 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1669 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1672 * check_config() is responsible for running update scripts. These automatically
1673 * update the DB schema whenever we push a new one out. It also checks to see if
1674 * any addons have been added or removed and reacts accordingly.
1677 // in install mode, any url loads install module
1678 // but we need "view" module for stylesheet
1679 if ($this->getMode()->isInstall() && $this->module != 'view') {
1680 $this->module = 'install';
1681 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1682 $this->module = 'maintenance';
1685 Core\Update::check(false);
1686 Core\Addon::loadAddons();
1687 Core\Hook::loadHooks();
1698 'right_aside' => '',
1703 if (strlen($this->module)) {
1704 // Compatibility with the Android Diaspora client
1705 if ($this->module == 'stream') {
1706 $this->internalRedirect('network?f=&order=post');
1709 if ($this->module == 'conversations') {
1710 $this->internalRedirect('message');
1713 if ($this->module == 'commented') {
1714 $this->internalRedirect('network?f=&order=comment');
1717 if ($this->module == 'liked') {
1718 $this->internalRedirect('network?f=&order=comment');
1721 if ($this->module == 'activity') {
1722 $this->internalRedirect('network/?f=&conv=1');
1725 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1726 $this->internalRedirect('bookmarklet');
1729 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1730 $this->internalRedirect('settings');
1733 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1734 $this->internalRedirect('search');
1737 // Compatibility with the Firefox App
1738 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1739 $this->module = "login";
1742 $privateapps = Core\Config::get('config', 'private_addons', false);
1743 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1744 //Check if module is an app and if public access to apps is allowed or not
1745 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1746 info(Core\L10n::t("You must be logged in to use addons. "));
1748 include_once "addon/{$this->module}/{$this->module}.php";
1749 if (function_exists($this->module . '_module')) {
1750 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1751 $this->module_class = 'Friendica\\LegacyModule';
1752 $this->module_loaded = true;
1757 // Controller class routing
1758 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1759 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1760 $this->module_loaded = true;
1763 /* If not, next look for a 'standard' program module in the 'mod' directory
1764 * We emulate a Module class through the LegacyModule class
1766 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1767 LegacyModule::setModuleFile("mod/{$this->module}.php");
1768 $this->module_class = 'Friendica\\LegacyModule';
1769 $this->module_loaded = true;
1772 /* The URL provided does not resolve to a valid module.
1774 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1775 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1776 * 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
1777 * this will often succeed and eventually do the right thing.
1779 * Otherwise we are going to emit a 404 not found.
1781 if (! $this->module_loaded) {
1782 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1783 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1787 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1788 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1789 $this->internalRedirect($_SERVER['REQUEST_URI']);
1792 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1794 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1795 $tpl = get_markup_template("404.tpl");
1796 $this->page['content'] = replace_macros($tpl, [
1797 '$message' => Core\L10n::t('Page not found.')
1802 // Load current theme info
1803 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1804 if (file_exists($theme_info_file)) {
1805 require_once $theme_info_file;
1808 // initialise content region
1809 if ($this->getMode()->isNormal()) {
1810 Core\Addon::callHooks('page_content_top', $this->page['content']);
1813 // Call module functions
1814 if ($this->module_loaded) {
1815 $this->page['page_title'] = $this->module;
1818 Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1820 call_user_func([$this->module_class, 'init']);
1822 // "rawContent" is especially meant for technical endpoints.
1823 // This endpoint doesn't need any theme initialization or other comparable stuff.
1824 if (!$this->error) {
1825 call_user_func([$this->module_class, 'rawContent']);
1828 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1829 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1833 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1834 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1835 call_user_func([$this->module_class, 'post']);
1838 if (! $this->error) {
1839 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1840 call_user_func([$this->module_class, 'afterpost']);
1843 if (! $this->error) {
1844 $arr = ['content' => $this->page['content']];
1845 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1846 $this->page['content'] = $arr['content'];
1847 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1848 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1849 $this->page['content'] .= $arr['content'];
1852 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded')) {
1853 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded';
1858 /* Create the page head after setting the language
1859 * and getting any auth credentials.
1861 * Moved initHead() and initFooter() to after
1862 * all the module functions have executed so that all
1863 * theme choices made by the modules can take effect.
1867 /* Build the page ending -- this is stuff that goes right before
1868 * the closing </body> tag
1870 $this->initFooter();
1872 /* now that we've been through the module content, see if the page reported
1873 * a permission problem and if so, a 403 response would seem to be in order.
1875 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1876 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1879 // Report anything which needs to be communicated in the notification area (before the main body)
1880 Core\Addon::callHooks('page_end', $this->page['content']);
1882 // Add the navigation (menu) template
1883 if ($this->module != 'install' && $this->module != 'maintenance') {
1884 $this->page['htmlhead'] .= replace_macros(get_markup_template('nav_head.tpl'), []);
1885 $this->page['nav'] = Content\Nav::build($this);
1888 // Build the page - now that we have all the components
1889 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1890 $doc = new DOMDocument();
1892 $target = new DOMDocument();
1893 $target->loadXML("<root></root>");
1895 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1897 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1898 @$doc->loadHTML($content);
1900 $xpath = new DOMXPath($doc);
1902 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1904 foreach ($list as $item) {
1905 $item = $target->importNode($item, true);
1907 // And then append it to the target
1908 $target->documentElement->appendChild($item);
1912 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1913 header("Content-type: text/html; charset=utf-8");
1915 echo substr($target->saveHTML(), 6, -8);
1920 $page = $this->page;
1921 $profile = $this->profile;
1923 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1924 header("Content-type: text/html; charset=utf-8");
1926 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1927 header("Strict-Transport-Security: max-age=31536000");
1930 // Some security stuff
1931 header('X-Content-Type-Options: nosniff');
1932 header('X-XSS-Protection: 1; mode=block');
1933 header('X-Permitted-Cross-Domain-Policies: none');
1934 header('X-Frame-Options: sameorigin');
1936 // Things like embedded OSM maps don't work, when this is enabled
1937 // 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'");
1939 /* We use $_GET["mode"] for special page templates. So we will check if we have
1940 * to load another page template than the default one.
1941 * The page templates are located in /view/php/ or in the theme directory.
1943 if (isset($_GET["mode"])) {
1944 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1947 // If there is no page template use the default page template
1948 if (empty($template)) {
1949 $template = Core\Theme::getPathForFile("default.php");
1952 // Theme templates expect $a as an App instance
1955 // Used as is in view/php/default.php
1956 $lang = Core\L10n::getCurrentLang();
1958 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1959 require_once $template;
1963 * Redirects to another module relative to the current Friendica base.
1964 * If you want to redirect to a external URL, use System::externalRedirectTo()
1966 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1967 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1969 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1971 public function internalRedirect($toUrl = '', $ssl = false)
1973 if (filter_var($toUrl, FILTER_VALIDATE_URL)) {
1974 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1977 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1978 Core\System::externalRedirect($redirectTo);
1982 * Automatically redirects to relative or absolute URL
1983 * Should only be used if it isn't clear if the URL is either internal or external
1985 * @param string $toUrl The target URL
1988 public function redirect($toUrl)
1990 if (filter_var($toUrl, FILTER_VALIDATE_URL)) {
1991 Core\System::externalRedirect($toUrl);
1993 $this->internalRedirect($toUrl);