7 use Friendica\Core\Cache;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
13 use Detection\MobileDetect;
17 require_once 'boot.php';
18 require_once 'include/text.php';
24 * @brief Our main application structure for the life of this page.
26 * Primarily deals with the URL that got us here
27 * and tries to make some sense of it, and
28 * stores our page contents and config storage
29 * and anything else that might need to be passed around
30 * before we spit the page out.
35 public $module_loaded = false;
36 public $module_class = null;
50 public $error = false;
61 public $interactive = true;
63 public $addons_admin = [];
66 public $is_mobile = false;
67 public $is_tablet = false;
68 public $is_friendica_app;
69 public $performance = [];
70 public $callstack = [];
71 public $theme_info = [];
72 public $backend = true;
75 // Allow themes to control internal parameters
76 // by changing App values in theme.php
78 public $sourcename = '';
79 public $videowidth = 425;
80 public $videoheight = 350;
81 public $force_max_items = 0;
82 public $theme_events_in_profile = true;
85 * @brief An array for all theme-controllable parameters
87 * Mostly unimplemented yet. Only options 'template_engine' and
94 'force_max_items' => 0,
96 'template_engine' => 'smarty3',
100 * @brief An array of registered template engines ('name'=>'class name')
102 public $template_engines = [];
105 * @brief An array of instanced template engines ('name'=>'instance')
107 public $template_engine_instance = [];
121 private $curl_content_type;
122 private $curl_headers;
126 * @brief App constructor.
128 * @param string $basepath Path to the app base folder
130 public function __construct($basepath)
132 global $default_timezone;
134 if (!static::directory_usable($basepath, false)) {
135 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
138 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
140 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
141 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
144 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
146 date_default_timezone_set($this->timezone);
148 $this->performance['start'] = microtime(true);
149 $this->performance['database'] = 0;
150 $this->performance['database_write'] = 0;
151 $this->performance['network'] = 0;
152 $this->performance['file'] = 0;
153 $this->performance['rendering'] = 0;
154 $this->performance['parser'] = 0;
155 $this->performance['marktime'] = 0;
156 $this->performance['markstart'] = microtime(true);
158 $this->callstack['database'] = [];
159 $this->callstack['database_write'] = [];
160 $this->callstack['network'] = [];
161 $this->callstack['file'] = [];
162 $this->callstack['rendering'] = [];
163 $this->callstack['parser'] = [];
169 $this->query_string = '';
171 $this->process_id = uniqid('log', true);
175 $this->scheme = 'http';
177 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
178 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
179 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
180 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
181 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
182 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
184 $this->scheme = 'https';
187 if (x($_SERVER, 'SERVER_NAME')) {
188 $this->hostname = $_SERVER['SERVER_NAME'];
190 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
191 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
194 * Figure out if we are running at the top of a domain
195 * or in a sub-directory and adjust accordingly
198 /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
199 $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
200 if (isset($path) && strlen($path) && ($path != $this->path)) {
206 get_include_path() . PATH_SEPARATOR
207 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
208 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
212 if (is_array($_SERVER['argv']) && $_SERVER['argc'] > 1 && substr(end($_SERVER['argv']), 0, 4) == 'http') {
213 $this->set_baseurl(array_pop($_SERVER['argv']));
217 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
218 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
220 // removing trailing / - maybe a nginx problem
221 $this->query_string = ltrim($this->query_string, '/');
222 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
223 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
225 // removing trailing / - maybe a nginx problem
226 $this->query_string = ltrim($this->query_string, '/');
229 if (x($_GET, 'pagename')) {
230 $this->cmd = trim($_GET['pagename'], '/\\');
231 } elseif (x($_GET, 'q')) {
232 $this->cmd = trim($_GET['q'], '/\\');
236 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
238 // unix style "homedir"
239 if (substr($this->cmd, 0, 1) === '~') {
240 $this->cmd = 'profile/' . substr($this->cmd, 1);
243 // Diaspora style profile url
244 if (substr($this->cmd, 0, 2) === 'u/') {
245 $this->cmd = 'profile/' . substr($this->cmd, 2);
249 * Break the URL path into C style argc/argv style arguments for our
250 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
251 * will be 3 (integer) and $this->argv will contain:
257 * There will always be one argument. If provided a naked domain
258 * URL, $this->argv[0] is set to "home".
261 $this->argv = explode('/', $this->cmd);
262 $this->argc = count($this->argv);
263 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
264 $this->module = str_replace('.', '_', $this->argv[0]);
265 $this->module = str_replace('-', '_', $this->module);
268 $this->argv = ['home'];
269 $this->module = 'home';
272 // See if there is any page number information, and initialise pagination
273 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
274 $this->pager['itemspage'] = 50;
275 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
277 if ($this->pager['start'] < 0) {
278 $this->pager['start'] = 0;
280 $this->pager['total'] = 0;
282 // Detect mobile devices
283 $mobile_detect = new MobileDetect();
284 $this->is_mobile = $mobile_detect->isMobile();
285 $this->is_tablet = $mobile_detect->isTablet();
288 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)');
290 // Register template engines
291 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
297 * @brief Returns the base filesystem path of the App
299 * It first checks for the internal variable, then for DOCUMENT_ROOT and
304 public function get_basepath()
306 $basepath = $this->basepath;
309 $basepath = Config::get('system', 'basepath');
312 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
313 $basepath = $_SERVER['DOCUMENT_ROOT'];
316 if (!$basepath && x($_SERVER, 'PWD')) {
317 $basepath = $_SERVER['PWD'];
320 return self::realpath($basepath);
324 * @brief Returns a normalized file path
326 * This is a wrapper for the "realpath" function.
327 * That function cannot detect the real path when some folders aren't readable.
328 * Since this could happen with some hosters we need to handle this.
330 * @param string $path The path that is about to be normalized
331 * @return string normalized path - when possible
333 public static function realpath($path)
335 $normalized = realpath($path);
337 if (!is_bool($normalized)) {
344 public function get_scheme()
346 return $this->scheme;
350 * @brief Retrieves the Friendica instance base URL
352 * This function assembles the base URL from multiple parts:
353 * - Protocol is determined either by the request or a combination of
354 * system.ssl_policy and the $ssl parameter.
355 * - Host name is determined either by system.hostname or inferred from request
356 * - Path is inferred from SCRIPT_NAME
358 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
360 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
361 * @return string Friendica server base URL
363 public function get_baseurl($ssl = false)
365 $scheme = $this->scheme;
367 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
371 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
372 // (and also the login link). Anything seen by an outsider will have it turned off.
374 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
382 if (Config::get('config', 'hostname') != '') {
383 $this->hostname = Config::get('config', 'hostname');
386 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
390 * @brief Initializes the baseurl components
392 * Clears the baseurl cache to prevent inconsistencies
396 public function set_baseurl($url)
398 $parsed = @parse_url($url);
401 $this->scheme = $parsed['scheme'];
403 $hostname = $parsed['host'];
404 if (x($parsed, 'port')) {
405 $hostname .= ':' . $parsed['port'];
407 if (x($parsed, 'path')) {
408 $this->path = trim($parsed['path'], '\\/');
411 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
412 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
415 if (Config::get('config', 'hostname') != '') {
416 $this->hostname = Config::get('config', 'hostname');
419 if (!isset($this->hostname) || ( $this->hostname == '')) {
420 $this->hostname = $hostname;
425 public function get_hostname()
427 if (Config::get('config', 'hostname') != '') {
428 $this->hostname = Config::get('config', 'hostname');
431 return $this->hostname;
434 public function get_path()
439 public function set_pager_total($n)
441 $this->pager['total'] = intval($n);
444 public function set_pager_itemspage($n)
446 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
447 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
450 public function set_pager_page($n)
452 $this->pager['page'] = $n;
453 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
456 public function init_pagehead()
458 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
460 // If the update is 'deactivated' set it to the highest integer number (~24 days)
462 $interval = 2147483647;
465 if ($interval < 10000) {
469 // compose the page title from the sitename and the
470 // current module called
471 if (!$this->module == '') {
472 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
474 $this->page['title'] = $this->config['sitename'];
477 /* put the head template at the beginning of page['htmlhead']
478 * since the code added by the modules frequently depends on it
481 if (!isset($this->page['htmlhead'])) {
482 $this->page['htmlhead'] = '';
485 // If we're using Smarty, then doing replace_macros() will replace
486 // any unrecognized variables with a blank string. Since we delay
487 // replacing $stylesheet until later, we need to replace it now
488 // with another variable name
489 if ($this->theme['template_engine'] === 'smarty3') {
490 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
492 $stylesheet = '$stylesheet';
495 $shortcut_icon = Config::get('system', 'shortcut_icon');
496 if ($shortcut_icon == '') {
497 $shortcut_icon = 'images/friendica-32.png';
500 $touch_icon = Config::get('system', 'touch_icon');
501 if ($touch_icon == '') {
502 $touch_icon = 'images/friendica-128.png';
505 // get data wich is needed for infinite scroll on the network page
506 $invinite_scroll = infinite_scroll_data($this->module);
508 $tpl = get_markup_template('head.tpl');
509 $this->page['htmlhead'] = replace_macros($tpl, [
510 '$baseurl' => $this->get_baseurl(),
511 '$local_user' => local_user(),
512 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
513 '$delitem' => L10n::t('Delete this item?'),
514 '$showmore' => L10n::t('show more'),
515 '$showfewer' => L10n::t('show fewer'),
516 '$update_interval' => $interval,
517 '$shortcut_icon' => $shortcut_icon,
518 '$touch_icon' => $touch_icon,
519 '$stylesheet' => $stylesheet,
520 '$infinite_scroll' => $invinite_scroll,
521 ]) . $this->page['htmlhead'];
524 public function init_page_end()
526 if (!isset($this->page['end'])) {
527 $this->page['end'] = '';
529 $tpl = get_markup_template('end.tpl');
530 $this->page['end'] = replace_macros($tpl, [
531 '$baseurl' => $this->get_baseurl()
532 ]) . $this->page['end'];
535 public function set_curl_code($code)
537 $this->curl_code = $code;
540 public function get_curl_code()
542 return $this->curl_code;
545 public function set_curl_content_type($content_type)
547 $this->curl_content_type = $content_type;
550 public function get_curl_content_type()
552 return $this->curl_content_type;
555 public function set_curl_headers($headers)
557 $this->curl_headers = $headers;
560 public function get_curl_headers()
562 return $this->curl_headers;
566 * @brief Removes the base url from an url. This avoids some mixed content problems.
568 * @param string $orig_url
570 * @return string The cleaned url
572 public function remove_baseurl($orig_url)
574 // Remove the hostname from the url if it is an internal link
575 $nurl = normalise_link($orig_url);
576 $base = normalise_link($this->get_baseurl());
577 $url = str_replace($base . '/', '', $nurl);
579 // if it is an external link return the orignal value
580 if ($url == normalise_link($orig_url)) {
588 * @brief Register template engine class
590 * @param string $class
592 private function register_template_engine($class)
594 $v = get_class_vars($class);
597 $this->template_engines[$name] = $class;
599 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
605 * @brief Return template engine instance.
607 * If $name is not defined, return engine defined by theme,
610 * @return object Template Engine instance
612 public function template_engine()
614 $template_engine = 'smarty3';
615 if (x($this->theme, 'template_engine')) {
616 $template_engine = $this->theme['template_engine'];
619 if (isset($this->template_engines[$template_engine])) {
620 if (isset($this->template_engine_instance[$template_engine])) {
621 return $this->template_engine_instance[$template_engine];
623 $class = $this->template_engines[$template_engine];
625 $this->template_engine_instance[$template_engine] = $obj;
630 echo "template engine <tt>$template_engine</tt> is not registered!\n";
635 * @brief Returns the active template engine.
639 public function get_template_engine()
641 return $this->theme['template_engine'];
644 public function set_template_engine($engine = 'smarty3')
646 $this->theme['template_engine'] = $engine;
649 public function get_template_ldelim($engine = 'smarty3')
651 return $this->ldelim[$engine];
654 public function get_template_rdelim($engine = 'smarty3')
656 return $this->rdelim[$engine];
659 public function save_timestamp($stamp, $value)
661 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
665 $duration = (float) (microtime(true) - $stamp);
667 if (!isset($this->performance[$value])) {
668 // Prevent ugly E_NOTICE
669 $this->performance[$value] = 0;
672 $this->performance[$value] += (float) $duration;
673 $this->performance['marktime'] += (float) $duration;
675 $callstack = System::callstack();
677 if (!isset($this->callstack[$value][$callstack])) {
678 // Prevent ugly E_NOTICE
679 $this->callstack[$value][$callstack] = 0;
682 $this->callstack[$value][$callstack] += (float) $duration;
685 public function get_useragent()
688 FRIENDICA_PLATFORM . " '" .
689 FRIENDICA_CODENAME . "' " .
690 FRIENDICA_VERSION . '-' .
691 DB_UPDATE_VERSION . '; ' .
692 $this->get_baseurl();
695 public function is_friendica_app()
697 return $this->is_friendica_app;
701 * @brief Checks if the site is called via a backend process
703 * This isn't a perfect solution. But we need this check very early.
704 * So we cannot wait until the modules are loaded.
706 * @return bool Is it a known backend?
708 public function is_backend()
732 // Check if current module is in backend or backend flag is set
733 return (in_array($this->module, $backends) || $this->backend);
737 * @brief Checks if the maximum number of database processes is reached
739 * @return bool Is the limit reached?
741 public function max_processes_reached()
743 // Deactivated, needs more investigating if this check really makes sense
747 * Commented out to suppress static analyzer issues
749 if ($this->is_backend()) {
750 $process = 'backend';
751 $max_processes = Config::get('system', 'max_processes_backend');
752 if (intval($max_processes) == 0) {
756 $process = 'frontend';
757 $max_processes = Config::get('system', 'max_processes_frontend');
758 if (intval($max_processes) == 0) {
763 $processlist = DBM::processlist();
764 if ($processlist['list'] != '') {
765 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
767 if ($processlist['amount'] > $max_processes) {
768 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
777 * @brief Checks if the minimal memory is reached
779 * @return bool Is the memory limit reached?
781 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 public 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 public 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 private static function systemuser()
901 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
905 $processUser = posix_getpwuid(posix_geteuid());
906 return $processUser['name'];
910 * @brief Checks if a given directory is usable for the system
912 * @return boolean the directory is usable
914 public static function directory_usable($directory, $check_writable = true)
916 if ($directory == '') {
917 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
921 if (!file_exists($directory)) {
922 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
926 if (is_file($directory)) {
927 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
931 if (!is_dir($directory)) {
932 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
936 if ($check_writable && !is_writable($directory)) {
937 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);