Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1486 lines
38KB

  1. <?php
  2. /**
  3. * @file src/App.php
  4. */
  5. namespace Friendica;
  6. use Detection\MobileDetect;
  7. use Exception;
  8. use Friendica\App;
  9. use Friendica\Core\Config;
  10. use Friendica\Core\L10n;
  11. use Friendica\Core\PConfig;
  12. use Friendica\Core\System;
  13. use Friendica\Database\DBA;
  14. require_once 'boot.php';
  15. require_once 'include/dba.php';
  16. require_once 'include/text.php';
  17. /**
  18. *
  19. * class: App
  20. *
  21. * @brief Our main application structure for the life of this page.
  22. *
  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.
  28. *
  29. */
  30. class App
  31. {
  32. public $module_loaded = false;
  33. public $module_class = null;
  34. public $query_string = '';
  35. public $config = [];
  36. public $page = [];
  37. public $pager = [];
  38. public $page_offset;
  39. public $profile;
  40. public $profile_uid;
  41. public $user;
  42. public $cid;
  43. public $contact;
  44. public $contacts;
  45. public $page_contact;
  46. public $content;
  47. public $data = [];
  48. public $error = false;
  49. public $cmd = '';
  50. public $argv;
  51. public $argc;
  52. public $module;
  53. public $strings;
  54. public $basepath;
  55. public $urlpath;
  56. public $hooks = [];
  57. public $timezone;
  58. public $interactive = true;
  59. public $addons;
  60. public $addons_admin = [];
  61. public $apps = [];
  62. public $identities;
  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;
  70. public $nav_sel;
  71. public $category;
  72. // Allow themes to control internal parameters
  73. // by changing App values in theme.php
  74. public $sourcename = '';
  75. public $videowidth = 425;
  76. public $videoheight = 350;
  77. public $force_max_items = 0;
  78. public $theme_events_in_profile = true;
  79. public $stylesheets = [];
  80. public $footerScripts = [];
  81. /**
  82. * Register a stylesheet file path to be included in the <head> tag of every page.
  83. * Inclusion is done in App->initHead().
  84. * The path can be absolute or relative to the Friendica installation base folder.
  85. *
  86. * @see App->initHead()
  87. *
  88. * @param string $path
  89. */
  90. public function registerStylesheet($path)
  91. {
  92. $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
  93. $this->stylesheets[] = trim($url, '/');
  94. }
  95. /**
  96. * Register a javascript file path to be included in the <footer> tag of every page.
  97. * Inclusion is done in App->initFooter().
  98. * The path can be absolute or relative to the Friendica installation base folder.
  99. *
  100. * @see App->initFooter()
  101. *
  102. * @param string $path
  103. */
  104. public function registerFooterScript($path)
  105. {
  106. $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
  107. $this->footerScripts[] = trim($url, '/');
  108. }
  109. /**
  110. * @brief An array for all theme-controllable parameters
  111. *
  112. * Mostly unimplemented yet. Only options 'template_engine' and
  113. * beyond are used.
  114. */
  115. public $theme = [
  116. 'sourcename' => '',
  117. 'videowidth' => 425,
  118. 'videoheight' => 350,
  119. 'force_max_items' => 0,
  120. 'stylesheet' => '',
  121. 'template_engine' => 'smarty3',
  122. ];
  123. /**
  124. * @brief An array of registered template engines ('name'=>'class name')
  125. */
  126. public $template_engines = [];
  127. /**
  128. * @brief An array of instanced template engines ('name'=>'instance')
  129. */
  130. public $template_engine_instance = [];
  131. public $process_id;
  132. public $queue;
  133. private $ldelim = [
  134. 'internal' => '',
  135. 'smarty3' => '{{'
  136. ];
  137. private $rdelim = [
  138. 'internal' => '',
  139. 'smarty3' => '}}'
  140. ];
  141. private $scheme;
  142. private $hostname;
  143. private $curl_code;
  144. private $curl_content_type;
  145. private $curl_headers;
  146. /**
  147. * @brief App constructor.
  148. *
  149. * @param string $basepath Path to the app base folder
  150. *
  151. * @throws Exception if the Basepath is not usable
  152. */
  153. public function __construct($basepath)
  154. {
  155. if (!static::directory_usable($basepath, false)) {
  156. throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
  157. }
  158. BaseObject::setApp($this);
  159. $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
  160. $this->performance['start'] = microtime(true);
  161. $this->performance['database'] = 0;
  162. $this->performance['database_write'] = 0;
  163. $this->performance['cache'] = 0;
  164. $this->performance['cache_write'] = 0;
  165. $this->performance['network'] = 0;
  166. $this->performance['file'] = 0;
  167. $this->performance['rendering'] = 0;
  168. $this->performance['parser'] = 0;
  169. $this->performance['marktime'] = 0;
  170. $this->performance['markstart'] = microtime(true);
  171. $this->callstack['database'] = [];
  172. $this->callstack['database_write'] = [];
  173. $this->callstack['cache'] = [];
  174. $this->callstack['cache_write'] = [];
  175. $this->callstack['network'] = [];
  176. $this->callstack['file'] = [];
  177. $this->callstack['rendering'] = [];
  178. $this->callstack['parser'] = [];
  179. $this->reload();
  180. set_time_limit(0);
  181. // This has to be quite large to deal with embedded private photos
  182. ini_set('pcre.backtrack_limit', 500000);
  183. $this->scheme = 'http';
  184. if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
  185. (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
  186. (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
  187. (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
  188. (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
  189. (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
  190. ) {
  191. $this->scheme = 'https';
  192. }
  193. if (x($_SERVER, 'SERVER_NAME')) {
  194. $this->hostname = $_SERVER['SERVER_NAME'];
  195. if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
  196. $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
  197. }
  198. }
  199. set_include_path(
  200. get_include_path() . PATH_SEPARATOR
  201. . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
  202. . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
  203. . $this->basepath);
  204. if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
  205. $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
  206. } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
  207. $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
  208. }
  209. // removing trailing / - maybe a nginx problem
  210. $this->query_string = ltrim($this->query_string, '/');
  211. if (!empty($_GET['pagename'])) {
  212. $this->cmd = trim($_GET['pagename'], '/\\');
  213. } elseif (!empty($_GET['q'])) {
  214. $this->cmd = trim($_GET['q'], '/\\');
  215. }
  216. // fix query_string
  217. $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
  218. // unix style "homedir"
  219. if (substr($this->cmd, 0, 1) === '~') {
  220. $this->cmd = 'profile/' . substr($this->cmd, 1);
  221. }
  222. // Diaspora style profile url
  223. if (substr($this->cmd, 0, 2) === 'u/') {
  224. $this->cmd = 'profile/' . substr($this->cmd, 2);
  225. }
  226. /*
  227. * Break the URL path into C style argc/argv style arguments for our
  228. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  229. * will be 3 (integer) and $this->argv will contain:
  230. * [0] => 'module'
  231. * [1] => 'arg1'
  232. * [2] => 'arg2'
  233. *
  234. *
  235. * There will always be one argument. If provided a naked domain
  236. * URL, $this->argv[0] is set to "home".
  237. */
  238. $this->argv = explode('/', $this->cmd);
  239. $this->argc = count($this->argv);
  240. if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
  241. $this->module = str_replace('.', '_', $this->argv[0]);
  242. $this->module = str_replace('-', '_', $this->module);
  243. } else {
  244. $this->argc = 1;
  245. $this->argv = ['home'];
  246. $this->module = 'home';
  247. }
  248. // See if there is any page number information, and initialise pagination
  249. $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
  250. $this->pager['itemspage'] = 50;
  251. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  252. if ($this->pager['start'] < 0) {
  253. $this->pager['start'] = 0;
  254. }
  255. $this->pager['total'] = 0;
  256. // Detect mobile devices
  257. $mobile_detect = new MobileDetect();
  258. $this->is_mobile = $mobile_detect->isMobile();
  259. $this->is_tablet = $mobile_detect->isTablet();
  260. // Friendica-Client
  261. $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
  262. // Register template engines
  263. $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
  264. }
  265. /**
  266. * Reloads the whole app instance
  267. */
  268. public function reload()
  269. {
  270. // The order of the following calls is important to ensure proper initialization
  271. $this->loadConfigFiles();
  272. $this->loadDatabase();
  273. App\Mode::determine($this->basepath);
  274. $this->determineUrlPath();
  275. Config::load();
  276. if (App\Mode::has(App\Mode::DBAVAILABLE)) {
  277. Core\Addon::loadHooks();
  278. $this->loadAddonConfig();
  279. }
  280. $this->loadDefaultTimezone();
  281. $this->page = [
  282. 'aside' => '',
  283. 'bottom' => '',
  284. 'content' => '',
  285. 'footer' => '',
  286. 'htmlhead' => '',
  287. 'nav' => '',
  288. 'page_title' => '',
  289. 'right_aside' => '',
  290. 'template' => '',
  291. 'title' => ''
  292. ];
  293. $this->process_id = System::processID('log');
  294. }
  295. /**
  296. * Load the configuration files
  297. *
  298. * First loads the default value for all the configuration keys, then the legacy configuration files, then the
  299. * expected local.ini.php
  300. */
  301. private function loadConfigFiles()
  302. {
  303. $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
  304. $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
  305. // Legacy .htconfig.php support
  306. if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
  307. $a = $this;
  308. include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
  309. }
  310. // Legacy .htconfig.php support
  311. if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
  312. $a = $this;
  313. include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
  314. $this->setConfigValue('database', 'hostname', $db_host);
  315. $this->setConfigValue('database', 'username', $db_user);
  316. $this->setConfigValue('database', 'password', $db_pass);
  317. $this->setConfigValue('database', 'database', $db_data);
  318. if (isset($a->config['system']['db_charset'])) {
  319. $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
  320. }
  321. unset($db_host, $db_user, $db_pass, $db_data);
  322. if (isset($default_timezone)) {
  323. $this->setConfigValue('system', 'default_timezone', $default_timezone);
  324. unset($default_timezone);
  325. }
  326. if (isset($pidfile)) {
  327. $this->setConfigValue('system', 'pidfile', $pidfile);
  328. unset($pidfile);
  329. }
  330. if (isset($lang)) {
  331. $this->setConfigValue('system', 'language', $lang);
  332. unset($lang);
  333. }
  334. }
  335. if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
  336. $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
  337. }
  338. }
  339. /**
  340. * Tries to load the specified configuration file into the App->config array.
  341. * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
  342. *
  343. * The config format is INI and the template for configuration files is the following:
  344. *
  345. * <?php return <<<INI
  346. *
  347. * [section]
  348. * key = value
  349. *
  350. * INI;
  351. * // Keep this line
  352. *
  353. * @param type $filepath
  354. * @param bool $overwrite Force value overwrite if the config key already exists
  355. * @throws Exception
  356. */
  357. public function loadConfigFile($filepath, $overwrite = false)
  358. {
  359. if (!file_exists($filepath)) {
  360. throw new Exception('Error parsing non-existent config file ' . $filepath);
  361. }
  362. $contents = include($filepath);
  363. $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
  364. if ($config === false) {
  365. throw new Exception('Error parsing config file ' . $filepath);
  366. }
  367. foreach ($config as $category => $values) {
  368. foreach ($values as $key => $value) {
  369. if ($overwrite) {
  370. $this->setConfigValue($category, $key, $value);
  371. } else {
  372. $this->setDefaultConfigValue($category, $key, $value);
  373. }
  374. }
  375. }
  376. }
  377. /**
  378. * Loads addons configuration files
  379. *
  380. * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
  381. * again to overwrite potential local addon configuration.
  382. */
  383. private function loadAddonConfig()
  384. {
  385. // Loads addons default config
  386. Core\Addon::callHooks('load_config');
  387. // Load the local addon config file to overwritten default addon config values
  388. if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
  389. $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
  390. }
  391. }
  392. /**
  393. * Loads the default timezone
  394. *
  395. * Include support for legacy $default_timezone
  396. *
  397. * @global string $default_timezone
  398. */
  399. private function loadDefaultTimezone()
  400. {
  401. if ($this->getConfigValue('system', 'default_timezone')) {
  402. $this->timezone = $this->getConfigValue('system', 'default_timezone');
  403. } else {
  404. global $default_timezone;
  405. $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
  406. }
  407. if ($this->timezone) {
  408. date_default_timezone_set($this->timezone);
  409. }
  410. }
  411. /**
  412. * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
  413. */
  414. private function determineUrlPath()
  415. {
  416. $this->urlpath = $this->getConfigValue('system', 'urlpath');
  417. /* SCRIPT_URL gives /path/to/friendica/module/parameter
  418. * QUERY_STRING gives pagename=module/parameter
  419. *
  420. * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
  421. */
  422. if (!empty($_SERVER['SCRIPT_URL'])) {
  423. // Module
  424. if (!empty($_SERVER['QUERY_STRING'])) {
  425. $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
  426. } else {
  427. // Root page
  428. $path = trim($_SERVER['SCRIPT_URL'], '/');
  429. }
  430. if ($path && $path != $this->urlpath) {
  431. $this->urlpath = $path;
  432. }
  433. }
  434. }
  435. public function loadDatabase()
  436. {
  437. if (DBA::connected()) {
  438. return;
  439. }
  440. $db_host = $this->getConfigValue('database', 'hostname');
  441. $db_user = $this->getConfigValue('database', 'username');
  442. $db_pass = $this->getConfigValue('database', 'password');
  443. $db_data = $this->getConfigValue('database', 'database');
  444. $charset = $this->getConfigValue('database', 'charset');
  445. // Use environment variables for mysql if they are set beforehand
  446. if (!empty(getenv('MYSQL_HOST'))
  447. && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
  448. && getenv('MYSQL_PASSWORD') !== false
  449. && !empty(getenv('MYSQL_DATABASE')))
  450. {
  451. $db_host = getenv('MYSQL_HOST');
  452. if (!empty(getenv('MYSQL_PORT'))) {
  453. $db_host .= ':' . getenv('MYSQL_PORT');
  454. }
  455. if (!empty(getenv('MYSQL_USERNAME'))) {
  456. $db_user = getenv('MYSQL_USERNAME');
  457. } else {
  458. $db_user = getenv('MYSQL_USER');
  459. }
  460. $db_pass = (string) getenv('MYSQL_PASSWORD');
  461. $db_data = getenv('MYSQL_DATABASE');
  462. }
  463. $stamp1 = microtime(true);
  464. DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
  465. unset($db_host, $db_user, $db_pass, $db_data, $charset);
  466. $this->save_timestamp($stamp1, 'network');
  467. }
  468. /**
  469. * @brief Returns the base filesystem path of the App
  470. *
  471. * It first checks for the internal variable, then for DOCUMENT_ROOT and
  472. * finally for PWD
  473. *
  474. * @return string
  475. */
  476. public function get_basepath()
  477. {
  478. $basepath = $this->basepath;
  479. if (!$basepath) {
  480. $basepath = Config::get('system', 'basepath');
  481. }
  482. if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
  483. $basepath = $_SERVER['DOCUMENT_ROOT'];
  484. }
  485. if (!$basepath && x($_SERVER, 'PWD')) {
  486. $basepath = $_SERVER['PWD'];
  487. }
  488. return self::realpath($basepath);
  489. }
  490. /**
  491. * @brief Returns a normalized file path
  492. *
  493. * This is a wrapper for the "realpath" function.
  494. * That function cannot detect the real path when some folders aren't readable.
  495. * Since this could happen with some hosters we need to handle this.
  496. *
  497. * @param string $path The path that is about to be normalized
  498. * @return string normalized path - when possible
  499. */
  500. public static function realpath($path)
  501. {
  502. $normalized = realpath($path);
  503. if (!is_bool($normalized)) {
  504. return $normalized;
  505. } else {
  506. return $path;
  507. }
  508. }
  509. public function get_scheme()
  510. {
  511. return $this->scheme;
  512. }
  513. /**
  514. * @brief Retrieves the Friendica instance base URL
  515. *
  516. * This function assembles the base URL from multiple parts:
  517. * - Protocol is determined either by the request or a combination of
  518. * system.ssl_policy and the $ssl parameter.
  519. * - Host name is determined either by system.hostname or inferred from request
  520. * - Path is inferred from SCRIPT_NAME
  521. *
  522. * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
  523. *
  524. * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
  525. * @return string Friendica server base URL
  526. */
  527. public function get_baseurl($ssl = false)
  528. {
  529. $scheme = $this->scheme;
  530. if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
  531. $scheme = 'https';
  532. }
  533. // Basically, we have $ssl = true on any links which can only be seen by a logged in user
  534. // (and also the login link). Anything seen by an outsider will have it turned off.
  535. if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
  536. if ($ssl) {
  537. $scheme = 'https';
  538. } else {
  539. $scheme = 'http';
  540. }
  541. }
  542. if (Config::get('config', 'hostname') != '') {
  543. $this->hostname = Config::get('config', 'hostname');
  544. }
  545. return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
  546. }
  547. /**
  548. * @brief Initializes the baseurl components
  549. *
  550. * Clears the baseurl cache to prevent inconsistencies
  551. *
  552. * @param string $url
  553. */
  554. public function set_baseurl($url)
  555. {
  556. $parsed = @parse_url($url);
  557. $hostname = '';
  558. if (x($parsed)) {
  559. if (!empty($parsed['scheme'])) {
  560. $this->scheme = $parsed['scheme'];
  561. }
  562. if (!empty($parsed['host'])) {
  563. $hostname = $parsed['host'];
  564. }
  565. if (x($parsed, 'port')) {
  566. $hostname .= ':' . $parsed['port'];
  567. }
  568. if (x($parsed, 'path')) {
  569. $this->urlpath = trim($parsed['path'], '\\/');
  570. }
  571. if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
  572. include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
  573. }
  574. if (Config::get('config', 'hostname') != '') {
  575. $this->hostname = Config::get('config', 'hostname');
  576. }
  577. if (!isset($this->hostname) || ($this->hostname == '')) {
  578. $this->hostname = $hostname;
  579. }
  580. }
  581. }
  582. public function get_hostname()
  583. {
  584. if (Config::get('config', 'hostname') != '') {
  585. $this->hostname = Config::get('config', 'hostname');
  586. }
  587. return $this->hostname;
  588. }
  589. public function get_path()
  590. {
  591. return $this->urlpath;
  592. }
  593. public function set_pager_total($n)
  594. {
  595. $this->pager['total'] = intval($n);
  596. }
  597. public function set_pager_itemspage($n)
  598. {
  599. $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
  600. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  601. }
  602. public function set_pager_page($n)
  603. {
  604. $this->pager['page'] = $n;
  605. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  606. }
  607. /**
  608. * Initializes App->page['htmlhead'].
  609. *
  610. * Includes:
  611. * - Page title
  612. * - Favicons
  613. * - Registered stylesheets (through App->registerStylesheet())
  614. * - Infinite scroll data
  615. * - head.tpl template
  616. */
  617. public function initHead()
  618. {
  619. $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
  620. // If the update is 'deactivated' set it to the highest integer number (~24 days)
  621. if ($interval < 0) {
  622. $interval = 2147483647;
  623. }
  624. if ($interval < 10000) {
  625. $interval = 40000;
  626. }
  627. // compose the page title from the sitename and the
  628. // current module called
  629. if (!$this->module == '') {
  630. $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
  631. } else {
  632. $this->page['title'] = $this->config['sitename'];
  633. }
  634. if (!empty($this->theme['stylesheet'])) {
  635. $stylesheet = $this->theme['stylesheet'];
  636. } else {
  637. $stylesheet = $this->getCurrentThemeStylesheetPath();
  638. }
  639. $this->registerStylesheet($stylesheet);
  640. $shortcut_icon = Config::get('system', 'shortcut_icon');
  641. if ($shortcut_icon == '') {
  642. $shortcut_icon = 'images/friendica-32.png';
  643. }
  644. $touch_icon = Config::get('system', 'touch_icon');
  645. if ($touch_icon == '') {
  646. $touch_icon = 'images/friendica-128.png';
  647. }
  648. // get data wich is needed for infinite scroll on the network page
  649. $infinite_scroll = infinite_scroll_data($this->module);
  650. Core\Addon::callHooks('head', $this->page['htmlhead']);
  651. $tpl = get_markup_template('head.tpl');
  652. /* put the head template at the beginning of page['htmlhead']
  653. * since the code added by the modules frequently depends on it
  654. * being first
  655. */
  656. $this->page['htmlhead'] = replace_macros($tpl, [
  657. '$baseurl' => $this->get_baseurl(),
  658. '$local_user' => local_user(),
  659. '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
  660. '$delitem' => L10n::t('Delete this item?'),
  661. '$showmore' => L10n::t('show more'),
  662. '$showfewer' => L10n::t('show fewer'),
  663. '$update_interval' => $interval,
  664. '$shortcut_icon' => $shortcut_icon,
  665. '$touch_icon' => $touch_icon,
  666. '$infinite_scroll' => $infinite_scroll,
  667. '$block_public' => intval(Config::get('system', 'block_public')),
  668. '$stylesheets' => $this->stylesheets,
  669. ]) . $this->page['htmlhead'];
  670. }
  671. /**
  672. * Initializes App->page['footer'].
  673. *
  674. * Includes:
  675. * - Javascript homebase
  676. * - Mobile toggle link
  677. * - Registered footer scripts (through App->registerFooterScript())
  678. * - footer.tpl template
  679. */
  680. public function initFooter()
  681. {
  682. // If you're just visiting, let javascript take you home
  683. if (!empty($_SESSION['visitor_home'])) {
  684. $homebase = $_SESSION['visitor_home'];
  685. } elseif (local_user()) {
  686. $homebase = 'profile/' . $this->user['nickname'];
  687. }
  688. if (isset($homebase)) {
  689. $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
  690. }
  691. /*
  692. * Add a "toggle mobile" link if we're using a mobile device
  693. */
  694. if ($this->is_mobile || $this->is_tablet) {
  695. if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  696. $link = 'toggle_mobile?address=' . curPageURL();
  697. } else {
  698. $link = 'toggle_mobile?off=1&address=' . curPageURL();
  699. }
  700. $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
  701. '$toggle_link' => $link,
  702. '$toggle_text' => Core\L10n::t('toggle mobile')
  703. ]);
  704. }
  705. Core\Addon::callHooks('footer', $this->page['footer']);
  706. $tpl = get_markup_template('footer.tpl');
  707. $this->page['footer'] = replace_macros($tpl, [
  708. '$baseurl' => $this->get_baseurl(),
  709. '$footerScripts' => $this->footerScripts,
  710. ]) . $this->page['footer'];
  711. }
  712. public function set_curl_code($code)
  713. {
  714. $this->curl_code = $code;
  715. }
  716. public function get_curl_code()
  717. {
  718. return $this->curl_code;
  719. }
  720. public function set_curl_content_type($content_type)
  721. {
  722. $this->curl_content_type = $content_type;
  723. }
  724. public function get_curl_content_type()
  725. {
  726. return $this->curl_content_type;
  727. }
  728. public function set_curl_headers($headers)
  729. {
  730. $this->curl_headers = $headers;
  731. }
  732. public function get_curl_headers()
  733. {
  734. return $this->curl_headers;
  735. }
  736. /**
  737. * @brief Removes the base url from an url. This avoids some mixed content problems.
  738. *
  739. * @param string $orig_url
  740. *
  741. * @return string The cleaned url
  742. */
  743. public function remove_baseurl($orig_url)
  744. {
  745. // Remove the hostname from the url if it is an internal link
  746. $nurl = normalise_link($orig_url);
  747. $base = normalise_link($this->get_baseurl());
  748. $url = str_replace($base . '/', '', $nurl);
  749. // if it is an external link return the orignal value
  750. if ($url == normalise_link($orig_url)) {
  751. return $orig_url;
  752. } else {
  753. return $url;
  754. }
  755. }
  756. /**
  757. * @brief Register template engine class
  758. *
  759. * @param string $class
  760. */
  761. private function register_template_engine($class)
  762. {
  763. $v = get_class_vars($class);
  764. if (x($v, 'name')) {
  765. $name = $v['name'];
  766. $this->template_engines[$name] = $class;
  767. } else {
  768. echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
  769. die();
  770. }
  771. }
  772. /**
  773. * @brief Return template engine instance.
  774. *
  775. * If $name is not defined, return engine defined by theme,
  776. * or default
  777. *
  778. * @return object Template Engine instance
  779. */
  780. public function template_engine()
  781. {
  782. $template_engine = 'smarty3';
  783. if (x($this->theme, 'template_engine')) {
  784. $template_engine = $this->theme['template_engine'];
  785. }
  786. if (isset($this->template_engines[$template_engine])) {
  787. if (isset($this->template_engine_instance[$template_engine])) {
  788. return $this->template_engine_instance[$template_engine];
  789. } else {
  790. $class = $this->template_engines[$template_engine];
  791. $obj = new $class;
  792. $this->template_engine_instance[$template_engine] = $obj;
  793. return $obj;
  794. }
  795. }
  796. echo "template engine <tt>$template_engine</tt> is not registered!\n";
  797. killme();
  798. }
  799. /**
  800. * @brief Returns the active template engine.
  801. *
  802. * @return string
  803. */
  804. public function get_template_engine()
  805. {
  806. return $this->theme['template_engine'];
  807. }
  808. public function set_template_engine($engine = 'smarty3')
  809. {
  810. $this->theme['template_engine'] = $engine;
  811. }
  812. public function get_template_ldelim($engine = 'smarty3')
  813. {
  814. return $this->ldelim[$engine];
  815. }
  816. public function get_template_rdelim($engine = 'smarty3')
  817. {
  818. return $this->rdelim[$engine];
  819. }
  820. public function save_timestamp($stamp, $value)
  821. {
  822. if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
  823. return;
  824. }
  825. $duration = (float) (microtime(true) - $stamp);
  826. if (!isset($this->performance[$value])) {
  827. // Prevent ugly E_NOTICE
  828. $this->performance[$value] = 0;
  829. }
  830. $this->performance[$value] += (float) $duration;
  831. $this->performance['marktime'] += (float) $duration;
  832. $callstack = System::callstack();
  833. if (!isset($this->callstack[$value][$callstack])) {
  834. // Prevent ugly E_NOTICE
  835. $this->callstack[$value][$callstack] = 0;
  836. }
  837. $this->callstack[$value][$callstack] += (float) $duration;
  838. }
  839. public function get_useragent()
  840. {
  841. return
  842. FRIENDICA_PLATFORM . " '" .
  843. FRIENDICA_CODENAME . "' " .
  844. FRIENDICA_VERSION . '-' .
  845. DB_UPDATE_VERSION . '; ' .
  846. $this->get_baseurl();
  847. }
  848. public function is_friendica_app()
  849. {
  850. return $this->is_friendica_app;
  851. }
  852. /**
  853. * @brief Checks if the site is called via a backend process
  854. *
  855. * This isn't a perfect solution. But we need this check very early.
  856. * So we cannot wait until the modules are loaded.
  857. *
  858. * @return bool Is it a known backend?
  859. */
  860. public function is_backend()
  861. {
  862. static $backends = [
  863. '_well_known',
  864. 'api',
  865. 'dfrn_notify',
  866. 'fetch',
  867. 'hcard',
  868. 'hostxrd',
  869. 'nodeinfo',
  870. 'noscrape',
  871. 'p',
  872. 'poco',
  873. 'post',
  874. 'proxy',
  875. 'pubsub',
  876. 'pubsubhubbub',
  877. 'receive',
  878. 'rsd_xml',
  879. 'salmon',
  880. 'statistics_json',
  881. 'xrd',
  882. ];
  883. // Check if current module is in backend or backend flag is set
  884. return (in_array($this->module, $backends) || $this->backend);
  885. }
  886. /**
  887. * @brief Checks if the maximum number of database processes is reached
  888. *
  889. * @return bool Is the limit reached?
  890. */
  891. public function isMaxProcessesReached()
  892. {
  893. // Deactivated, needs more investigating if this check really makes sense
  894. return false;
  895. /*
  896. * Commented out to suppress static analyzer issues
  897. *
  898. if ($this->is_backend()) {
  899. $process = 'backend';
  900. $max_processes = Config::get('system', 'max_processes_backend');
  901. if (intval($max_processes) == 0) {
  902. $max_processes = 5;
  903. }
  904. } else {
  905. $process = 'frontend';
  906. $max_processes = Config::get('system', 'max_processes_frontend');
  907. if (intval($max_processes) == 0) {
  908. $max_processes = 20;
  909. }
  910. }
  911. $processlist = DBA::processlist();
  912. if ($processlist['list'] != '') {
  913. logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
  914. if ($processlist['amount'] > $max_processes) {
  915. logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
  916. return true;
  917. }
  918. }
  919. return false;
  920. */
  921. }
  922. /**
  923. * @brief Checks if the minimal memory is reached
  924. *
  925. * @return bool Is the memory limit reached?
  926. */
  927. public function min_memory_reached()
  928. {
  929. $min_memory = Config::get('system', 'min_memory', 0);
  930. if ($min_memory == 0) {
  931. return false;
  932. }
  933. if (!is_readable('/proc/meminfo')) {
  934. return false;
  935. }
  936. $memdata = explode("\n", file_get_contents('/proc/meminfo'));
  937. $meminfo = [];
  938. foreach ($memdata as $line) {
  939. $data = explode(':', $line);
  940. if (count($data) != 2) {
  941. continue;
  942. }
  943. list($key, $val) = $data;
  944. $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
  945. $meminfo[$key] = (int) ($meminfo[$key] / 1024);
  946. }
  947. if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
  948. return false;
  949. }
  950. $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
  951. $reached = ($free < $min_memory);
  952. if ($reached) {
  953. logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
  954. }
  955. return $reached;
  956. }
  957. /**
  958. * @brief Checks if the maximum load is reached
  959. *
  960. * @return bool Is the load reached?
  961. */
  962. public function isMaxLoadReached()
  963. {
  964. if ($this->is_backend()) {
  965. $process = 'backend';
  966. $maxsysload = intval(Config::get('system', 'maxloadavg'));
  967. if ($maxsysload < 1) {
  968. $maxsysload = 50;
  969. }
  970. } else {
  971. $process = 'frontend';
  972. $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
  973. if ($maxsysload < 1) {
  974. $maxsysload = 50;
  975. }
  976. }
  977. $load = current_load();
  978. if ($load) {
  979. if (intval($load) > $maxsysload) {
  980. logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
  981. return true;
  982. }
  983. }
  984. return false;
  985. }
  986. /**
  987. * Executes a child process with 'proc_open'
  988. *
  989. * @param string $command The command to execute
  990. * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
  991. */
  992. public function proc_run($command, $args)
  993. {
  994. if (!function_exists('proc_open')) {
  995. return;
  996. }
  997. $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
  998. foreach ($args as $key => $value) {
  999. if (!is_null($value) && is_bool($value) && !$value) {
  1000. continue;
  1001. }
  1002. $cmdline .= ' --' . $key;
  1003. if (!is_null($value) && !is_bool($value)) {
  1004. $cmdline .= ' ' . $value;
  1005. }
  1006. }
  1007. if ($this->min_memory_reached()) {
  1008. return;
  1009. }
  1010. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  1011. $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
  1012. } else {
  1013. $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
  1014. }
  1015. if (!is_resource($resource)) {
  1016. logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
  1017. return;
  1018. }
  1019. proc_close($resource);
  1020. }
  1021. /**
  1022. * @brief Returns the system user that is executing the script
  1023. *
  1024. * This mostly returns something like "www-data".
  1025. *
  1026. * @return string system username
  1027. */
  1028. private static function systemuser()
  1029. {
  1030. if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
  1031. return '';
  1032. }
  1033. $processUser = posix_getpwuid(posix_geteuid());
  1034. return $processUser['name'];
  1035. }
  1036. /**
  1037. * @brief Checks if a given directory is usable for the system
  1038. *
  1039. * @return boolean the directory is usable
  1040. */
  1041. public static function directory_usable($directory, $check_writable = true)
  1042. {
  1043. if ($directory == '') {
  1044. logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
  1045. return false;
  1046. }
  1047. if (!file_exists($directory)) {
  1048. logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
  1049. return false;
  1050. }
  1051. if (is_file($directory)) {
  1052. logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
  1053. return false;
  1054. }
  1055. if (!is_dir($directory)) {
  1056. logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
  1057. return false;
  1058. }
  1059. if ($check_writable && !is_writable($directory)) {
  1060. logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
  1061. return false;
  1062. }
  1063. return true;
  1064. }
  1065. /**
  1066. * @param string $cat Config category
  1067. * @param string $k Config key
  1068. * @param mixed $default Default value if it isn't set
  1069. */
  1070. public function getConfigValue($cat, $k, $default = null)
  1071. {
  1072. $return = $default;
  1073. if ($cat === 'config') {
  1074. if (isset($this->config[$k])) {
  1075. $return = $this->config[$k];
  1076. }
  1077. } else {
  1078. if (isset($this->config[$cat][$k])) {
  1079. $return = $this->config[$cat][$k];
  1080. }
  1081. }
  1082. return $return;
  1083. }
  1084. /**
  1085. * Sets a default value in the config cache. Ignores already existing keys.
  1086. *
  1087. * @param string $cat Config category
  1088. * @param string $k Config key
  1089. * @param mixed $v Default value to set
  1090. */
  1091. private function setDefaultConfigValue($cat, $k, $v)
  1092. {
  1093. if (!isset($this->config[$cat][$k])) {
  1094. $this->setConfigValue($cat, $k, $v);
  1095. }
  1096. }
  1097. /**
  1098. * Sets a value in the config cache. Accepts raw output from the config table
  1099. *
  1100. * @param string $cat Config category
  1101. * @param string $k Config key
  1102. * @param mixed $v Value to set
  1103. */
  1104. public function setConfigValue($cat, $k, $v)
  1105. {
  1106. // Only arrays are serialized in database, so we have to unserialize sparingly
  1107. $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
  1108. if ($cat === 'config') {
  1109. $this->config[$k] = $value;
  1110. } else {
  1111. if (!isset($this->config[$cat])) {
  1112. $this->config[$cat] = [];
  1113. }
  1114. $this->config[$cat][$k] = $value;
  1115. }
  1116. }
  1117. /**
  1118. * Deletes a value from the config cache
  1119. *
  1120. * @param string $cat Config category
  1121. * @param string $k Config key
  1122. */
  1123. public function deleteConfigValue($cat, $k)
  1124. {
  1125. if ($cat === 'config') {
  1126. if (isset($this->config[$k])) {
  1127. unset($this->config[$k]);
  1128. }
  1129. } else {
  1130. if (isset($this->config[$cat][$k])) {
  1131. unset($this->config[$cat][$k]);
  1132. }
  1133. }
  1134. }
  1135. /**
  1136. * Retrieves a value from the user config cache
  1137. *
  1138. * @param int $uid User Id
  1139. * @param string $cat Config category
  1140. * @param string $k Config key
  1141. * @param mixed $default Default value if key isn't set
  1142. */
  1143. public function getPConfigValue($uid, $cat, $k, $default = null)
  1144. {
  1145. $return = $default;
  1146. if (isset($this->config[$uid][$cat][$k])) {
  1147. $return = $this->config[$uid][$cat][$k];
  1148. }
  1149. return $return;
  1150. }
  1151. /**
  1152. * Sets a value in the user config cache
  1153. *
  1154. * Accepts raw output from the pconfig table
  1155. *
  1156. * @param int $uid User Id
  1157. * @param string $cat Config category
  1158. * @param string $k Config key
  1159. * @param mixed $v Value to set
  1160. */
  1161. public function setPConfigValue($uid, $cat, $k, $v)
  1162. {
  1163. // Only arrays are serialized in database, so we have to unserialize sparingly
  1164. $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
  1165. if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
  1166. $this->config[$uid] = [];
  1167. }
  1168. if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
  1169. $this->config[$uid][$cat] = [];
  1170. }
  1171. $this->config[$uid][$cat][$k] = $value;
  1172. }
  1173. /**
  1174. * Deletes a value from the user config cache
  1175. *
  1176. * @param int $uid User Id
  1177. * @param string $cat Config category
  1178. * @param string $k Config key
  1179. */
  1180. public function deletePConfigValue($uid, $cat, $k)
  1181. {
  1182. if (isset($this->config[$uid][$cat][$k])) {
  1183. unset($this->config[$uid][$cat][$k]);
  1184. }
  1185. }
  1186. /**
  1187. * Generates the site's default sender email address
  1188. *
  1189. * @return string
  1190. */
  1191. public function getSenderEmailAddress()
  1192. {
  1193. $sender_email = Config::get('config', 'sender_email');
  1194. if (empty($sender_email)) {
  1195. $hostname = $this->get_hostname();
  1196. if (strpos($hostname, ':')) {
  1197. $hostname = substr($hostname, 0, strpos($hostname, ':'));
  1198. }
  1199. $sender_email = 'noreply@' . $hostname;
  1200. }
  1201. return $sender_email;
  1202. }
  1203. /**
  1204. * Returns the current theme name.
  1205. *
  1206. * @return string
  1207. */
  1208. public function getCurrentTheme()
  1209. {
  1210. if (App\Mode::isInstall()) {
  1211. return '';
  1212. }
  1213. //// @TODO Compute the current theme only once (this behavior has
  1214. /// already been implemented, but it didn't work well -
  1215. /// https://github.com/friendica/friendica/issues/5092)
  1216. $this->computeCurrentTheme();
  1217. return $this->current_theme;
  1218. }
  1219. /**
  1220. * Computes the current theme name based on the node settings, the user settings and the device type
  1221. *
  1222. * @throws Exception
  1223. */
  1224. private function computeCurrentTheme()
  1225. {
  1226. $system_theme = Config::get('system', 'theme');
  1227. if (!$system_theme) {
  1228. throw new Exception(L10n::t('No system theme config value set.'));
  1229. }
  1230. // Sane default
  1231. $this->current_theme = $system_theme;
  1232. $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
  1233. $page_theme = null;
  1234. // Find the theme that belongs to the user whose stuff we are looking at
  1235. if ($this->profile_uid && ($this->profile_uid != local_user())) {
  1236. // Allow folks to override user themes and always use their own on their own site.
  1237. // This works only if the user is on the same server
  1238. $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
  1239. if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
  1240. $page_theme = $user['theme'];
  1241. }
  1242. }
  1243. $user_theme = Core\Session::get('theme', $system_theme);
  1244. // Specific mobile theme override
  1245. if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
  1246. $system_mobile_theme = Config::get('system', 'mobile-theme');
  1247. $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
  1248. // --- means same mobile theme as desktop
  1249. if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
  1250. $user_theme = $user_mobile_theme;
  1251. }
  1252. }
  1253. if ($page_theme) {
  1254. $theme_name = $page_theme;
  1255. } else {
  1256. $theme_name = $user_theme;
  1257. }
  1258. if ($theme_name
  1259. && in_array($theme_name, $allowed_themes)
  1260. && (file_exists('view/theme/' . $theme_name . '/style.css')
  1261. || file_exists('view/theme/' . $theme_name . '/style.php'))
  1262. ) {
  1263. $this->current_theme = $theme_name;
  1264. }
  1265. }
  1266. /**
  1267. * @brief Return full URL to theme which is currently in effect.
  1268. *
  1269. * Provide a sane default if nothing is chosen or the specified theme does not exist.
  1270. *
  1271. * @return string
  1272. */
  1273. public function getCurrentThemeStylesheetPath()
  1274. {
  1275. return Core\Theme::getStylesheetPath($this->getCurrentTheme());
  1276. }
  1277. }