5 use Friendica\Core\Cache;
6 use Friendica\Core\Config;
7 use Friendica\Core\PConfig;
8 use Friendica\Core\System;
10 use Detection\MobileDetect;
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;
47 public $error = false;
58 public $interactive = true;
60 public $plugins_admin = [];
63 public $is_mobile = false;
64 public $is_tablet = false;
65 public $is_friendica_app;
66 public $performance = [];
67 public $callstack = [];
68 public $theme_info = [];
69 public $backend = true;
72 // Allow themes to control internal parameters
73 // by changing App values in theme.php
75 public $sourcename = '';
76 public $videowidth = 425;
77 public $videoheight = 350;
78 public $force_max_items = 0;
79 public $theme_events_in_profile = true;
82 * @brief An array for all theme-controllable parameters
84 * Mostly unimplemented yet. Only options 'template_engine' and
91 'force_max_items' => 0,
93 'template_engine' => 'smarty3',
97 * @brief An array of registered template engines ('name'=>'class name')
99 public $template_engines = [];
102 * @brief An array of instanced template engines ('name'=>'instance')
104 public $template_engine_instance = [];
119 private $curl_content_type;
120 private $curl_headers;
121 private $cached_profile_image;
122 private $cached_profile_picdate;
126 * @brief App constructor.
128 * @param string $basepath Path to the app base folder
130 function __construct($basepath) {
132 global $default_timezone;
136 if (! static::directory_usable($basepath, false)) {
137 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
140 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
142 if (file_exists($this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php')) {
143 include $this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php';
146 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
148 date_default_timezone_set($this->timezone);
150 $this->performance['start'] = microtime(true);
151 $this->performance['database'] = 0;
152 $this->performance['database_write'] = 0;
153 $this->performance['network'] = 0;
154 $this->performance['file'] = 0;
155 $this->performance['rendering'] = 0;
156 $this->performance['parser'] = 0;
157 $this->performance['marktime'] = 0;
158 $this->performance['markstart'] = microtime(true);
160 $this->callstack['database'] = [];
161 $this->callstack['database_write'] = [];
162 $this->callstack['network'] = [];
163 $this->callstack['file'] = [];
164 $this->callstack['rendering'] = [];
165 $this->callstack['parser'] = [];
171 $this->query_string = '';
173 $this->process_id = uniqid('log', true);
177 $this->scheme = 'http';
179 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
180 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
181 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
182 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
183 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
184 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
186 $this->scheme = 'https';
189 if (x($_SERVER, 'SERVER_NAME')) {
190 $this->hostname = $_SERVER['SERVER_NAME'];
192 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
193 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
196 * Figure out if we are running at the top of a domain
197 * or in a sub-directory and adjust accordingly
200 /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
201 $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
202 if (isset($path) && strlen($path) && ($path != $this->path)) {
207 if ($hostname != '') {
208 $this->hostname = $hostname;
212 get_include_path() . PATH_SEPARATOR
213 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
214 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
218 if (is_array($_SERVER['argv']) && $_SERVER['argc'] > 1 && substr(end($_SERVER['argv']), 0, 4) == 'http') {
219 $this->set_baseurl(array_pop($_SERVER['argv']));
223 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
224 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
226 // removing trailing / - maybe a nginx problem
227 $this->query_string = ltrim($this->query_string, '/');
228 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
229 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
231 // removing trailing / - maybe a nginx problem
232 $this->query_string = ltrim($this->query_string, '/');
235 if (x($_GET, 'pagename')) {
236 $this->cmd = trim($_GET['pagename'], '/\\');
237 } elseif (x($_GET, 'q')) {
238 $this->cmd = trim($_GET['q'], '/\\');
242 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
244 // unix style "homedir"
245 if (substr($this->cmd, 0, 1) === '~') {
246 $this->cmd = 'profile/' . substr($this->cmd, 1);
249 // Diaspora style profile url
250 if (substr($this->cmd, 0, 2) === 'u/') {
251 $this->cmd = 'profile/' . substr($this->cmd, 2);
255 * Break the URL path into C style argc/argv style arguments for our
256 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
257 * will be 3 (integer) and $this->argv will contain:
263 * There will always be one argument. If provided a naked domain
264 * URL, $this->argv[0] is set to "home".
267 $this->argv = explode('/', $this->cmd);
268 $this->argc = count($this->argv);
269 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
270 $this->module = str_replace('.', '_', $this->argv[0]);
271 $this->module = str_replace('-', '_', $this->module);
274 $this->argv = ['home'];
275 $this->module = 'home';
278 // See if there is any page number information, and initialise pagination
279 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
280 $this->pager['itemspage'] = 50;
281 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
283 if ($this->pager['start'] < 0) {
284 $this->pager['start'] = 0;
286 $this->pager['total'] = 0;
288 // Detect mobile devices
289 $mobile_detect = new MobileDetect();
290 $this->is_mobile = $mobile_detect->isMobile();
291 $this->is_tablet = $mobile_detect->isTablet();
294 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)');
296 // Register template engines
297 $dc = get_declared_classes();
298 foreach ($dc as $k) {
299 if (in_array('Friendica\Render\ITemplateEngine', class_implements($k))) {
300 $this->register_template_engine($k);
308 * @brief Returns the base filesystem path of the App
310 * It first checks for the internal variable, then for DOCUMENT_ROOT and
315 public function get_basepath() {
316 $basepath = $this->basepath;
319 $basepath = Config::get('system', 'basepath');
322 if (! $basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
323 $basepath = $_SERVER['DOCUMENT_ROOT'];
326 if (! $basepath && x($_SERVER, 'PWD')) {
327 $basepath = $_SERVER['PWD'];
330 return self::realpath($basepath);
334 * @brief Returns a normalized file path
336 * This is a wrapper for the "realpath" function.
337 * That function cannot detect the real path when some folders aren't readable.
338 * Since this could happen with some hosters we need to handle this.
340 * @param string $path The path that is about to be normalized
341 * @return string normalized path - when possible
343 public static function realpath($path) {
344 $normalized = realpath($path);
346 if (!is_bool($normalized)) {
353 function get_scheme() {
354 return $this->scheme;
358 * @brief Retrieves the Friendica instance base URL
360 * This function assembles the base URL from multiple parts:
361 * - Protocol is determined either by the request or a combination of
362 * system.ssl_policy and the $ssl parameter.
363 * - Host name is determined either by system.hostname or inferred from request
364 * - Path is inferred from SCRIPT_NAME
366 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
368 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
369 * @return string Friendica server base URL
371 function get_baseurl($ssl = false) {
372 $scheme = $this->scheme;
374 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
378 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
379 // (and also the login link). Anything seen by an outsider will have it turned off.
381 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
389 if (Config::get('config', 'hostname') != '') {
390 $this->hostname = Config::get('config', 'hostname');
393 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
397 * @brief Initializes the baseurl components
399 * Clears the baseurl cache to prevent inconstistencies
403 function set_baseurl($url) {
404 $parsed = @parse_url($url);
407 $this->scheme = $parsed['scheme'];
409 $hostname = $parsed['host'];
410 if (x($parsed, 'port')) {
411 $hostname .= ':' . $parsed['port'];
413 if (x($parsed, 'path')) {
414 $this->path = trim($parsed['path'], '\\/');
417 if (file_exists($this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php')) {
418 include $this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php';
421 if (Config::get('config', 'hostname') != '') {
422 $this->hostname = Config::get('config', 'hostname');
425 if (!isset($this->hostname) || ( $this->hostname == '')) {
426 $this->hostname = $hostname;
431 function get_hostname() {
432 if (Config::get('config', 'hostname') != '') {
433 $this->hostname = Config::get('config', 'hostname');
436 return $this->hostname;
439 function set_hostname($h) {
440 $this->hostname = $h;
443 function set_path($p) {
444 $this->path = trim(trim($p), '/');
447 function get_path() {
451 function set_pager_total($n) {
452 $this->pager['total'] = intval($n);
455 function set_pager_itemspage($n) {
456 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
457 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
460 function set_pager_page($n) {
461 $this->pager['page'] = $n;
462 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
465 function init_pagehead() {
466 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
468 // If the update is 'deactivated' set it to the highest integer number (~24 days)
470 $interval = 2147483647;
473 if ($interval < 10000) {
477 // compose the page title from the sitename and the
478 // current module called
479 if (!$this->module == '') {
480 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
482 $this->page['title'] = $this->config['sitename'];
485 /* put the head template at the beginning of page['htmlhead']
486 * since the code added by the modules frequently depends on it
489 if (!isset($this->page['htmlhead'])) {
490 $this->page['htmlhead'] = '';
493 // If we're using Smarty, then doing replace_macros() will replace
494 // any unrecognized variables with a blank string. Since we delay
495 // replacing $stylesheet until later, we need to replace it now
496 // with another variable name
497 if ($this->theme['template_engine'] === 'smarty3') {
498 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
500 $stylesheet = '$stylesheet';
503 $shortcut_icon = Config::get('system', 'shortcut_icon');
504 if ($shortcut_icon == '') {
505 $shortcut_icon = 'images/friendica-32.png';
508 $touch_icon = Config::get('system', 'touch_icon');
509 if ($touch_icon == '') {
510 $touch_icon = 'images/friendica-128.png';
513 // get data wich is needed for infinite scroll on the network page
514 $invinite_scroll = infinite_scroll_data($this->module);
516 $tpl = get_markup_template('head.tpl');
517 $this->page['htmlhead'] = replace_macros($tpl, [
518 '$baseurl' => $this->get_baseurl(),
519 '$local_user' => local_user(),
520 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
521 '$delitem' => t('Delete this item?'),
522 '$showmore' => t('show more'),
523 '$showfewer' => t('show fewer'),
524 '$update_interval' => $interval,
525 '$shortcut_icon' => $shortcut_icon,
526 '$touch_icon' => $touch_icon,
527 '$stylesheet' => $stylesheet,
528 '$infinite_scroll' => $invinite_scroll,
529 ]) . $this->page['htmlhead'];
532 function init_page_end() {
533 if (!isset($this->page['end'])) {
534 $this->page['end'] = '';
536 $tpl = get_markup_template('end.tpl');
537 $this->page['end'] = replace_macros($tpl, [
538 '$baseurl' => $this->get_baseurl()
539 ]) . $this->page['end'];
542 function set_curl_code($code) {
543 $this->curl_code = $code;
546 function get_curl_code() {
547 return $this->curl_code;
550 function set_curl_content_type($content_type) {
551 $this->curl_content_type = $content_type;
554 function get_curl_content_type() {
555 return $this->curl_content_type;
558 function set_curl_headers($headers) {
559 $this->curl_headers = $headers;
562 function get_curl_headers() {
563 return $this->curl_headers;
566 function get_cached_avatar_image($avatar_image) {
567 return $avatar_image;
571 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
573 * @param string $orig_url
575 * @return string The cleaned url
577 function remove_baseurl($orig_url) {
579 // Remove the hostname from the url if it is an internal link
580 $nurl = normalise_link($orig_url);
581 $base = normalise_link($this->get_baseurl());
582 $url = str_replace($base . '/', '', $nurl);
584 // if it is an external link return the orignal value
585 if ($url == normalise_link($orig_url)) {
593 * @brief Register template engine class
595 * If $name is '', is used class static property $class::$name
597 * @param string $class
598 * @param string $name
600 function register_template_engine($class, $name = '') {
601 /// @TODO Really === and not just == ?
603 $v = get_class_vars($class);
608 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
611 $this->template_engines[$name] = $class;
615 * @brief Return template engine instance.
617 * If $name is not defined, return engine defined by theme,
620 * @param string $name Template engine name
621 * @return object Template Engine instance
623 function template_engine($name = '') {
624 /// @TODO really type-check included?
626 $template_engine = $name;
628 $template_engine = 'smarty3';
629 if (x($this->theme, 'template_engine')) {
630 $template_engine = $this->theme['template_engine'];
634 if (isset($this->template_engines[$template_engine])) {
635 if (isset($this->template_engine_instance[$template_engine])) {
636 return $this->template_engine_instance[$template_engine];
638 $class = $this->template_engines[$template_engine];
640 $this->template_engine_instance[$template_engine] = $obj;
645 echo "template engine <tt>$template_engine</tt> is not registered!\n";
650 * @brief Returns the active template engine.
654 function get_template_engine() {
655 return $this->theme['template_engine'];
658 function set_template_engine($engine = 'smarty3') {
659 $this->theme['template_engine'] = $engine;
662 function get_template_ldelim($engine = 'smarty3') {
663 return $this->ldelim[$engine];
666 function get_template_rdelim($engine = 'smarty3') {
667 return $this->rdelim[$engine];
670 function save_timestamp($stamp, $value) {
671 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
675 $duration = (float) (microtime(true) - $stamp);
677 if (!isset($this->performance[$value])) {
678 // Prevent ugly E_NOTICE
679 $this->performance[$value] = 0;
682 $this->performance[$value] += (float) $duration;
683 $this->performance['marktime'] += (float) $duration;
685 $callstack = System::callstack();
687 if (!isset($this->callstack[$value][$callstack])) {
688 // Prevent ugly E_NOTICE
689 $this->callstack[$value][$callstack] = 0;
692 $this->callstack[$value][$callstack] += (float) $duration;
695 function get_useragent() {
697 FRIENDICA_PLATFORM . " '" .
698 FRIENDICA_CODENAME . "' " .
699 FRIENDICA_VERSION . '-' .
700 DB_UPDATE_VERSION . '; ' .
701 $this->get_baseurl();
704 function is_friendica_app() {
705 return $this->is_friendica_app;
709 * @brief Checks if the site is called via a backend process
711 * This isn't a perfect solution. But we need this check very early.
712 * So we cannot wait until the modules are loaded.
714 * @return bool Is it a known backend?
716 function is_backend() {
717 static $backends = [];
718 $backends[] = '_well_known';
720 $backends[] = 'dfrn_notify';
721 $backends[] = 'fetch';
722 $backends[] = 'hcard';
723 $backends[] = 'hostxrd';
724 $backends[] = 'nodeinfo';
725 $backends[] = 'noscrape';
727 $backends[] = 'poco';
728 $backends[] = 'post';
729 $backends[] = 'proxy';
730 $backends[] = 'pubsub';
731 $backends[] = 'pubsubhubbub';
732 $backends[] = 'receive';
733 $backends[] = 'rsd_xml';
734 $backends[] = 'salmon';
735 $backends[] = 'statistics_json';
738 // Check if current module is in backend or backend flag is set
739 return (in_array($this->module, $backends) || $this->backend);
743 * @brief Checks if the maximum number of database processes is reached
745 * @return bool Is the limit reached?
747 function max_processes_reached() {
748 // Deactivated, needs more investigating if this check really makes sense
751 if ($this->is_backend()) {
752 $process = 'backend';
753 $max_processes = Config::get('system', 'max_processes_backend');
754 if (intval($max_processes) == 0) {
758 $process = 'frontend';
759 $max_processes = Config::get('system', 'max_processes_frontend');
760 if (intval($max_processes) == 0) {
765 $processlist = DBM::processlist();
766 if ($processlist['list'] != '') {
767 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
769 if ($processlist['amount'] > $max_processes) {
770 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
778 * @brief Checks if the minimal memory is reached
780 * @return bool Is the memory limit reached?
782 public function min_memory_reached() {
783 $min_memory = Config::get('system', 'min_memory', 0);
784 if ($min_memory == 0) {
788 if (!is_readable('/proc/meminfo')) {
792 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
795 foreach ($memdata as $line) {
796 list($key, $val) = explode(':', $line);
797 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
798 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
801 if (!isset($meminfo['MemAvailable']) || ! isset($meminfo['MemFree'])) {
805 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
807 $reached = ($free < $min_memory);
810 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
817 * @brief Checks if the maximum load is reached
819 * @return bool Is the load reached?
821 function maxload_reached() {
823 if ($this->is_backend()) {
824 $process = 'backend';
825 $maxsysload = intval(Config::get('system', 'maxloadavg'));
826 if ($maxsysload < 1) {
830 $process = 'frontend';
831 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
832 if ($maxsysload < 1) {
837 $load = current_load();
839 if (intval($load) > $maxsysload) {
840 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
847 function proc_run($args) {
849 if (!function_exists('proc_open')) {
853 // If the last worker fork was less than 2 seconds before then don't fork another one.
854 // This should prevent the forking of masses of workers.
855 $cachekey = 'app:proc_run:started';
856 $result = Cache::get($cachekey);
858 if (!is_null($result) && ( time() - $result) < 2) {
862 // Set the timestamp of the last proc_run
863 Cache::set($cachekey, time(), CACHE_MINUTE);
865 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
867 // add baseurl to args. cli scripts can't construct it
868 $args[] = $this->get_baseurl();
870 for ($x = 0; $x < count($args); $x ++) {
871 $args[$x] = escapeshellarg($args[$x]);
874 $cmdline = implode($args, ' ');
876 if ($this->min_memory_reached()) {
880 if (Config::get('system', 'proc_windows')) {
881 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
883 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
885 if (!is_resource($resource)) {
886 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
889 proc_close($resource);
893 * @brief Returns the system user that is executing the script
895 * This mostly returns something like "www-data".
897 * @return string system username
899 static function systemuser() {
900 if (!function_exists('posix_getpwuid') || ! function_exists('posix_geteuid')) {
904 $processUser = posix_getpwuid(posix_geteuid());
905 return $processUser['name'];
909 * @brief Checks if a given directory is usable for the system
911 * @return boolean the directory is usable
913 static function directory_usable($directory, $check_writable = true) {
914 if ($directory == '') {
915 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
919 if (!file_exists($directory)) {
920 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
923 if (is_file($directory)) {
924 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
927 if (!is_dir($directory)) {
928 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
931 if ($check_writable && !is_writable($directory)) {
932 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);