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 = [];
118 private $curl_content_type;
119 private $curl_headers;
123 * @brief App constructor.
125 * @param string $basepath Path to the app base folder
127 public function __construct($basepath)
129 global $default_timezone;
131 if (!static::directory_usable($basepath, false)) {
132 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
135 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
137 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
138 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
141 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
143 date_default_timezone_set($this->timezone);
145 $this->performance['start'] = microtime(true);
146 $this->performance['database'] = 0;
147 $this->performance['database_write'] = 0;
148 $this->performance['network'] = 0;
149 $this->performance['file'] = 0;
150 $this->performance['rendering'] = 0;
151 $this->performance['parser'] = 0;
152 $this->performance['marktime'] = 0;
153 $this->performance['markstart'] = microtime(true);
155 $this->callstack['database'] = [];
156 $this->callstack['database_write'] = [];
157 $this->callstack['network'] = [];
158 $this->callstack['file'] = [];
159 $this->callstack['rendering'] = [];
160 $this->callstack['parser'] = [];
166 $this->query_string = '';
168 $this->process_id = uniqid('log', true);
172 $this->scheme = 'http';
174 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
175 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
176 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
177 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
178 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
179 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
181 $this->scheme = 'https';
184 if (x($_SERVER, 'SERVER_NAME')) {
185 $this->hostname = $_SERVER['SERVER_NAME'];
187 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
188 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
191 * Figure out if we are running at the top of a domain
192 * or in a sub-directory and adjust accordingly
195 /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
196 $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
197 if (isset($path) && strlen($path) && ($path != $this->path)) {
203 get_include_path() . PATH_SEPARATOR
204 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
205 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
209 if (is_array($_SERVER['argv']) && $_SERVER['argc'] > 1 && substr(end($_SERVER['argv']), 0, 4) == 'http') {
210 $this->set_baseurl(array_pop($_SERVER['argv']));
214 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
215 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
217 // removing trailing / - maybe a nginx problem
218 $this->query_string = ltrim($this->query_string, '/');
219 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
220 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
222 // removing trailing / - maybe a nginx problem
223 $this->query_string = ltrim($this->query_string, '/');
226 if (x($_GET, 'pagename')) {
227 $this->cmd = trim($_GET['pagename'], '/\\');
228 } elseif (x($_GET, 'q')) {
229 $this->cmd = trim($_GET['q'], '/\\');
233 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
235 // unix style "homedir"
236 if (substr($this->cmd, 0, 1) === '~') {
237 $this->cmd = 'profile/' . substr($this->cmd, 1);
240 // Diaspora style profile url
241 if (substr($this->cmd, 0, 2) === 'u/') {
242 $this->cmd = 'profile/' . substr($this->cmd, 2);
246 * Break the URL path into C style argc/argv style arguments for our
247 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
248 * will be 3 (integer) and $this->argv will contain:
254 * There will always be one argument. If provided a naked domain
255 * URL, $this->argv[0] is set to "home".
258 $this->argv = explode('/', $this->cmd);
259 $this->argc = count($this->argv);
260 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
261 $this->module = str_replace('.', '_', $this->argv[0]);
262 $this->module = str_replace('-', '_', $this->module);
265 $this->argv = ['home'];
266 $this->module = 'home';
269 // See if there is any page number information, and initialise pagination
270 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
271 $this->pager['itemspage'] = 50;
272 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
274 if ($this->pager['start'] < 0) {
275 $this->pager['start'] = 0;
277 $this->pager['total'] = 0;
279 // Detect mobile devices
280 $mobile_detect = new MobileDetect();
281 $this->is_mobile = $mobile_detect->isMobile();
282 $this->is_tablet = $mobile_detect->isTablet();
285 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)');
287 // Register template engines
288 $dc = get_declared_classes();
289 foreach ($dc as $k) {
290 if (in_array('Friendica\Render\ITemplateEngine', class_implements($k))) {
291 $this->register_template_engine($k);
299 * @brief Returns the base filesystem path of the App
301 * It first checks for the internal variable, then for DOCUMENT_ROOT and
306 public function get_basepath()
308 $basepath = $this->basepath;
311 $basepath = Config::get('system', 'basepath');
314 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
315 $basepath = $_SERVER['DOCUMENT_ROOT'];
318 if (!$basepath && x($_SERVER, 'PWD')) {
319 $basepath = $_SERVER['PWD'];
322 return self::realpath($basepath);
326 * @brief Returns a normalized file path
328 * This is a wrapper for the "realpath" function.
329 * That function cannot detect the real path when some folders aren't readable.
330 * Since this could happen with some hosters we need to handle this.
332 * @param string $path The path that is about to be normalized
333 * @return string normalized path - when possible
335 public static function realpath($path)
337 $normalized = realpath($path);
339 if (!is_bool($normalized)) {
346 public function get_scheme()
348 return $this->scheme;
352 * @brief Retrieves the Friendica instance base URL
354 * This function assembles the base URL from multiple parts:
355 * - Protocol is determined either by the request or a combination of
356 * system.ssl_policy and the $ssl parameter.
357 * - Host name is determined either by system.hostname or inferred from request
358 * - Path is inferred from SCRIPT_NAME
360 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
362 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
363 * @return string Friendica server base URL
365 public function get_baseurl($ssl = false)
367 $scheme = $this->scheme;
369 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
373 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
374 // (and also the login link). Anything seen by an outsider will have it turned off.
376 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
384 if (Config::get('config', 'hostname') != '') {
385 $this->hostname = Config::get('config', 'hostname');
388 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
392 * @brief Initializes the baseurl components
394 * Clears the baseurl cache to prevent inconsistencies
398 public function set_baseurl($url)
400 $parsed = @parse_url($url);
403 $this->scheme = $parsed['scheme'];
405 $hostname = $parsed['host'];
406 if (x($parsed, 'port')) {
407 $hostname .= ':' . $parsed['port'];
409 if (x($parsed, 'path')) {
410 $this->path = trim($parsed['path'], '\\/');
413 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
414 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
417 if (Config::get('config', 'hostname') != '') {
418 $this->hostname = Config::get('config', 'hostname');
421 if (!isset($this->hostname) || ( $this->hostname == '')) {
422 $this->hostname = $hostname;
427 public function get_hostname()
429 if (Config::get('config', 'hostname') != '') {
430 $this->hostname = Config::get('config', 'hostname');
433 return $this->hostname;
436 public function get_path()
441 public function set_pager_total($n)
443 $this->pager['total'] = intval($n);
446 public function set_pager_itemspage($n)
448 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
449 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
452 public function set_pager_page($n)
454 $this->pager['page'] = $n;
455 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
458 public function init_pagehead()
460 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
462 // If the update is 'deactivated' set it to the highest integer number (~24 days)
464 $interval = 2147483647;
467 if ($interval < 10000) {
471 // compose the page title from the sitename and the
472 // current module called
473 if (!$this->module == '') {
474 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
476 $this->page['title'] = $this->config['sitename'];
479 /* put the head template at the beginning of page['htmlhead']
480 * since the code added by the modules frequently depends on it
483 if (!isset($this->page['htmlhead'])) {
484 $this->page['htmlhead'] = '';
487 // If we're using Smarty, then doing replace_macros() will replace
488 // any unrecognized variables with a blank string. Since we delay
489 // replacing $stylesheet until later, we need to replace it now
490 // with another variable name
491 if ($this->theme['template_engine'] === 'smarty3') {
492 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
494 $stylesheet = '$stylesheet';
497 $shortcut_icon = Config::get('system', 'shortcut_icon');
498 if ($shortcut_icon == '') {
499 $shortcut_icon = 'images/friendica-32.png';
502 $touch_icon = Config::get('system', 'touch_icon');
503 if ($touch_icon == '') {
504 $touch_icon = 'images/friendica-128.png';
507 // get data wich is needed for infinite scroll on the network page
508 $invinite_scroll = infinite_scroll_data($this->module);
510 $tpl = get_markup_template('head.tpl');
511 $this->page['htmlhead'] = replace_macros($tpl, [
512 '$baseurl' => $this->get_baseurl(),
513 '$local_user' => local_user(),
514 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
515 '$delitem' => t('Delete this item?'),
516 '$showmore' => t('show more'),
517 '$showfewer' => t('show fewer'),
518 '$update_interval' => $interval,
519 '$shortcut_icon' => $shortcut_icon,
520 '$touch_icon' => $touch_icon,
521 '$stylesheet' => $stylesheet,
522 '$infinite_scroll' => $invinite_scroll,
523 ]) . $this->page['htmlhead'];
526 public function init_page_end()
528 if (!isset($this->page['end'])) {
529 $this->page['end'] = '';
531 $tpl = get_markup_template('end.tpl');
532 $this->page['end'] = replace_macros($tpl, [
533 '$baseurl' => $this->get_baseurl()
534 ]) . $this->page['end'];
537 public function set_curl_code($code)
539 $this->curl_code = $code;
542 public function get_curl_code()
544 return $this->curl_code;
547 public function set_curl_content_type($content_type)
549 $this->curl_content_type = $content_type;
552 public function get_curl_content_type()
554 return $this->curl_content_type;
557 public function set_curl_headers($headers)
559 $this->curl_headers = $headers;
562 public function get_curl_headers()
564 return $this->curl_headers;
568 * @brief Removes the base url from an url. This avoids some mixed content problems.
570 * @param string $orig_url
572 * @return string The cleaned url
574 public function remove_baseurl($orig_url)
576 // Remove the hostname from the url if it is an internal link
577 $nurl = normalise_link($orig_url);
578 $base = normalise_link($this->get_baseurl());
579 $url = str_replace($base . '/', '', $nurl);
581 // if it is an external link return the orignal value
582 if ($url == normalise_link($orig_url)) {
590 * @brief Register template engine class
592 * @param string $class
594 private function register_template_engine($class)
596 $v = get_class_vars($class);
599 $this->template_engines[$name] = $class;
601 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
607 * @brief Return template engine instance.
609 * If $name is not defined, return engine defined by theme,
612 * @return object Template Engine instance
614 public function template_engine()
616 $template_engine = 'smarty3';
617 if (x($this->theme, 'template_engine')) {
618 $template_engine = $this->theme['template_engine'];
621 if (isset($this->template_engines[$template_engine])) {
622 if (isset($this->template_engine_instance[$template_engine])) {
623 return $this->template_engine_instance[$template_engine];
625 $class = $this->template_engines[$template_engine];
627 $this->template_engine_instance[$template_engine] = $obj;
632 echo "template engine <tt>$template_engine</tt> is not registered!\n";
637 * @brief Returns the active template engine.
641 public function get_template_engine()
643 return $this->theme['template_engine'];
646 public function set_template_engine($engine = 'smarty3')
648 $this->theme['template_engine'] = $engine;
651 public function get_template_ldelim($engine = 'smarty3')
653 return $this->ldelim[$engine];
656 public function get_template_rdelim($engine = 'smarty3')
658 return $this->rdelim[$engine];
661 public function save_timestamp($stamp, $value)
663 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
667 $duration = (float) (microtime(true) - $stamp);
669 if (!isset($this->performance[$value])) {
670 // Prevent ugly E_NOTICE
671 $this->performance[$value] = 0;
674 $this->performance[$value] += (float) $duration;
675 $this->performance['marktime'] += (float) $duration;
677 $callstack = System::callstack();
679 if (!isset($this->callstack[$value][$callstack])) {
680 // Prevent ugly E_NOTICE
681 $this->callstack[$value][$callstack] = 0;
684 $this->callstack[$value][$callstack] += (float) $duration;
687 public function get_useragent()
690 FRIENDICA_PLATFORM . " '" .
691 FRIENDICA_CODENAME . "' " .
692 FRIENDICA_VERSION . '-' .
693 DB_UPDATE_VERSION . '; ' .
694 $this->get_baseurl();
697 public function is_friendica_app()
699 return $this->is_friendica_app;
703 * @brief Checks if the site is called via a backend process
705 * This isn't a perfect solution. But we need this check very early.
706 * So we cannot wait until the modules are loaded.
708 * @return bool Is it a known backend?
710 public function is_backend()
734 // Check if current module is in backend or backend flag is set
735 return (in_array($this->module, $backends) || $this->backend);
739 * @brief Checks if the maximum number of database processes is reached
741 * @return bool Is the limit reached?
743 public function max_processes_reached()
745 // Deactivated, needs more investigating if this check really makes sense
749 * Commented out to suppress static analyzer issues
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);
779 * @brief Checks if the minimal memory is reached
781 * @return bool Is the memory limit reached?
783 public function min_memory_reached()
785 $min_memory = Config::get('system', 'min_memory', 0);
786 if ($min_memory == 0) {
790 if (!is_readable('/proc/meminfo')) {
794 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
797 foreach ($memdata as $line) {
798 list($key, $val) = explode(':', $line);
799 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
800 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
803 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
807 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
809 $reached = ($free < $min_memory);
812 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
819 * @brief Checks if the maximum load is reached
821 * @return bool Is the load reached?
823 public function maxload_reached()
825 if ($this->is_backend()) {
826 $process = 'backend';
827 $maxsysload = intval(Config::get('system', 'maxloadavg'));
828 if ($maxsysload < 1) {
832 $process = 'frontend';
833 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
834 if ($maxsysload < 1) {
839 $load = current_load();
841 if (intval($load) > $maxsysload) {
842 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
849 public function proc_run($args)
851 if (!function_exists('proc_open')) {
855 // If the last worker fork was less than 2 seconds before then don't fork another one.
856 // This should prevent the forking of masses of workers.
857 $cachekey = 'app:proc_run:started';
858 $result = Cache::get($cachekey);
860 if (!is_null($result) && ( time() - $result) < 2) {
864 // Set the timestamp of the last proc_run
865 Cache::set($cachekey, time(), CACHE_MINUTE);
867 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
869 // add baseurl to args. cli scripts can't construct it
870 $args[] = $this->get_baseurl();
872 for ($x = 0; $x < count($args); $x ++) {
873 $args[$x] = escapeshellarg($args[$x]);
876 $cmdline = implode(' ', $args);
878 if ($this->min_memory_reached()) {
882 if (Config::get('system', 'proc_windows')) {
883 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
885 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
887 if (!is_resource($resource)) {
888 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
891 proc_close($resource);
895 * @brief Returns the system user that is executing the script
897 * This mostly returns something like "www-data".
899 * @return string system username
901 private static function systemuser()
903 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
907 $processUser = posix_getpwuid(posix_geteuid());
908 return $processUser['name'];
912 * @brief Checks if a given directory is usable for the system
914 * @return boolean the directory is usable
916 public static function directory_usable($directory, $check_writable = true)
918 if ($directory == '') {
919 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
923 if (!file_exists($directory)) {
924 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
928 if (is_file($directory)) {
929 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
933 if (!is_dir($directory)) {
934 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
938 if ($check_writable && !is_writable($directory)) {
939 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);