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 = '';
48 public $error = false;
55 public $interactive = true;
57 public $addons_admin = [];
60 public $is_mobile = false;
61 public $is_tablet = false;
62 public $performance = [];
63 public $callstack = [];
64 public $theme_info = [];
67 // Allow themes to control internal parameters
68 // by changing App values in theme.php
70 public $sourcename = '';
71 public $videowidth = 425;
72 public $videoheight = 350;
73 public $force_max_items = 0;
74 public $theme_events_in_profile = true;
76 public $stylesheets = [];
77 public $footerScripts = [];
80 * @var App\Mode The Mode of the Application
85 * @var string The App base path
90 * @var string The App URL path
95 * @var bool true, if the call is from the Friendica APP, otherwise false
97 private $isFriendicaApp;
100 * @var bool true, if the call is from an backend node (f.e. worker)
105 * @var string The name of the current theme
107 private $currentTheme;
110 * @var bool check if request was an AJAX (xmlhttprequest) request
115 * Register a stylesheet file path to be included in the <head> tag of every page.
116 * Inclusion is done in App->initHead().
117 * The path can be absolute or relative to the Friendica installation base folder.
121 * @param string $path
123 public function registerStylesheet($path)
125 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
127 $this->stylesheets[] = trim($url, '/');
131 * Register a javascript file path to be included in the <footer> tag of every page.
132 * Inclusion is done in App->initFooter().
133 * The path can be absolute or relative to the Friendica installation base folder.
137 * @param string $path
139 public function registerFooterScript($path)
141 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
143 $this->footerScripts[] = trim($url, '/');
147 * @brief An array for all theme-controllable parameters
149 * Mostly unimplemented yet. Only options 'template_engine' and
155 'videoheight' => 350,
156 'force_max_items' => 0,
158 'template_engine' => 'smarty3',
162 * @brief An array of registered template engines ('name'=>'class name')
164 public $template_engines = [];
167 * @brief An array of instanced template engines ('name'=>'instance')
169 public $template_engine_instance = [];
184 * @brief App constructor.
186 * @param string $basePath Path to the app base folder
187 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
189 * @throws Exception if the Basepath is not usable
191 public function __construct($basePath, $isBackend = true)
193 if (!static::isDirectoryUsable($basePath, false)) {
194 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
197 BaseObject::setApp($this);
199 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
200 $this->checkBackend($isBackend);
201 $this->checkFriendicaApp();
203 $this->performance['start'] = microtime(true);
204 $this->performance['database'] = 0;
205 $this->performance['database_write'] = 0;
206 $this->performance['cache'] = 0;
207 $this->performance['cache_write'] = 0;
208 $this->performance['network'] = 0;
209 $this->performance['file'] = 0;
210 $this->performance['rendering'] = 0;
211 $this->performance['parser'] = 0;
212 $this->performance['marktime'] = 0;
213 $this->performance['markstart'] = microtime(true);
215 $this->callstack['database'] = [];
216 $this->callstack['database_write'] = [];
217 $this->callstack['cache'] = [];
218 $this->callstack['cache_write'] = [];
219 $this->callstack['network'] = [];
220 $this->callstack['file'] = [];
221 $this->callstack['rendering'] = [];
222 $this->callstack['parser'] = [];
224 $this->mode = new App\Mode($basePath);
230 // This has to be quite large to deal with embedded private photos
231 ini_set('pcre.backtrack_limit', 500000);
233 $this->scheme = 'http';
235 if (!empty($_SERVER['HTTPS']) ||
236 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
237 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
238 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
239 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
240 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
242 $this->scheme = 'https';
245 if (!empty($_SERVER['SERVER_NAME'])) {
246 $this->hostname = $_SERVER['SERVER_NAME'];
248 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
249 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
254 get_include_path() . PATH_SEPARATOR
255 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
256 . $this->getBasePath(). DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
257 . $this->getBasePath());
259 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
260 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
261 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
262 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
265 // removing trailing / - maybe a nginx problem
266 $this->query_string = ltrim($this->query_string, '/');
268 if (!empty($_GET['pagename'])) {
269 $this->cmd = trim($_GET['pagename'], '/\\');
270 } elseif (!empty($_GET['q'])) {
271 $this->cmd = trim($_GET['q'], '/\\');
275 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
277 // unix style "homedir"
278 if (substr($this->cmd, 0, 1) === '~') {
279 $this->cmd = 'profile/' . substr($this->cmd, 1);
282 // Diaspora style profile url
283 if (substr($this->cmd, 0, 2) === 'u/') {
284 $this->cmd = 'profile/' . substr($this->cmd, 2);
288 * Break the URL path into C style argc/argv style arguments for our
289 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
290 * will be 3 (integer) and $this->argv will contain:
296 * There will always be one argument. If provided a naked domain
297 * URL, $this->argv[0] is set to "home".
300 $this->argv = explode('/', $this->cmd);
301 $this->argc = count($this->argv);
302 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
303 $this->module = str_replace('.', '_', $this->argv[0]);
304 $this->module = str_replace('-', '_', $this->module);
307 $this->argv = ['home'];
308 $this->module = 'home';
311 // See if there is any page number information, and initialise pagination
312 $this->pager['page'] = !empty($_GET['page']) && intval($_GET['page']) > 0 ? intval($_GET['page']) : 1;
313 $this->pager['itemspage'] = 50;
314 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
316 if ($this->pager['start'] < 0) {
317 $this->pager['start'] = 0;
319 $this->pager['total'] = 0;
321 // Detect mobile devices
322 $mobile_detect = new MobileDetect();
323 $this->is_mobile = $mobile_detect->isMobile();
324 $this->is_tablet = $mobile_detect->isTablet();
326 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
328 // Register template engines
329 $this->registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
333 * Returns the Mode of the Application
335 * @return App\Mode The Application Mode
337 * @throws InternalServerErrorException when the mode isn't created
339 public function getMode()
341 if (empty($this->mode)) {
342 throw new InternalServerErrorException('Mode of the Application is not defined');
349 * Reloads the whole app instance
351 public function reload()
353 // The order of the following calls is important to ensure proper initialization
354 $this->loadConfigFiles();
356 $this->loadDatabase();
358 $this->getMode()->determine($this->getBasePath());
360 $this->determineURLPath();
364 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
365 Core\Addon::loadHooks();
367 $this->loadAddonConfig();
370 $this->loadDefaultTimezone();
387 $this->process_id = Core\System::processID('log');
391 * Load the configuration files
393 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
394 * expected local.ini.php
396 private function loadConfigFiles()
398 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
399 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
401 // Legacy .htconfig.php support
402 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
404 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
407 // Legacy .htconfig.php support
408 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php')) {
411 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php';
413 $this->setConfigValue('database', 'hostname', $db_host);
414 $this->setConfigValue('database', 'username', $db_user);
415 $this->setConfigValue('database', 'password', $db_pass);
416 $this->setConfigValue('database', 'database', $db_data);
417 if (isset($a->config['system']['db_charset'])) {
418 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
421 unset($db_host, $db_user, $db_pass, $db_data);
423 if (isset($default_timezone)) {
424 $this->setConfigValue('system', 'default_timezone', $default_timezone);
425 unset($default_timezone);
428 if (isset($pidfile)) {
429 $this->setConfigValue('system', 'pidfile', $pidfile);
434 $this->setConfigValue('system', 'language', $lang);
439 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
440 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
445 * Tries to load the specified configuration file into the App->config array.
446 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
448 * The config format is INI and the template for configuration files is the following:
450 * <?php return <<<INI
458 * @param string $filepath
459 * @param bool $overwrite Force value overwrite if the config key already exists
462 public function loadConfigFile($filepath, $overwrite = false)
464 if (!file_exists($filepath)) {
465 throw new Exception('Error parsing non-existent config file ' . $filepath);
468 $contents = include($filepath);
470 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
472 if ($config === false) {
473 throw new Exception('Error parsing config file ' . $filepath);
476 foreach ($config as $category => $values) {
477 foreach ($values as $key => $value) {
479 $this->setConfigValue($category, $key, $value);
481 $this->setDefaultConfigValue($category, $key, $value);
488 * Loads addons configuration files
490 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
491 * again to overwrite potential local addon configuration.
493 private function loadAddonConfig()
495 // Loads addons default config
496 Core\Addon::callHooks('load_config');
498 // Load the local addon config file to overwritten default addon config values
499 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
500 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
505 * Loads the default timezone
507 * Include support for legacy $default_timezone
509 * @global string $default_timezone
511 private function loadDefaultTimezone()
513 if ($this->getConfigValue('system', 'default_timezone')) {
514 $this->timezone = $this->getConfigValue('system', 'default_timezone');
516 global $default_timezone;
517 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
520 if ($this->timezone) {
521 date_default_timezone_set($this->timezone);
526 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
528 private function determineURLPath()
530 /* Relative script path to the web server root
531 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
533 $relative_script_path = '';
534 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
535 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
536 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
537 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
539 $this->urlPath = $this->getConfigValue('system', 'urlpath');
541 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
542 * QUERY_STRING gives pagename=module/parameter
544 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
546 if (!empty($relative_script_path)) {
548 if (!empty($_SERVER['QUERY_STRING'])) {
549 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
552 $path = trim($relative_script_path, '/');
555 if ($path && $path != $this->urlPath) {
556 $this->urlPath = $path;
561 public function loadDatabase()
563 if (DBA::connected()) {
567 $db_host = $this->getConfigValue('database', 'hostname');
568 $db_user = $this->getConfigValue('database', 'username');
569 $db_pass = $this->getConfigValue('database', 'password');
570 $db_data = $this->getConfigValue('database', 'database');
571 $charset = $this->getConfigValue('database', 'charset');
573 // Use environment variables for mysql if they are set beforehand
574 if (!empty(getenv('MYSQL_HOST'))
575 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
576 && getenv('MYSQL_PASSWORD') !== false
577 && !empty(getenv('MYSQL_DATABASE')))
579 $db_host = getenv('MYSQL_HOST');
580 if (!empty(getenv('MYSQL_PORT'))) {
581 $db_host .= ':' . getenv('MYSQL_PORT');
583 if (!empty(getenv('MYSQL_USERNAME'))) {
584 $db_user = getenv('MYSQL_USERNAME');
586 $db_user = getenv('MYSQL_USER');
588 $db_pass = (string) getenv('MYSQL_PASSWORD');
589 $db_data = getenv('MYSQL_DATABASE');
592 $stamp1 = microtime(true);
594 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
595 unset($db_host, $db_user, $db_pass, $db_data, $charset);
597 $this->saveTimestamp($stamp1, 'network');
601 * @brief Returns the base filesystem path of the App
603 * It first checks for the internal variable, then for DOCUMENT_ROOT and
608 public function getBasePath()
610 $basepath = $this->basePath;
613 $basepath = Core\Config::get('system', 'basepath');
616 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
617 $basepath = $_SERVER['DOCUMENT_ROOT'];
620 if (!$basepath && !empty($_SERVER['PWD'])) {
621 $basepath = $_SERVER['PWD'];
624 return self::getRealPath($basepath);
628 * @brief Returns a normalized file path
630 * This is a wrapper for the "realpath" function.
631 * That function cannot detect the real path when some folders aren't readable.
632 * Since this could happen with some hosters we need to handle this.
634 * @param string $path The path that is about to be normalized
635 * @return string normalized path - when possible
637 public static function getRealPath($path)
639 $normalized = realpath($path);
641 if (!is_bool($normalized)) {
648 public function getScheme()
650 return $this->scheme;
654 * @brief Retrieves the Friendica instance base URL
656 * This function assembles the base URL from multiple parts:
657 * - Protocol is determined either by the request or a combination of
658 * system.ssl_policy and the $ssl parameter.
659 * - Host name is determined either by system.hostname or inferred from request
660 * - Path is inferred from SCRIPT_NAME
662 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
664 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
665 * @return string Friendica server base URL
667 public function getBaseURL($ssl = false)
669 $scheme = $this->scheme;
671 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
675 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
676 // (and also the login link). Anything seen by an outsider will have it turned off.
678 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
686 if (Core\Config::get('config', 'hostname') != '') {
687 $this->hostname = Core\Config::get('config', 'hostname');
690 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
694 * @brief Initializes the baseurl components
696 * Clears the baseurl cache to prevent inconsistencies
700 public function setBaseURL($url)
702 $parsed = @parse_url($url);
705 if (!empty($parsed)) {
706 if (!empty($parsed['scheme'])) {
707 $this->scheme = $parsed['scheme'];
710 if (!empty($parsed['host'])) {
711 $hostname = $parsed['host'];
714 if (!empty($parsed['port'])) {
715 $hostname .= ':' . $parsed['port'];
717 if (!empty($parsed['path'])) {
718 $this->urlPath = trim($parsed['path'], '\\/');
721 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
722 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
725 if (Core\Config::get('config', 'hostname') != '') {
726 $this->hostname = Core\Config::get('config', 'hostname');
729 if (!isset($this->hostname) || ($this->hostname == '')) {
730 $this->hostname = $hostname;
735 public function getHostName()
737 if (Core\Config::get('config', 'hostname') != '') {
738 $this->hostname = Core\Config::get('config', 'hostname');
741 return $this->hostname;
744 public function getURLPath()
746 return $this->urlPath;
749 public function setPagerTotal($n)
751 $this->pager['total'] = intval($n);
754 public function setPagerItemsPage($n)
756 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
757 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
760 public function setPagerPage($n)
762 $this->pager['page'] = $n;
763 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
767 * Initializes App->page['htmlhead'].
772 * - Registered stylesheets (through App->registerStylesheet())
773 * - Infinite scroll data
774 * - head.tpl template
776 public function initHead()
778 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
780 // If the update is 'deactivated' set it to the highest integer number (~24 days)
782 $interval = 2147483647;
785 if ($interval < 10000) {
789 // compose the page title from the sitename and the
790 // current module called
791 if (!$this->module == '') {
792 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
794 $this->page['title'] = $this->config['sitename'];
797 if (!empty($this->theme['stylesheet'])) {
798 $stylesheet = $this->theme['stylesheet'];
800 $stylesheet = $this->getCurrentThemeStylesheetPath();
803 $this->registerStylesheet($stylesheet);
805 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
806 if ($shortcut_icon == '') {
807 $shortcut_icon = 'images/friendica-32.png';
810 $touch_icon = Core\Config::get('system', 'touch_icon');
811 if ($touch_icon == '') {
812 $touch_icon = 'images/friendica-128.png';
815 // get data wich is needed for infinite scroll on the network page
816 $infinite_scroll = infinite_scroll_data($this->module);
818 Core\Addon::callHooks('head', $this->page['htmlhead']);
820 $tpl = get_markup_template('head.tpl');
821 /* put the head template at the beginning of page['htmlhead']
822 * since the code added by the modules frequently depends on it
825 $this->page['htmlhead'] = replace_macros($tpl, [
826 '$baseurl' => $this->getBaseURL(),
827 '$local_user' => local_user(),
828 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
829 '$delitem' => Core\L10n::t('Delete this item?'),
830 '$showmore' => Core\L10n::t('show more'),
831 '$showfewer' => Core\L10n::t('show fewer'),
832 '$update_interval' => $interval,
833 '$shortcut_icon' => $shortcut_icon,
834 '$touch_icon' => $touch_icon,
835 '$infinite_scroll' => $infinite_scroll,
836 '$block_public' => intval(Core\Config::get('system', 'block_public')),
837 '$stylesheets' => $this->stylesheets,
838 ]) . $this->page['htmlhead'];
842 * Initializes App->page['footer'].
845 * - Javascript homebase
846 * - Mobile toggle link
847 * - Registered footer scripts (through App->registerFooterScript())
848 * - footer.tpl template
850 public function initFooter()
852 // If you're just visiting, let javascript take you home
853 if (!empty($_SESSION['visitor_home'])) {
854 $homebase = $_SESSION['visitor_home'];
855 } elseif (local_user()) {
856 $homebase = 'profile/' . $this->user['nickname'];
859 if (isset($homebase)) {
860 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
864 * Add a "toggle mobile" link if we're using a mobile device
866 if ($this->is_mobile || $this->is_tablet) {
867 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
868 $link = 'toggle_mobile?address=' . curPageURL();
870 $link = 'toggle_mobile?off=1&address=' . curPageURL();
872 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
873 '$toggle_link' => $link,
874 '$toggle_text' => Core\L10n::t('toggle mobile')
878 Core\Addon::callHooks('footer', $this->page['footer']);
880 $tpl = get_markup_template('footer.tpl');
881 $this->page['footer'] = replace_macros($tpl, [
882 '$baseurl' => $this->getBaseURL(),
883 '$footerScripts' => $this->footerScripts,
884 ]) . $this->page['footer'];
888 * @brief Removes the base url from an url. This avoids some mixed content problems.
890 * @param string $origURL
892 * @return string The cleaned url
894 public function removeBaseURL($origURL)
896 // Remove the hostname from the url if it is an internal link
897 $nurl = normalise_link($origURL);
898 $base = normalise_link($this->getBaseURL());
899 $url = str_replace($base . '/', '', $nurl);
901 // if it is an external link return the orignal value
902 if ($url == normalise_link($origURL)) {
910 * @brief Register template engine class
912 * @param string $class
914 private function registerTemplateEngine($class)
916 $v = get_class_vars($class);
917 if (!empty($v['name'])) {
919 $this->template_engines[$name] = $class;
921 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
927 * @brief Return template engine instance.
929 * If $name is not defined, return engine defined by theme,
932 * @return object Template Engine instance
934 public function getTemplateEngine()
936 $template_engine = defaults($this->theme, 'template_engine', 'smarty3');
938 if (isset($this->template_engines[$template_engine])) {
939 if (isset($this->template_engine_instance[$template_engine])) {
940 return $this->template_engine_instance[$template_engine];
942 $class = $this->template_engines[$template_engine];
944 $this->template_engine_instance[$template_engine] = $obj;
949 echo "template engine <tt>$template_engine</tt> is not registered!\n";
954 * @brief Returns the active template engine.
956 * @return string the active template engine
958 public function getActiveTemplateEngine()
960 return $this->theme['template_engine'];
964 * sets the active template engine
966 * @param string $engine the template engine (default is Smarty3)
968 public function setActiveTemplateEngine($engine = 'smarty3')
970 $this->theme['template_engine'] = $engine;
974 * Gets the right delimiter for a template engine
980 * @param string $engine The template engine (default is Smarty3)
982 * @return string the right delimiter
984 public function getTemplateLeftDelimiter($engine = 'smarty3')
986 return $this->ldelim[$engine];
990 * Gets the left delimiter for a template engine
996 * @param string $engine The template engine (default is Smarty3)
998 * @return string the left delimiter
1000 public function getTemplateRightDelimiter($engine = 'smarty3')
1002 return $this->rdelim[$engine];
1006 * Saves a timestamp for a value - f.e. a call
1007 * Necessary for profiling Friendica
1009 * @param int $timestamp the Timestamp
1010 * @param string $value A value to profile
1012 public function saveTimestamp($timestamp, $value)
1014 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
1018 $duration = (float) (microtime(true) - $timestamp);
1020 if (!isset($this->performance[$value])) {
1021 // Prevent ugly E_NOTICE
1022 $this->performance[$value] = 0;
1025 $this->performance[$value] += (float) $duration;
1026 $this->performance['marktime'] += (float) $duration;
1028 $callstack = Core\System::callstack();
1030 if (!isset($this->callstack[$value][$callstack])) {
1031 // Prevent ugly E_NOTICE
1032 $this->callstack[$value][$callstack] = 0;
1035 $this->callstack[$value][$callstack] += (float) $duration;
1039 * Returns the current UserAgent as a String
1041 * @return string the UserAgent as a String
1043 public function getUserAgent()
1046 FRIENDICA_PLATFORM . " '" .
1047 FRIENDICA_CODENAME . "' " .
1048 FRIENDICA_VERSION . '-' .
1049 DB_UPDATE_VERSION . '; ' .
1050 $this->getBaseURL();
1054 * Checks, if the call is from the Friendica App
1057 * The friendica client has problems with the GUID in the notify. this is some workaround
1059 private function checkFriendicaApp()
1062 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1066 * Is the call via the Friendica app? (not a "normale" call)
1068 * @return bool true if it's from the Friendica app
1070 public function isFriendicaApp()
1072 return $this->isFriendicaApp;
1076 * @brief Checks if the site is called via a backend process
1078 * This isn't a perfect solution. But we need this check very early.
1079 * So we cannot wait until the modules are loaded.
1081 * @param string $backend true, if the backend flag was set during App initialization
1084 private function checkBackend($backend) {
1085 static $backends = [
1107 // Check if current module is in backend or backend flag is set
1108 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1112 * Returns true, if the call is from a backend node (f.e. from a worker)
1114 * @return bool Is it a known backend?
1116 public function isBackend()
1118 return $this->isBackend;
1122 * @brief Checks if the maximum number of database processes is reached
1124 * @return bool Is the limit reached?
1126 public function isMaxProcessesReached()
1128 // Deactivated, needs more investigating if this check really makes sense
1132 * Commented out to suppress static analyzer issues
1134 if ($this->is_backend()) {
1135 $process = 'backend';
1136 $max_processes = Core\Config::get('system', 'max_processes_backend');
1137 if (intval($max_processes) == 0) {
1141 $process = 'frontend';
1142 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1143 if (intval($max_processes) == 0) {
1144 $max_processes = 20;
1148 $processlist = DBA::processlist();
1149 if ($processlist['list'] != '') {
1150 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1152 if ($processlist['amount'] > $max_processes) {
1153 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1162 * @brief Checks if the minimal memory is reached
1164 * @return bool Is the memory limit reached?
1166 public function isMinMemoryReached()
1168 $min_memory = Core\Config::get('system', 'min_memory', 0);
1169 if ($min_memory == 0) {
1173 if (!is_readable('/proc/meminfo')) {
1177 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1180 foreach ($memdata as $line) {
1181 $data = explode(':', $line);
1182 if (count($data) != 2) {
1185 list($key, $val) = $data;
1186 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1187 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1190 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1194 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1196 $reached = ($free < $min_memory);
1199 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1206 * @brief Checks if the maximum load is reached
1208 * @return bool Is the load reached?
1210 public function isMaxLoadReached()
1212 if ($this->isBackend()) {
1213 $process = 'backend';
1214 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1215 if ($maxsysload < 1) {
1219 $process = 'frontend';
1220 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1221 if ($maxsysload < 1) {
1226 $load = Core\System::currentLoad();
1228 if (intval($load) > $maxsysload) {
1229 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1237 * Executes a child process with 'proc_open'
1239 * @param string $command The command to execute
1240 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1242 public function proc_run($command, $args)
1244 if (!function_exists('proc_open')) {
1248 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1250 foreach ($args as $key => $value) {
1251 if (!is_null($value) && is_bool($value) && !$value) {
1255 $cmdline .= ' --' . $key;
1256 if (!is_null($value) && !is_bool($value)) {
1257 $cmdline .= ' ' . $value;
1261 if ($this->isMinMemoryReached()) {
1265 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1266 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1268 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1270 if (!is_resource($resource)) {
1271 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1274 proc_close($resource);
1278 * @brief Returns the system user that is executing the script
1280 * This mostly returns something like "www-data".
1282 * @return string system username
1284 private static function getSystemUser()
1286 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1290 $processUser = posix_getpwuid(posix_geteuid());
1291 return $processUser['name'];
1295 * @brief Checks if a given directory is usable for the system
1297 * @return boolean the directory is usable
1299 public static function isDirectoryUsable($directory, $check_writable = true)
1301 if ($directory == '') {
1302 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1306 if (!file_exists($directory)) {
1307 logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1311 if (is_file($directory)) {
1312 logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1316 if (!is_dir($directory)) {
1317 logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1321 if ($check_writable && !is_writable($directory)) {
1322 logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1330 * @param string $cat Config category
1331 * @param string $k Config key
1332 * @param mixed $default Default value if it isn't set
1334 * @return string Returns the value of the Config entry
1336 public function getConfigValue($cat, $k, $default = null)
1340 if ($cat === 'config') {
1341 if (isset($this->config[$k])) {
1342 $return = $this->config[$k];
1345 if (isset($this->config[$cat][$k])) {
1346 $return = $this->config[$cat][$k];
1354 * Sets a default value in the config cache. Ignores already existing keys.
1356 * @param string $cat Config category
1357 * @param string $k Config key
1358 * @param mixed $v Default value to set
1360 private function setDefaultConfigValue($cat, $k, $v)
1362 if (!isset($this->config[$cat][$k])) {
1363 $this->setConfigValue($cat, $k, $v);
1368 * Sets a value in the config cache. Accepts raw output from the config table
1370 * @param string $cat Config category
1371 * @param string $k Config key
1372 * @param mixed $v Value to set
1374 public function setConfigValue($cat, $k, $v)
1376 // Only arrays are serialized in database, so we have to unserialize sparingly
1377 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1379 if ($cat === 'config') {
1380 $this->config[$k] = $value;
1382 if (!isset($this->config[$cat])) {
1383 $this->config[$cat] = [];
1386 $this->config[$cat][$k] = $value;
1391 * Deletes a value from the config cache
1393 * @param string $cat Config category
1394 * @param string $k Config key
1396 public function deleteConfigValue($cat, $k)
1398 if ($cat === 'config') {
1399 if (isset($this->config[$k])) {
1400 unset($this->config[$k]);
1403 if (isset($this->config[$cat][$k])) {
1404 unset($this->config[$cat][$k]);
1411 * Retrieves 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
1416 * @param mixed $default Default value if key isn't set
1418 * @return string The value of the config entry
1420 public function getPConfigValue($uid, $cat, $k, $default = null)
1424 if (isset($this->config[$uid][$cat][$k])) {
1425 $return = $this->config[$uid][$cat][$k];
1432 * Sets a value in the user config cache
1434 * Accepts raw output from the pconfig table
1436 * @param int $uid User Id
1437 * @param string $cat Config category
1438 * @param string $k Config key
1439 * @param mixed $v Value to set
1441 public function setPConfigValue($uid, $cat, $k, $v)
1443 // Only arrays are serialized in database, so we have to unserialize sparingly
1444 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1446 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1447 $this->config[$uid] = [];
1450 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1451 $this->config[$uid][$cat] = [];
1454 $this->config[$uid][$cat][$k] = $value;
1458 * Deletes a value from the user config cache
1460 * @param int $uid User Id
1461 * @param string $cat Config category
1462 * @param string $k Config key
1464 public function deletePConfigValue($uid, $cat, $k)
1466 if (isset($this->config[$uid][$cat][$k])) {
1467 unset($this->config[$uid][$cat][$k]);
1472 * Generates the site's default sender email address
1476 public function getSenderEmailAddress()
1478 $sender_email = Core\Config::get('config', 'sender_email');
1479 if (empty($sender_email)) {
1480 $hostname = $this->getHostName();
1481 if (strpos($hostname, ':')) {
1482 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1485 $sender_email = 'noreply@' . $hostname;
1488 return $sender_email;
1492 * Returns the current theme name.
1494 * @return string the name of the current theme
1496 public function getCurrentTheme()
1498 if ($this->getMode()->isInstall()) {
1502 //// @TODO Compute the current theme only once (this behavior has
1503 /// already been implemented, but it didn't work well -
1504 /// https://github.com/friendica/friendica/issues/5092)
1505 $this->computeCurrentTheme();
1507 return $this->currentTheme;
1511 * Computes the current theme name based on the node settings, the user settings and the device type
1515 private function computeCurrentTheme()
1517 $system_theme = Core\Config::get('system', 'theme');
1518 if (!$system_theme) {
1519 throw new Exception(Core\L10n::t('No system theme config value set.'));
1523 $this->currentTheme = $system_theme;
1525 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1528 // Find the theme that belongs to the user whose stuff we are looking at
1529 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1530 // Allow folks to override user themes and always use their own on their own site.
1531 // This works only if the user is on the same server
1532 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1533 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1534 $page_theme = $user['theme'];
1538 $user_theme = Core\Session::get('theme', $system_theme);
1540 // Specific mobile theme override
1541 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1542 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1543 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1545 // --- means same mobile theme as desktop
1546 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1547 $user_theme = $user_mobile_theme;
1552 $theme_name = $page_theme;
1554 $theme_name = $user_theme;
1558 && in_array($theme_name, $allowed_themes)
1559 && (file_exists('view/theme/' . $theme_name . '/style.css')
1560 || file_exists('view/theme/' . $theme_name . '/style.php'))
1562 $this->currentTheme = $theme_name;
1567 * @brief Return full URL to theme which is currently in effect.
1569 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1573 public function getCurrentThemeStylesheetPath()
1575 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1579 * Check if request was an AJAX (xmlhttprequest) request.
1581 * @return boolean true if it was an AJAX request
1583 public function isAjax()
1585 return $this->isAjax;
1589 * Returns the value of a argv key
1590 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1592 * @param int $position the position of the argument
1593 * @param mixed $default the default value if not found
1595 * @return mixed returns the value of the argument
1597 public function getArgumentValue($position, $default = '')
1599 if (array_key_exists($position, $this->argv)) {
1600 return $this->argv[$position];
1607 * Sets the base url for use in cmdline programs which don't have
1608 * $_SERVER variables
1610 public function checkURL()
1612 $url = Core\Config::get('system', 'url');
1614 // if the url isn't set or the stored url is radically different
1615 // than the currently visited url, store the current value accordingly.
1616 // "Radically different" ignores common variations such as http vs https
1617 // and www.example.com vs example.com.
1618 // We will only change the url to an ip address if there is no existing setting
1620 if (empty($url) || (!link_compare($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1621 Core\Config::set('system', 'url', $this->getBaseURL());
1626 * Frontend App script
1628 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1629 * request and a representation of the response.
1631 * This probably should change to limit the size of this monster method.
1633 public function runFrontend()
1635 // Missing DB connection: ERROR
1636 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1637 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1640 // Max Load Average reached: ERROR
1641 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1642 header('Retry-After: 120');
1643 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1645 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1648 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1649 Core\System::httpExit(404);
1652 if (!$this->getMode()->isInstall()) {
1653 // Force SSL redirection
1654 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1655 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1656 && strpos($this->getBaseURL(), 'https://') === 0
1657 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1658 header('HTTP/1.1 302 Moved Temporarily');
1659 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1663 Core\Session::init();
1664 Core\Addon::callHooks('init_1');
1667 // Exclude the backend processes from the session management
1668 if (!$this->isBackend()) {
1669 $stamp1 = microtime(true);
1671 $this->saveTimestamp($stamp1, 'parser');
1672 Core\L10n::setSessionVariable();
1673 Core\L10n::setLangFromSession();
1676 Core\Worker::executeIfIdle();
1680 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1681 $this->query_string = Model\Profile::stripZrls($this->query_string);
1682 if (!local_user()) {
1683 // Only continue when the given profile link seems valid
1684 // Valid profile links contain a path with "/profile/" and no query parameters
1685 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1686 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1687 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1688 $_SESSION['my_url'] = $_GET['zrl'];
1689 $_SESSION['authenticated'] = 0;
1691 Model\Profile::zrlInit($this);
1693 // Someone came with an invalid parameter, maybe as a DDoS attempt
1694 // We simply stop processing here
1695 logger("Invalid ZRL parameter " . $_GET['zrl'], LOGGER_DEBUG);
1696 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1701 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1702 $token = $_GET['owt'];
1703 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1704 Model\Profile::openWebAuthInit($token);
1707 Module\Login::sessionAuth();
1709 if (empty($_SESSION['authenticated'])) {
1710 header('X-Account-Management-Status: none');
1713 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1714 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1715 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1718 * check_config() is responsible for running update scripts. These automatically
1719 * update the DB schema whenever we push a new one out. It also checks to see if
1720 * any addons have been added or removed and reacts accordingly.
1723 // in install mode, any url loads install module
1724 // but we need "view" module for stylesheet
1725 if ($this->getMode()->isInstall() && $this->module != 'view') {
1726 $this->module = 'install';
1727 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1728 $this->module = 'maintenance';
1732 Core\Addon::check();
1735 Content\Nav::setSelected('nothing');
1737 //Don't populate apps_menu if apps are private
1738 $privateapps = Core\Config::get('config', 'private_addons');
1739 if ((local_user()) || (! $privateapps === "1")) {
1740 $arr = ['app_menu' => $this->apps];
1742 Core\Addon::callHooks('app_menu', $arr);
1744 $this->apps = $arr['app_menu'];
1747 if (strlen($this->module)) {
1748 // Compatibility with the Android Diaspora client
1749 if ($this->module == 'stream') {
1750 goaway('network?f=&order=post');
1753 if ($this->module == 'conversations') {
1757 if ($this->module == 'commented') {
1758 goaway('network?f=&order=comment');
1761 if ($this->module == 'liked') {
1762 goaway('network?f=&order=comment');
1765 if ($this->module == 'activity') {
1766 goaway('network/?f=&conv=1');
1769 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1770 goaway('bookmarklet');
1773 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1777 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1781 // Compatibility with the Firefox App
1782 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1783 $this->module = "login";
1786 $privateapps = Core\Config::get('config', 'private_addons', false);
1787 if (is_array($this->addons) && in_array($this->module, $this->addons) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1788 //Check if module is an app and if public access to apps is allowed or not
1789 if ((!local_user()) && Core\Addon::isApp($this->module) && $privateapps) {
1790 info(Core\L10n::t("You must be logged in to use addons. "));
1792 include_once "addon/{$this->module}/{$this->module}.php";
1793 if (function_exists($this->module . '_module')) {
1794 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1795 $this->module_class = 'Friendica\\LegacyModule';
1796 $this->module_loaded = true;
1801 // Controller class routing
1802 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1803 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1804 $this->module_loaded = true;
1807 /* If not, next look for a 'standard' program module in the 'mod' directory
1808 * We emulate a Module class through the LegacyModule class
1810 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1811 LegacyModule::setModuleFile("mod/{$this->module}.php");
1812 $this->module_class = 'Friendica\\LegacyModule';
1813 $this->module_loaded = true;
1816 /* The URL provided does not resolve to a valid module.
1818 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1819 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1820 * 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
1821 * this will often succeed and eventually do the right thing.
1823 * Otherwise we are going to emit a 404 not found.
1825 if (! $this->module_loaded) {
1826 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1827 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1831 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1832 logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1833 goaway($this->getBaseURL() . $_SERVER['REQUEST_URI']);
1836 logger('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], LOGGER_DEBUG);
1838 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1839 $tpl = get_markup_template("404.tpl");
1840 $this->page['content'] = replace_macros($tpl, [
1841 '$message' => Core\L10n::t('Page not found.')
1846 // Load current theme info
1847 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1848 if (file_exists($theme_info_file)) {
1849 require_once $theme_info_file;
1853 // initialise content region
1854 if ($this->getMode()->isNormal()) {
1855 Core\Addon::callHooks('page_content_top', $this->page['content']);
1858 // Call module functions
1859 if ($this->module_loaded) {
1860 $this->page['page_title'] = $this->module;
1863 Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1865 call_user_func([$this->module_class, 'init']);
1867 // "rawContent" is especially meant for technical endpoints.
1868 // This endpoint doesn't need any theme initialization or other comparable stuff.
1869 if (!$this->error) {
1870 call_user_func([$this->module_class, 'rawContent']);
1873 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1874 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1878 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1879 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1880 call_user_func([$this->module_class, 'post']);
1883 if (! $this->error) {
1884 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1885 call_user_func([$this->module_class, 'afterpost']);
1888 if (! $this->error) {
1889 $arr = ['content' => $this->page['content']];
1890 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1891 $this->page['content'] = $arr['content'];
1892 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1893 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1894 $this->page['content'] .= $arr['content'];
1897 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded')) {
1898 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded';
1903 /* Create the page head after setting the language
1904 * and getting any auth credentials.
1906 * Moved initHead() and initFooter() to after
1907 * all the module functions have executed so that all
1908 * theme choices made by the modules can take effect.
1912 /* Build the page ending -- this is stuff that goes right before
1913 * the closing </body> tag
1915 $this->initFooter();
1917 /* now that we've been through the module content, see if the page reported
1918 * a permission problem and if so, a 403 response would seem to be in order.
1920 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1921 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1924 // Report anything which needs to be communicated in the notification area (before the main body)
1925 Core\Addon::callHooks('page_end', $this->page['content']);
1927 // Add the navigation (menu) template
1928 if ($this->module != 'install' && $this->module != 'maintenance') {
1929 Content\Nav::build($this);
1932 // Build the page - now that we have all the components
1933 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1934 $doc = new DOMDocument();
1936 $target = new DOMDocument();
1937 $target->loadXML("<root></root>");
1939 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1941 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1942 @$doc->loadHTML($content);
1944 $xpath = new DOMXPath($doc);
1946 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1948 foreach ($list as $item) {
1949 $item = $target->importNode($item, true);
1951 // And then append it to the target
1952 $target->documentElement->appendChild($item);
1956 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1957 header("Content-type: text/html; charset=utf-8");
1959 echo substr($target->saveHTML(), 6, -8);
1964 $page = $this->page;
1965 $profile = $this->profile;
1967 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1968 header("Content-type: text/html; charset=utf-8");
1970 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1971 header("Strict-Transport-Security: max-age=31536000");
1974 // Some security stuff
1975 header('X-Content-Type-Options: nosniff');
1976 header('X-XSS-Protection: 1; mode=block');
1977 header('X-Permitted-Cross-Domain-Policies: none');
1978 header('X-Frame-Options: sameorigin');
1980 // Things like embedded OSM maps don't work, when this is enabled
1981 // 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'");
1983 /* We use $_GET["mode"] for special page templates. So we will check if we have
1984 * to load another page template than the default one.
1985 * The page templates are located in /view/php/ or in the theme directory.
1987 if (isset($_GET["mode"])) {
1988 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1991 // If there is no page template use the default page template
1992 if (empty($template)) {
1993 $template = Core\Theme::getPathForFile("default.php");
1996 // Theme templates expect $a as an App instance
1999 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
2000 require_once $template;