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.

1917 lines
55KB

  1. <?php
  2. /**
  3. * @file src/App.php
  4. */
  5. namespace Friendica;
  6. use Detection\MobileDetect;
  7. use DOMDocument;
  8. use DOMXPath;
  9. use Exception;
  10. use Friendica\Database\DBA;
  11. use Friendica\Network\HTTPException\InternalServerErrorException;
  12. /**
  13. *
  14. * class: App
  15. *
  16. * @brief Our main application structure for the life of this page.
  17. *
  18. * Primarily deals with the URL that got us here
  19. * and tries to make some sense of it, and
  20. * stores our page contents and config storage
  21. * and anything else that might need to be passed around
  22. * before we spit the page out.
  23. *
  24. */
  25. class App
  26. {
  27. public $module_loaded = false;
  28. public $module_class = null;
  29. public $query_string = '';
  30. public $config = [];
  31. public $page = [];
  32. public $profile;
  33. public $profile_uid;
  34. public $user;
  35. public $cid;
  36. public $contact;
  37. public $contacts;
  38. public $page_contact;
  39. public $content;
  40. public $data = [];
  41. public $error = false;
  42. public $cmd = '';
  43. public $argv;
  44. public $argc;
  45. public $module;
  46. public $timezone;
  47. public $interactive = true;
  48. public $identities;
  49. public $is_mobile = false;
  50. public $is_tablet = false;
  51. public $performance = [];
  52. public $callstack = [];
  53. public $theme_info = [];
  54. public $category;
  55. // Allow themes to control internal parameters
  56. // by changing App values in theme.php
  57. public $sourcename = '';
  58. public $videowidth = 425;
  59. public $videoheight = 350;
  60. public $force_max_items = 0;
  61. public $theme_events_in_profile = true;
  62. public $stylesheets = [];
  63. public $footerScripts = [];
  64. /**
  65. * @var App\Mode The Mode of the Application
  66. */
  67. private $mode;
  68. /**
  69. * @var string The App base path
  70. */
  71. private $basePath;
  72. /**
  73. * @var string The App URL path
  74. */
  75. private $urlPath;
  76. /**
  77. * @var bool true, if the call is from the Friendica APP, otherwise false
  78. */
  79. private $isFriendicaApp;
  80. /**
  81. * @var bool true, if the call is from an backend node (f.e. worker)
  82. */
  83. private $isBackend;
  84. /**
  85. * @var string The name of the current theme
  86. */
  87. private $currentTheme;
  88. /**
  89. * @var bool check if request was an AJAX (xmlhttprequest) request
  90. */
  91. private $isAjax;
  92. /**
  93. * @var MobileDetect
  94. */
  95. public $mobileDetect;
  96. /**
  97. * Register a stylesheet file path to be included in the <head> tag of every page.
  98. * Inclusion is done in App->initHead().
  99. * The path can be absolute or relative to the Friendica installation base folder.
  100. *
  101. * @see initHead()
  102. *
  103. * @param string $path
  104. */
  105. public function registerStylesheet($path)
  106. {
  107. $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
  108. $this->stylesheets[] = trim($url, '/');
  109. }
  110. /**
  111. * Register a javascript file path to be included in the <footer> tag of every page.
  112. * Inclusion is done in App->initFooter().
  113. * The path can be absolute or relative to the Friendica installation base folder.
  114. *
  115. * @see initFooter()
  116. *
  117. * @param string $path
  118. */
  119. public function registerFooterScript($path)
  120. {
  121. $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
  122. $this->footerScripts[] = trim($url, '/');
  123. }
  124. public $process_id;
  125. public $queue;
  126. private $scheme;
  127. private $hostname;
  128. /**
  129. * @brief App constructor.
  130. *
  131. * @param string $basePath Path to the app base folder
  132. * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
  133. *
  134. * @throws Exception if the Basepath is not usable
  135. */
  136. public function __construct($basePath, $isBackend = true)
  137. {
  138. if (!static::isDirectoryUsable($basePath, false)) {
  139. throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
  140. }
  141. BaseObject::setApp($this);
  142. $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
  143. $this->checkBackend($isBackend);
  144. $this->checkFriendicaApp();
  145. $this->performance['start'] = microtime(true);
  146. $this->performance['database'] = 0;
  147. $this->performance['database_write'] = 0;
  148. $this->performance['cache'] = 0;
  149. $this->performance['cache_write'] = 0;
  150. $this->performance['network'] = 0;
  151. $this->performance['file'] = 0;
  152. $this->performance['rendering'] = 0;
  153. $this->performance['parser'] = 0;
  154. $this->performance['marktime'] = 0;
  155. $this->performance['markstart'] = microtime(true);
  156. $this->callstack['database'] = [];
  157. $this->callstack['database_write'] = [];
  158. $this->callstack['cache'] = [];
  159. $this->callstack['cache_write'] = [];
  160. $this->callstack['network'] = [];
  161. $this->callstack['file'] = [];
  162. $this->callstack['rendering'] = [];
  163. $this->callstack['parser'] = [];
  164. $this->mode = new App\Mode($basePath);
  165. $this->reload();
  166. set_time_limit(0);
  167. // This has to be quite large to deal with embedded private photos
  168. ini_set('pcre.backtrack_limit', 500000);
  169. $this->scheme = 'http';
  170. if (!empty($_SERVER['HTTPS']) ||
  171. !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
  172. !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
  173. !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
  174. !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
  175. !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
  176. ) {
  177. $this->scheme = 'https';
  178. }
  179. if (!empty($_SERVER['SERVER_NAME'])) {
  180. $this->hostname = $_SERVER['SERVER_NAME'];
  181. if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
  182. $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
  183. }
  184. }
  185. set_include_path(
  186. get_include_path() . PATH_SEPARATOR
  187. . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
  188. . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
  189. . $this->getBasePath());
  190. if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
  191. $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
  192. } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
  193. $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
  194. }
  195. // removing trailing / - maybe a nginx problem
  196. $this->query_string = ltrim($this->query_string, '/');
  197. if (!empty($_GET['pagename'])) {
  198. $this->cmd = trim($_GET['pagename'], '/\\');
  199. } elseif (!empty($_GET['q'])) {
  200. $this->cmd = trim($_GET['q'], '/\\');
  201. }
  202. // fix query_string
  203. $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
  204. // unix style "homedir"
  205. if (substr($this->cmd, 0, 1) === '~') {
  206. $this->cmd = 'profile/' . substr($this->cmd, 1);
  207. }
  208. // Diaspora style profile url
  209. if (substr($this->cmd, 0, 2) === 'u/') {
  210. $this->cmd = 'profile/' . substr($this->cmd, 2);
  211. }
  212. /*
  213. * Break the URL path into C style argc/argv style arguments for our
  214. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  215. * will be 3 (integer) and $this->argv will contain:
  216. * [0] => 'module'
  217. * [1] => 'arg1'
  218. * [2] => 'arg2'
  219. *
  220. *
  221. * There will always be one argument. If provided a naked domain
  222. * URL, $this->argv[0] is set to "home".
  223. */
  224. $this->argv = explode('/', $this->cmd);
  225. $this->argc = count($this->argv);
  226. if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
  227. $this->module = str_replace('.', '_', $this->argv[0]);
  228. $this->module = str_replace('-', '_', $this->module);
  229. } else {
  230. $this->argc = 1;
  231. $this->argv = ['home'];
  232. $this->module = 'home';
  233. }
  234. // Detect mobile devices
  235. $mobile_detect = new MobileDetect();
  236. $this->mobileDetect = $mobile_detect;
  237. $this->is_mobile = $mobile_detect->isMobile();
  238. $this->is_tablet = $mobile_detect->isTablet();
  239. $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
  240. // Register template engines
  241. Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
  242. }
  243. /**
  244. * Returns the Mode of the Application
  245. *
  246. * @return App\Mode The Application Mode
  247. *
  248. * @throws InternalServerErrorException when the mode isn't created
  249. */
  250. public function getMode()
  251. {
  252. if (empty($this->mode)) {
  253. throw new InternalServerErrorException('Mode of the Application is not defined');
  254. }
  255. return $this->mode;
  256. }
  257. /**
  258. * Reloads the whole app instance
  259. */
  260. public function reload()
  261. {
  262. // The order of the following calls is important to ensure proper initialization
  263. $this->loadConfigFiles();
  264. $this->loadDatabase();
  265. $this->getMode()->determine($this->getBasePath());
  266. $this->determineURLPath();
  267. Core\Config::load();
  268. if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
  269. Core\Hook::loadHooks();
  270. $this->loadAddonConfig();
  271. }
  272. $this->loadDefaultTimezone();
  273. Core\L10n::init();
  274. $this->process_id = Core\System::processID('log');
  275. }
  276. /**
  277. * Load the configuration files
  278. *
  279. * First loads the default value for all the configuration keys, then the legacy configuration files, then the
  280. * expected local.config.php
  281. */
  282. private function loadConfigFiles()
  283. {
  284. $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php');
  285. $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php');
  286. // Legacy .htconfig.php support
  287. if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
  288. $a = $this;
  289. include $this->getBasePath() . '/.htpreconfig.php';
  290. }
  291. // Legacy .htconfig.php support
  292. if (file_exists($this->getBasePath() . '/.htconfig.php')) {
  293. $a = $this;
  294. include $this->getBasePath() . '/.htconfig.php';
  295. $this->setConfigValue('database', 'hostname', $db_host);
  296. $this->setConfigValue('database', 'username', $db_user);
  297. $this->setConfigValue('database', 'password', $db_pass);
  298. $this->setConfigValue('database', 'database', $db_data);
  299. if (isset($a->config['system']['db_charset'])) {
  300. $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
  301. }
  302. unset($db_host, $db_user, $db_pass, $db_data);
  303. if (isset($default_timezone)) {
  304. $this->setConfigValue('system', 'default_timezone', $default_timezone);
  305. unset($default_timezone);
  306. }
  307. if (isset($pidfile)) {
  308. $this->setConfigValue('system', 'pidfile', $pidfile);
  309. unset($pidfile);
  310. }
  311. if (isset($lang)) {
  312. $this->setConfigValue('system', 'language', $lang);
  313. unset($lang);
  314. }
  315. }
  316. if (file_exists($this->getBasePath() . '/config/local.config.php')) {
  317. $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true);
  318. } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) {
  319. $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true);
  320. }
  321. }
  322. /**
  323. * Tries to load the specified legacy configuration file into the App->config array.
  324. * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
  325. *
  326. * @deprecated since version 2018.12
  327. * @param string $filepath
  328. * @param bool $overwrite Force value overwrite if the config key already exists
  329. * @throws Exception
  330. */
  331. public function loadINIConfigFile($filepath, $overwrite = false)
  332. {
  333. if (!file_exists($filepath)) {
  334. throw new Exception('Error parsing non-existent INI config file ' . $filepath);
  335. }
  336. $contents = include($filepath);
  337. $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
  338. if ($config === false) {
  339. throw new Exception('Error parsing INI config file ' . $filepath);
  340. }
  341. $this->loadConfigArray($config, $overwrite);
  342. }
  343. /**
  344. * Tries to load the specified configuration file into the App->config array.
  345. * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
  346. *
  347. * The config format is PHP array and the template for configuration files is the following:
  348. *
  349. * <?php return [
  350. * 'section' => [
  351. * 'key' => 'value',
  352. * ],
  353. * ];
  354. *
  355. * @param string $filepath
  356. * @param bool $overwrite Force value overwrite if the config key already exists
  357. * @throws Exception
  358. */
  359. public function loadConfigFile($filepath, $overwrite = false)
  360. {
  361. if (!file_exists($filepath)) {
  362. throw new Exception('Error loading non-existent config file ' . $filepath);
  363. }
  364. $config = include($filepath);
  365. if (!is_array($config)) {
  366. throw new Exception('Error loading config file ' . $filepath);
  367. }
  368. $this->loadConfigArray($config, $overwrite);
  369. }
  370. /**
  371. * Loads addons configuration files
  372. *
  373. * First loads all activated addons default configuration through the load_config hook, then load the local.config.php
  374. * again to overwrite potential local addon configuration.
  375. */
  376. private function loadAddonConfig()
  377. {
  378. // Loads addons default config
  379. Core\Hook::callAll('load_config');
  380. // Load the local addon config file to overwritten default addon config values
  381. if (file_exists($this->getBasePath() . '/config/addon.config.php')) {
  382. $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true);
  383. } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) {
  384. $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true);
  385. }
  386. }
  387. /**
  388. * Tries to load the specified configuration array into the App->config array.
  389. * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
  390. *
  391. * @param array $config
  392. * @param bool $overwrite Force value overwrite if the config key already exists
  393. */
  394. private function loadConfigArray(array $config, $overwrite = false)
  395. {
  396. foreach ($config as $category => $values) {
  397. foreach ($values as $key => $value) {
  398. if ($overwrite) {
  399. $this->setConfigValue($category, $key, $value);
  400. } else {
  401. $this->setDefaultConfigValue($category, $key, $value);
  402. }
  403. }
  404. }
  405. }
  406. /**
  407. * Loads the default timezone
  408. *
  409. * Include support for legacy $default_timezone
  410. *
  411. * @global string $default_timezone
  412. */
  413. private function loadDefaultTimezone()
  414. {
  415. if ($this->getConfigValue('system', 'default_timezone')) {
  416. $this->timezone = $this->getConfigValue('system', 'default_timezone');
  417. } else {
  418. global $default_timezone;
  419. $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
  420. }
  421. if ($this->timezone) {
  422. date_default_timezone_set($this->timezone);
  423. }
  424. }
  425. /**
  426. * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
  427. */
  428. private function determineURLPath()
  429. {
  430. /* Relative script path to the web server root
  431. * Not all of those $_SERVER properties can be present, so we do by inverse priority order
  432. */
  433. $relative_script_path = '';
  434. $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
  435. $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
  436. $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
  437. $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
  438. $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
  439. $this->urlPath = $this->getConfigValue('system', 'urlpath');
  440. /* $relative_script_path gives /relative/path/to/friendica/module/parameter
  441. * QUERY_STRING gives pagename=module/parameter
  442. *
  443. * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
  444. */
  445. if (!empty($relative_script_path)) {
  446. // Module
  447. if (!empty($_SERVER['QUERY_STRING'])) {
  448. $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
  449. } else {
  450. // Root page
  451. $path = trim($relative_script_path, '/');
  452. }
  453. if ($path && $path != $this->urlPath) {
  454. $this->urlPath = $path;
  455. }
  456. }
  457. }
  458. public function loadDatabase()
  459. {
  460. if (DBA::connected()) {
  461. return;
  462. }
  463. $db_host = $this->getConfigValue('database', 'hostname');
  464. $db_user = $this->getConfigValue('database', 'username');
  465. $db_pass = $this->getConfigValue('database', 'password');
  466. $db_data = $this->getConfigValue('database', 'database');
  467. $charset = $this->getConfigValue('database', 'charset');
  468. // Use environment variables for mysql if they are set beforehand
  469. if (!empty(getenv('MYSQL_HOST'))
  470. && !empty(getenv('MYSQL_USERNAME') || !empty(getenv('MYSQL_USER')))
  471. && getenv('MYSQL_PASSWORD') !== false
  472. && !empty(getenv('MYSQL_DATABASE')))
  473. {
  474. $db_host = getenv('MYSQL_HOST');
  475. if (!empty(getenv('MYSQL_PORT'))) {
  476. $db_host .= ':' . getenv('MYSQL_PORT');
  477. }
  478. if (!empty(getenv('MYSQL_USERNAME'))) {
  479. $db_user = getenv('MYSQL_USERNAME');
  480. } else {
  481. $db_user = getenv('MYSQL_USER');
  482. }
  483. $db_pass = (string) getenv('MYSQL_PASSWORD');
  484. $db_data = getenv('MYSQL_DATABASE');
  485. }
  486. $stamp1 = microtime(true);
  487. if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
  488. // Loads DB_UPDATE_VERSION constant
  489. Database\DBStructure::definition(false);
  490. }
  491. unset($db_host, $db_user, $db_pass, $db_data, $charset);
  492. $this->saveTimestamp($stamp1, 'network');
  493. }
  494. /**
  495. * @brief Returns the base filesystem path of the App
  496. *
  497. * It first checks for the internal variable, then for DOCUMENT_ROOT and
  498. * finally for PWD
  499. *
  500. * @return string
  501. */
  502. public function getBasePath()
  503. {
  504. $basepath = $this->basePath;
  505. if (!$basepath) {
  506. $basepath = Core\Config::get('system', 'basepath');
  507. }
  508. if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
  509. $basepath = $_SERVER['DOCUMENT_ROOT'];
  510. }
  511. if (!$basepath && !empty($_SERVER['PWD'])) {
  512. $basepath = $_SERVER['PWD'];
  513. }
  514. return self::getRealPath($basepath);
  515. }
  516. /**
  517. * @brief Returns a normalized file path
  518. *
  519. * This is a wrapper for the "realpath" function.
  520. * That function cannot detect the real path when some folders aren't readable.
  521. * Since this could happen with some hosters we need to handle this.
  522. *
  523. * @param string $path The path that is about to be normalized
  524. * @return string normalized path - when possible
  525. */
  526. public static function getRealPath($path)
  527. {
  528. $normalized = realpath($path);
  529. if (!is_bool($normalized)) {
  530. return $normalized;
  531. } else {
  532. return $path;
  533. }
  534. }
  535. public function getScheme()
  536. {
  537. return $this->scheme;
  538. }
  539. /**
  540. * @brief Retrieves the Friendica instance base URL
  541. *
  542. * This function assembles the base URL from multiple parts:
  543. * - Protocol is determined either by the request or a combination of
  544. * system.ssl_policy and the $ssl parameter.
  545. * - Host name is determined either by system.hostname or inferred from request
  546. * - Path is inferred from SCRIPT_NAME
  547. *
  548. * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
  549. *
  550. * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
  551. * @return string Friendica server base URL
  552. */
  553. public function getBaseURL($ssl = false)
  554. {
  555. $scheme = $this->scheme;
  556. if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
  557. $scheme = 'https';
  558. }
  559. // Basically, we have $ssl = true on any links which can only be seen by a logged in user
  560. // (and also the login link). Anything seen by an outsider will have it turned off.
  561. if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
  562. if ($ssl) {
  563. $scheme = 'https';
  564. } else {
  565. $scheme = 'http';
  566. }
  567. }
  568. if (Core\Config::get('config', 'hostname') != '') {
  569. $this->hostname = Core\Config::get('config', 'hostname');
  570. }
  571. return $scheme . '://' . $this->hostname . !empty($this->getURLPath() ? '/' . $this->getURLPath() : '' );
  572. }
  573. /**
  574. * @brief Initializes the baseurl components
  575. *
  576. * Clears the baseurl cache to prevent inconsistencies
  577. *
  578. * @param string $url
  579. */
  580. public function setBaseURL($url)
  581. {
  582. $parsed = @parse_url($url);
  583. $hostname = '';
  584. if (!empty($parsed)) {
  585. if (!empty($parsed['scheme'])) {
  586. $this->scheme = $parsed['scheme'];
  587. }
  588. if (!empty($parsed['host'])) {
  589. $hostname = $parsed['host'];
  590. }
  591. if (!empty($parsed['port'])) {
  592. $hostname .= ':' . $parsed['port'];
  593. }
  594. if (!empty($parsed['path'])) {
  595. $this->urlPath = trim($parsed['path'], '\\/');
  596. }
  597. if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
  598. include $this->getBasePath() . '/.htpreconfig.php';
  599. }
  600. if (Core\Config::get('config', 'hostname') != '') {
  601. $this->hostname = Core\Config::get('config', 'hostname');
  602. }
  603. if (!isset($this->hostname) || ($this->hostname == '')) {
  604. $this->hostname = $hostname;
  605. }
  606. }
  607. }
  608. public function getHostName()
  609. {
  610. if (Core\Config::get('config', 'hostname') != '') {
  611. $this->hostname = Core\Config::get('config', 'hostname');
  612. }
  613. return $this->hostname;
  614. }
  615. public function getURLPath()
  616. {
  617. return $this->urlPath;
  618. }
  619. /**
  620. * Initializes App->page['htmlhead'].
  621. *
  622. * Includes:
  623. * - Page title
  624. * - Favicons
  625. * - Registered stylesheets (through App->registerStylesheet())
  626. * - Infinite scroll data
  627. * - head.tpl template
  628. */
  629. public function initHead()
  630. {
  631. $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
  632. // If the update is 'deactivated' set it to the highest integer number (~24 days)
  633. if ($interval < 0) {
  634. $interval = 2147483647;
  635. }
  636. if ($interval < 10000) {
  637. $interval = 40000;
  638. }
  639. // compose the page title from the sitename and the
  640. // current module called
  641. if (!$this->module == '') {
  642. $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
  643. } else {
  644. $this->page['title'] = $this->config['sitename'];
  645. }
  646. if (!empty(Core\Renderer::$theme['stylesheet'])) {
  647. $stylesheet = Core\Renderer::$theme['stylesheet'];
  648. } else {
  649. $stylesheet = $this->getCurrentThemeStylesheetPath();
  650. }
  651. $this->registerStylesheet($stylesheet);
  652. $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
  653. if ($shortcut_icon == '') {
  654. $shortcut_icon = 'images/friendica-32.png';
  655. }
  656. $touch_icon = Core\Config::get('system', 'touch_icon');
  657. if ($touch_icon == '') {
  658. $touch_icon = 'images/friendica-128.png';
  659. }
  660. Core\Hook::callAll('head', $this->page['htmlhead']);
  661. $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
  662. /* put the head template at the beginning of page['htmlhead']
  663. * since the code added by the modules frequently depends on it
  664. * being first
  665. */
  666. $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
  667. '$baseurl' => $this->getBaseURL(),
  668. '$local_user' => local_user(),
  669. '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
  670. '$delitem' => Core\L10n::t('Delete this item?'),
  671. '$showmore' => Core\L10n::t('show more'),
  672. '$showfewer' => Core\L10n::t('show fewer'),
  673. '$update_interval' => $interval,
  674. '$shortcut_icon' => $shortcut_icon,
  675. '$touch_icon' => $touch_icon,
  676. '$block_public' => intval(Core\Config::get('system', 'block_public')),
  677. '$stylesheets' => $this->stylesheets,
  678. ]) . $this->page['htmlhead'];
  679. }
  680. /**
  681. * Initializes App->page['footer'].
  682. *
  683. * Includes:
  684. * - Javascript homebase
  685. * - Mobile toggle link
  686. * - Registered footer scripts (through App->registerFooterScript())
  687. * - footer.tpl template
  688. */
  689. public function initFooter()
  690. {
  691. // If you're just visiting, let javascript take you home
  692. if (!empty($_SESSION['visitor_home'])) {
  693. $homebase = $_SESSION['visitor_home'];
  694. } elseif (local_user()) {
  695. $homebase = 'profile/' . $this->user['nickname'];
  696. }
  697. if (isset($homebase)) {
  698. $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
  699. }
  700. /*
  701. * Add a "toggle mobile" link if we're using a mobile device
  702. */
  703. if ($this->is_mobile || $this->is_tablet) {
  704. if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  705. $link = 'toggle_mobile?address=' . urlencode(curPageURL());
  706. } else {
  707. $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
  708. }
  709. $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
  710. '$toggle_link' => $link,
  711. '$toggle_text' => Core\L10n::t('toggle mobile')
  712. ]);
  713. }
  714. Core\Hook::callAll('footer', $this->page['footer']);
  715. $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
  716. $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
  717. '$baseurl' => $this->getBaseURL(),
  718. '$footerScripts' => $this->footerScripts,
  719. ]) . $this->page['footer'];
  720. }
  721. /**
  722. * @brief Removes the base url from an url. This avoids some mixed content problems.
  723. *
  724. * @param string $origURL
  725. *
  726. * @return string The cleaned url
  727. */
  728. public function removeBaseURL($origURL)
  729. {
  730. // Remove the hostname from the url if it is an internal link
  731. $nurl = Util\Strings::normaliseLink($origURL);
  732. $base = Util\Strings::normaliseLink($this->getBaseURL());
  733. $url = str_replace($base . '/', '', $nurl);
  734. // if it is an external link return the orignal value
  735. if ($url == Util\Strings::normaliseLink($origURL)) {
  736. return $origURL;
  737. } else {
  738. return $url;
  739. }
  740. }
  741. /**
  742. * Saves a timestamp for a value - f.e. a call
  743. * Necessary for profiling Friendica
  744. *
  745. * @param int $timestamp the Timestamp
  746. * @param string $value A value to profile
  747. */
  748. public function saveTimestamp($timestamp, $value)
  749. {
  750. if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
  751. return;
  752. }
  753. $duration = (float) (microtime(true) - $timestamp);
  754. if (!isset($this->performance[$value])) {
  755. // Prevent ugly E_NOTICE
  756. $this->performance[$value] = 0;
  757. }
  758. $this->performance[$value] += (float) $duration;
  759. $this->performance['marktime'] += (float) $duration;
  760. $callstack = Core\System::callstack();
  761. if (!isset($this->callstack[$value][$callstack])) {
  762. // Prevent ugly E_NOTICE
  763. $this->callstack[$value][$callstack] = 0;
  764. }
  765. $this->callstack[$value][$callstack] += (float) $duration;
  766. }
  767. /**
  768. * Returns the current UserAgent as a String
  769. *
  770. * @return string the UserAgent as a String
  771. */
  772. public function getUserAgent()
  773. {
  774. return
  775. FRIENDICA_PLATFORM . " '" .
  776. FRIENDICA_CODENAME . "' " .
  777. FRIENDICA_VERSION . '-' .
  778. DB_UPDATE_VERSION . '; ' .
  779. $this->getBaseURL();
  780. }
  781. /**
  782. * Checks, if the call is from the Friendica App
  783. *
  784. * Reason:
  785. * The friendica client has problems with the GUID in the notify. this is some workaround
  786. */
  787. private function checkFriendicaApp()
  788. {
  789. // Friendica-Client
  790. $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
  791. }
  792. /**
  793. * Is the call via the Friendica app? (not a "normale" call)
  794. *
  795. * @return bool true if it's from the Friendica app
  796. */
  797. public function isFriendicaApp()
  798. {
  799. return $this->isFriendicaApp;
  800. }
  801. /**
  802. * @brief Checks if the site is called via a backend process
  803. *
  804. * This isn't a perfect solution. But we need this check very early.
  805. * So we cannot wait until the modules are loaded.
  806. *
  807. * @param string $backend true, if the backend flag was set during App initialization
  808. *
  809. */
  810. private function checkBackend($backend) {
  811. static $backends = [
  812. '_well_known',
  813. 'api',
  814. 'dfrn_notify',
  815. 'fetch',
  816. 'hcard',
  817. 'hostxrd',
  818. 'nodeinfo',
  819. 'noscrape',
  820. 'p',
  821. 'poco',
  822. 'post',
  823. 'proxy',
  824. 'pubsub',
  825. 'pubsubhubbub',
  826. 'receive',
  827. 'rsd_xml',
  828. 'salmon',
  829. 'statistics_json',
  830. 'xrd',
  831. ];
  832. // Check if current module is in backend or backend flag is set
  833. $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
  834. }
  835. /**
  836. * Returns true, if the call is from a backend node (f.e. from a worker)
  837. *
  838. * @return bool Is it a known backend?
  839. */
  840. public function isBackend()
  841. {
  842. return $this->isBackend;
  843. }
  844. /**
  845. * @brief Checks if the maximum number of database processes is reached
  846. *
  847. * @return bool Is the limit reached?
  848. */
  849. public function isMaxProcessesReached()
  850. {
  851. // Deactivated, needs more investigating if this check really makes sense
  852. return false;
  853. /*
  854. * Commented out to suppress static analyzer issues
  855. *
  856. if ($this->is_backend()) {
  857. $process = 'backend';
  858. $max_processes = Core\Config::get('system', 'max_processes_backend');
  859. if (intval($max_processes) == 0) {
  860. $max_processes = 5;
  861. }
  862. } else {
  863. $process = 'frontend';
  864. $max_processes = Core\Config::get('system', 'max_processes_frontend');
  865. if (intval($max_processes) == 0) {
  866. $max_processes = 20;
  867. }
  868. }
  869. $processlist = DBA::processlist();
  870. if ($processlist['list'] != '') {
  871. Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
  872. if ($processlist['amount'] > $max_processes) {
  873. Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
  874. return true;
  875. }
  876. }
  877. return false;
  878. */
  879. }
  880. /**
  881. * @brief Checks if the minimal memory is reached
  882. *
  883. * @return bool Is the memory limit reached?
  884. */
  885. public function isMinMemoryReached()
  886. {
  887. $min_memory = Core\Config::get('system', 'min_memory', 0);
  888. if ($min_memory == 0) {
  889. return false;
  890. }
  891. if (!is_readable('/proc/meminfo')) {
  892. return false;
  893. }
  894. $memdata = explode("\n", file_get_contents('/proc/meminfo'));
  895. $meminfo = [];
  896. foreach ($memdata as $line) {
  897. $data = explode(':', $line);
  898. if (count($data) != 2) {
  899. continue;
  900. }
  901. list($key, $val) = $data;
  902. $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
  903. $meminfo[$key] = (int) ($meminfo[$key] / 1024);
  904. }
  905. if (!isset($meminfo['MemFree'])) {
  906. return false;
  907. }
  908. $free = $meminfo['MemFree'];
  909. $reached = ($free < $min_memory);
  910. if ($reached) {
  911. Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
  912. }
  913. return $reached;
  914. }
  915. /**
  916. * @brief Checks if the maximum load is reached
  917. *
  918. * @return bool Is the load reached?
  919. */
  920. public function isMaxLoadReached()
  921. {
  922. if ($this->isBackend()) {
  923. $process = 'backend';
  924. $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
  925. if ($maxsysload < 1) {
  926. $maxsysload = 50;
  927. }
  928. } else {
  929. $process = 'frontend';
  930. $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
  931. if ($maxsysload < 1) {
  932. $maxsysload = 50;
  933. }
  934. }
  935. $load = Core\System::currentLoad();
  936. if ($load) {
  937. if (intval($load) > $maxsysload) {
  938. Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
  939. return true;
  940. }
  941. }
  942. return false;
  943. }
  944. /**
  945. * Executes a child process with 'proc_open'
  946. *
  947. * @param string $command The command to execute
  948. * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
  949. */
  950. public function proc_run($command, $args)
  951. {
  952. if (!function_exists('proc_open')) {
  953. return;
  954. }
  955. $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
  956. foreach ($args as $key => $value) {
  957. if (!is_null($value) && is_bool($value) && !$value) {
  958. continue;
  959. }
  960. $cmdline .= ' --' . $key;
  961. if (!is_null($value) && !is_bool($value)) {
  962. $cmdline .= ' ' . $value;
  963. }
  964. }
  965. if ($this->isMinMemoryReached()) {
  966. return;
  967. }
  968. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  969. $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
  970. } else {
  971. $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
  972. }
  973. if (!is_resource($resource)) {
  974. Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
  975. return;
  976. }
  977. proc_close($resource);
  978. }
  979. /**
  980. * @brief Returns the system user that is executing the script
  981. *
  982. * This mostly returns something like "www-data".
  983. *
  984. * @return string system username
  985. */
  986. private static function getSystemUser()
  987. {
  988. if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
  989. return '';
  990. }
  991. $processUser = posix_getpwuid(posix_geteuid());
  992. return $processUser['name'];
  993. }
  994. /**
  995. * @brief Checks if a given directory is usable for the system
  996. *
  997. * @return boolean the directory is usable
  998. */
  999. public static function isDirectoryUsable($directory, $check_writable = true)
  1000. {
  1001. if ($directory == '') {
  1002. Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
  1003. return false;
  1004. }
  1005. if (!file_exists($directory)) {
  1006. Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
  1007. return false;
  1008. }
  1009. if (is_file($directory)) {
  1010. Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
  1011. return false;
  1012. }
  1013. if (!is_dir($directory)) {
  1014. Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
  1015. return false;
  1016. }
  1017. if ($check_writable && !is_writable($directory)) {
  1018. Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
  1019. return false;
  1020. }
  1021. return true;
  1022. }
  1023. /**
  1024. * @param string $cat Config category
  1025. * @param string $k Config key
  1026. * @param mixed $default Default value if it isn't set
  1027. *
  1028. * @return string Returns the value of the Config entry
  1029. */
  1030. public function getConfigValue($cat, $k, $default = null)
  1031. {
  1032. $return = $default;
  1033. if ($cat === 'config') {
  1034. if (isset($this->config[$k])) {
  1035. $return = $this->config[$k];
  1036. }
  1037. } else {
  1038. if (isset($this->config[$cat][$k])) {
  1039. $return = $this->config[$cat][$k];
  1040. }
  1041. }
  1042. return $return;
  1043. }
  1044. /**
  1045. * Sets a default value in the config cache. Ignores already existing keys.
  1046. *
  1047. * @param string $cat Config category
  1048. * @param string $k Config key
  1049. * @param mixed $v Default value to set
  1050. */
  1051. private function setDefaultConfigValue($cat, $k, $v)
  1052. {
  1053. if (!isset($this->config[$cat][$k])) {
  1054. $this->setConfigValue($cat, $k, $v);
  1055. }
  1056. }
  1057. /**
  1058. * Sets a value in the config cache. Accepts raw output from the config table
  1059. *
  1060. * @param string $cat Config category
  1061. * @param string $k Config key
  1062. * @param mixed $v Value to set
  1063. */
  1064. public function setConfigValue($cat, $k, $v)
  1065. {
  1066. // Only arrays are serialized in database, so we have to unserialize sparingly
  1067. $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
  1068. if ($cat === 'config') {
  1069. $this->config[$k] = $value;
  1070. } else {
  1071. if (!isset($this->config[$cat])) {
  1072. $this->config[$cat] = [];
  1073. }
  1074. $this->config[$cat][$k] = $value;
  1075. }
  1076. }
  1077. /**
  1078. * Deletes a value from the config cache
  1079. *
  1080. * @param string $cat Config category
  1081. * @param string $k Config key
  1082. */
  1083. public function deleteConfigValue($cat, $k)
  1084. {
  1085. if ($cat === 'config') {
  1086. if (isset($this->config[$k])) {
  1087. unset($this->config[$k]);
  1088. }
  1089. } else {
  1090. if (isset($this->config[$cat][$k])) {
  1091. unset($this->config[$cat][$k]);
  1092. }
  1093. }
  1094. }
  1095. /**
  1096. * Retrieves a value from the user config cache
  1097. *
  1098. * @param int $uid User Id
  1099. * @param string $cat Config category
  1100. * @param string $k Config key
  1101. * @param mixed $default Default value if key isn't set
  1102. *
  1103. * @return string The value of the config entry
  1104. */
  1105. public function getPConfigValue($uid, $cat, $k, $default = null)
  1106. {
  1107. $return = $default;
  1108. if (isset($this->config[$uid][$cat][$k])) {
  1109. $return = $this->config[$uid][$cat][$k];
  1110. }
  1111. return $return;
  1112. }
  1113. /**
  1114. * Sets a value in the user config cache
  1115. *
  1116. * Accepts raw output from the pconfig table
  1117. *
  1118. * @param int $uid User Id
  1119. * @param string $cat Config category
  1120. * @param string $k Config key
  1121. * @param mixed $v Value to set
  1122. */
  1123. public function setPConfigValue($uid, $cat, $k, $v)
  1124. {
  1125. // Only arrays are serialized in database, so we have to unserialize sparingly
  1126. $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
  1127. if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
  1128. $this->config[$uid] = [];
  1129. }
  1130. if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
  1131. $this->config[$uid][$cat] = [];
  1132. }
  1133. $this->config[$uid][$cat][$k] = $value;
  1134. }
  1135. /**
  1136. * Deletes 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. */
  1142. public function deletePConfigValue($uid, $cat, $k)
  1143. {
  1144. if (isset($this->config[$uid][$cat][$k])) {
  1145. unset($this->config[$uid][$cat][$k]);
  1146. }
  1147. }
  1148. /**
  1149. * Generates the site's default sender email address
  1150. *
  1151. * @return string
  1152. */
  1153. public function getSenderEmailAddress()
  1154. {
  1155. $sender_email = Core\Config::get('config', 'sender_email');
  1156. if (empty($sender_email)) {
  1157. $hostname = $this->getHostName();
  1158. if (strpos($hostname, ':')) {
  1159. $hostname = substr($hostname, 0, strpos($hostname, ':'));
  1160. }
  1161. $sender_email = 'noreply@' . $hostname;
  1162. }
  1163. return $sender_email;
  1164. }
  1165. /**
  1166. * Returns the current theme name.
  1167. *
  1168. * @return string the name of the current theme
  1169. */
  1170. public function getCurrentTheme()
  1171. {
  1172. if ($this->getMode()->isInstall()) {
  1173. return '';
  1174. }
  1175. if (!$this->currentTheme) {
  1176. $this->computeCurrentTheme();
  1177. }
  1178. return $this->currentTheme;
  1179. }
  1180. public function setCurrentTheme($theme)
  1181. {
  1182. $this->currentTheme = $theme;
  1183. }
  1184. /**
  1185. * Computes the current theme name based on the node settings, the user settings and the device type
  1186. *
  1187. * @throws Exception
  1188. */
  1189. private function computeCurrentTheme()
  1190. {
  1191. $system_theme = Core\Config::get('system', 'theme');
  1192. if (!$system_theme) {
  1193. throw new Exception(Core\L10n::t('No system theme config value set.'));
  1194. }
  1195. // Sane default
  1196. $this->currentTheme = $system_theme;
  1197. $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
  1198. $page_theme = null;
  1199. // Find the theme that belongs to the user whose stuff we are looking at
  1200. if ($this->profile_uid && ($this->profile_uid != local_user())) {
  1201. // Allow folks to override user themes and always use their own on their own site.
  1202. // This works only if the user is on the same server
  1203. $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
  1204. if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
  1205. $page_theme = $user['theme'];
  1206. }
  1207. }
  1208. $user_theme = Core\Session::get('theme', $system_theme);
  1209. // Specific mobile theme override
  1210. if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
  1211. $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
  1212. $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
  1213. // --- means same mobile theme as desktop
  1214. if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
  1215. $user_theme = $user_mobile_theme;
  1216. }
  1217. }
  1218. if ($page_theme) {
  1219. $theme_name = $page_theme;
  1220. } else {
  1221. $theme_name = $user_theme;
  1222. }
  1223. if ($theme_name
  1224. && in_array($theme_name, $allowed_themes)
  1225. && (file_exists('view/theme/' . $theme_name . '/style.css')
  1226. || file_exists('view/theme/' . $theme_name . '/style.php'))
  1227. ) {
  1228. $this->currentTheme = $theme_name;
  1229. }
  1230. }
  1231. /**
  1232. * @brief Return full URL to theme which is currently in effect.
  1233. *
  1234. * Provide a sane default if nothing is chosen or the specified theme does not exist.
  1235. *
  1236. * @return string
  1237. */
  1238. public function getCurrentThemeStylesheetPath()
  1239. {
  1240. return Core\Theme::getStylesheetPath($this->getCurrentTheme());
  1241. }
  1242. /**
  1243. * Check if request was an AJAX (xmlhttprequest) request.
  1244. *
  1245. * @return boolean true if it was an AJAX request
  1246. */
  1247. public function isAjax()
  1248. {
  1249. return $this->isAjax;
  1250. }
  1251. /**
  1252. * Returns the value of a argv key
  1253. * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
  1254. *
  1255. * @param int $position the position of the argument
  1256. * @param mixed $default the default value if not found
  1257. *
  1258. * @return mixed returns the value of the argument
  1259. */
  1260. public function getArgumentValue($position, $default = '')
  1261. {
  1262. if (array_key_exists($position, $this->argv)) {
  1263. return $this->argv[$position];
  1264. }
  1265. return $default;
  1266. }
  1267. /**
  1268. * Sets the base url for use in cmdline programs which don't have
  1269. * $_SERVER variables
  1270. */
  1271. public function checkURL()
  1272. {
  1273. $url = Core\Config::get('system', 'url');
  1274. // if the url isn't set or the stored url is radically different
  1275. // than the currently visited url, store the current value accordingly.
  1276. // "Radically different" ignores common variations such as http vs https
  1277. // and www.example.com vs example.com.
  1278. // We will only change the url to an ip address if there is no existing setting
  1279. if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
  1280. Core\Config::set('system', 'url', $this->getBaseURL());
  1281. }
  1282. }
  1283. /**
  1284. * Frontend App script
  1285. *
  1286. * The App object behaves like a container and a dispatcher at the same time, including a representation of the
  1287. * request and a representation of the response.
  1288. *
  1289. * This probably should change to limit the size of this monster method.
  1290. */
  1291. public function runFrontend()
  1292. {
  1293. // Missing DB connection: ERROR
  1294. if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
  1295. Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
  1296. }
  1297. // Max Load Average reached: ERROR
  1298. if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
  1299. header('Retry-After: 120');
  1300. header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
  1301. Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
  1302. }
  1303. if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
  1304. Core\System::httpExit(404);
  1305. }
  1306. if (!$this->getMode()->isInstall()) {
  1307. // Force SSL redirection
  1308. if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
  1309. && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
  1310. && strpos($this->getBaseURL(), 'https://') === 0
  1311. && $_SERVER['REQUEST_METHOD'] == 'GET') {
  1312. header('HTTP/1.1 302 Moved Temporarily');
  1313. header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
  1314. exit();
  1315. }
  1316. Core\Session::init();
  1317. Core\Hook::callAll('init_1');
  1318. }
  1319. // Exclude the backend processes from the session management
  1320. if (!$this->isBackend()) {
  1321. $stamp1 = microtime(true);
  1322. session_start();
  1323. $this->saveTimestamp($stamp1, 'parser');
  1324. Core\L10n::setSessionVariable();
  1325. Core\L10n::setLangFromSession();
  1326. } else {
  1327. $_SESSION = [];
  1328. Core\Worker::executeIfIdle();
  1329. }
  1330. // ZRL
  1331. if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
  1332. $this->query_string = Model\Profile::stripZrls($this->query_string);
  1333. if (!local_user()) {
  1334. // Only continue when the given profile link seems valid
  1335. // Valid profile links contain a path with "/profile/" and no query parameters
  1336. if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
  1337. strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
  1338. if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
  1339. $_SESSION['my_url'] = $_GET['zrl'];
  1340. $_SESSION['authenticated'] = 0;
  1341. }
  1342. Model\Profile::zrlInit($this);
  1343. } else {
  1344. // Someone came with an invalid parameter, maybe as a DDoS attempt
  1345. // We simply stop processing here
  1346. Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
  1347. Core\System::httpExit(403, ['title' => '403 Forbidden']);
  1348. }
  1349. }
  1350. }
  1351. if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
  1352. $token = $_GET['owt'];
  1353. $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
  1354. Model\Profile::openWebAuthInit($token);
  1355. }
  1356. Module\Login::sessionAuth();
  1357. if (empty($_SESSION['authenticated'])) {
  1358. header('X-Account-Management-Status: none');
  1359. }
  1360. $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
  1361. $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
  1362. $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
  1363. /*
  1364. * check_config() is responsible for running update scripts. These automatically
  1365. * update the DB schema whenever we push a new one out. It also checks to see if
  1366. * any addons have been added or removed and reacts accordingly.
  1367. */
  1368. // in install mode, any url loads install module
  1369. // but we need "view" module for stylesheet
  1370. if ($this->getMode()->isInstall() && $this->module != 'view') {
  1371. $this->module = 'install';
  1372. } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
  1373. $this->module = 'maintenance';
  1374. } else {
  1375. $this->checkURL();
  1376. Core\Update::check(false);
  1377. Core\Addon::loadAddons();
  1378. Core\Hook::loadHooks();
  1379. }
  1380. $this->page = [
  1381. 'aside' => '',
  1382. 'bottom' => '',
  1383. 'content' => '',
  1384. 'footer' => '',
  1385. 'htmlhead' => '',
  1386. 'nav' => '',
  1387. 'page_title' => '',
  1388. 'right_aside' => '',
  1389. 'template' => '',
  1390. 'title' => ''
  1391. ];
  1392. if (strlen($this->module)) {
  1393. // Compatibility with the Android Diaspora client
  1394. if ($this->module == 'stream') {
  1395. $this->internalRedirect('network?f=&order=post');
  1396. }
  1397. if ($this->module == 'conversations') {
  1398. $this->internalRedirect('message');
  1399. }
  1400. if ($this->module == 'commented') {
  1401. $this->internalRedirect('network?f=&order=comment');
  1402. }
  1403. if ($this->module == 'liked') {
  1404. $this->internalRedirect('network?f=&order=comment');
  1405. }
  1406. if ($this->module == 'activity') {
  1407. $this->internalRedirect('network/?f=&conv=1');
  1408. }
  1409. if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
  1410. $this->internalRedirect('bookmarklet');
  1411. }
  1412. if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
  1413. $this->internalRedirect('settings');
  1414. }
  1415. if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
  1416. $this->internalRedirect('search');
  1417. }
  1418. // Compatibility with the Firefox App
  1419. if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
  1420. $this->module = "login";
  1421. }
  1422. $privateapps = Core\Config::get('config', 'private_addons', false);
  1423. if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
  1424. //Check if module is an app and if public access to apps is allowed or not
  1425. if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
  1426. info(Core\L10n::t("You must be logged in to use addons. "));
  1427. } else {
  1428. include_once "addon/{$this->module}/{$this->module}.php";
  1429. if (function_exists($this->module . '_module')) {
  1430. LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
  1431. $this->module_class = 'Friendica\\LegacyModule';
  1432. $this->module_loaded = true;
  1433. }
  1434. }
  1435. }
  1436. // Controller class routing
  1437. if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
  1438. $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
  1439. $this->module_loaded = true;
  1440. }
  1441. /* If not, next look for a 'standard' program module in the 'mod' directory
  1442. * We emulate a Module class through the LegacyModule class
  1443. */
  1444. if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
  1445. LegacyModule::setModuleFile("mod/{$this->module}.php");
  1446. $this->module_class = 'Friendica\\LegacyModule';
  1447. $this->module_loaded = true;
  1448. }
  1449. /* The URL provided does not resolve to a valid module.
  1450. *
  1451. * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
  1452. * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
  1453. * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
  1454. * this will often succeed and eventually do the right thing.
  1455. *
  1456. * Otherwise we are going to emit a 404 not found.
  1457. */
  1458. if (! $this->module_loaded) {
  1459. // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
  1460. if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
  1461. exit();
  1462. }
  1463. if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
  1464. Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
  1465. $this->internalRedirect($_SERVER['REQUEST_URI']);
  1466. }
  1467. Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
  1468. header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
  1469. $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
  1470. $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
  1471. '$message' => Core\L10n::t('Page not found.')
  1472. ]);
  1473. }
  1474. }
  1475. $content = '';
  1476. // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
  1477. if ($this->module_loaded) {
  1478. $this->page['page_title'] = $this->module;
  1479. $placeholder = '';
  1480. Core\Hook::callAll($this->module . '_mod_init', $placeholder);
  1481. call_user_func([$this->module_class, 'init']);
  1482. // "rawContent" is especially meant for technical endpoints.
  1483. // This endpoint doesn't need any theme initialization or other comparable stuff.
  1484. if (!$this->error) {
  1485. call_user_func([$this->module_class, 'rawContent']);
  1486. }
  1487. }
  1488. // Load current theme info after module has been initialized as theme could have been set in module
  1489. $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
  1490. if (file_exists($theme_info_file)) {
  1491. require_once $theme_info_file;
  1492. }
  1493. if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
  1494. $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
  1495. $func($this);
  1496. }
  1497. if ($this->module_loaded) {
  1498. if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
  1499. Core\Hook::callAll($this->module . '_mod_post', $_POST);
  1500. call_user_func([$this->module_class, 'post']);
  1501. }
  1502. if (! $this->error) {
  1503. Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
  1504. call_user_func([$this->module_class, 'afterpost']);
  1505. }
  1506. if (! $this->error) {
  1507. $arr = ['content' => $content];
  1508. Core\Hook::callAll($this->module . '_mod_content', $arr);
  1509. $content = $arr['content'];
  1510. $arr = ['content' => call_user_func([$this->module_class, 'content'])];
  1511. Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
  1512. $content .= $arr['content'];
  1513. }
  1514. }
  1515. // initialise content region
  1516. if ($this->getMode()->isNormal()) {
  1517. Core\Hook::callAll('page_content_top', $this->page['content']);
  1518. }
  1519. $this->page['content'] .= $content;
  1520. /* Create the page head after setting the language
  1521. * and getting any auth credentials.
  1522. *
  1523. * Moved initHead() and initFooter() to after
  1524. * all the module functions have executed so that all
  1525. * theme choices made by the modules can take effect.
  1526. */
  1527. $this->initHead();
  1528. /* Build the page ending -- this is stuff that goes right before
  1529. * the closing </body> tag
  1530. */
  1531. $this->initFooter();
  1532. /* now that we've been through the module content, see if the page reported
  1533. * a permission problem and if so, a 403 response would seem to be in order.
  1534. */
  1535. if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
  1536. header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
  1537. }
  1538. // Report anything which needs to be communicated in the notification area (before the main body)
  1539. Core\Hook::callAll('page_end', $this->page['content']);
  1540. // Add the navigation (menu) template
  1541. if ($this->module != 'install' && $this->module != 'maintenance') {
  1542. $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
  1543. $this->page['nav'] = Content\Nav::build($this);
  1544. }
  1545. // Build the page - now that we have all the components
  1546. if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
  1547. $doc = new DOMDocument();
  1548. $target = new DOMDocument();
  1549. $target->loadXML("<root></root>");
  1550. $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
  1551. /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
  1552. @$doc->loadHTML($content);
  1553. $xpath = new DOMXPath($doc);
  1554. $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
  1555. foreach ($list as $item) {
  1556. $item = $target->importNode($item, true);
  1557. // And then append it to the target
  1558. $target->documentElement->appendChild($item);
  1559. }
  1560. }
  1561. if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
  1562. header("Content-type: text/html; charset=utf-8");
  1563. echo substr($target->saveHTML(), 6, -8);
  1564. exit();
  1565. }
  1566. $page = $this->page;
  1567. $profile = $this->profile;
  1568. header("X-Friendica-Version: " . FRIENDICA_VERSION);
  1569. header("Content-type: text/html; charset=utf-8");
  1570. if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
  1571. header("Strict-Transport-Security: max-age=31536000");
  1572. }
  1573. // Some security stuff
  1574. header('X-Content-Type-Options: nosniff');
  1575. header('X-XSS-Protection: 1; mode=block');
  1576. header('X-Permitted-Cross-Domain-Policies: none');
  1577. header('X-Frame-Options: sameorigin');
  1578. // Things like embedded OSM maps don't work, when this is enabled
  1579. // header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https: data:; media-src 'self' https:; child-src 'self' https:; object-src 'none'");
  1580. /* We use $_GET["mode"] for special page templates. So we will check if we have
  1581. * to load another page template than the default one.
  1582. * The page templates are located in /view/php/ or in the theme directory.
  1583. */
  1584. if (isset($_GET["mode"])) {
  1585. $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
  1586. }
  1587. // If there is no page template use the default page template
  1588. if (empty($template)) {
  1589. $template = Core\Theme::getPathForFile("default.php");
  1590. }
  1591. // Theme templates expect $a as an App instance
  1592. $a = $this;
  1593. // Used as is in view/php/default.php
  1594. $lang = Core\L10n::getCurrentLang();
  1595. /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
  1596. require_once $template;
  1597. }
  1598. /**
  1599. * Redirects to another module relative to the current Friendica base.
  1600. * If you want to redirect to a external URL, use System::externalRedirectTo()
  1601. *
  1602. * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
  1603. * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
  1604. *
  1605. * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
  1606. */
  1607. public function internalRedirect($toUrl = '', $ssl = false)
  1608. {
  1609. if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
  1610. throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
  1611. }
  1612. $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
  1613. Core\System::externalRedirect($redirectTo);
  1614. }
  1615. /**
  1616. * Automatically redirects to relative or absolute URL
  1617. * Should only be used if it isn't clear if the URL is either internal or external
  1618. *
  1619. * @param string $toUrl The target URL
  1620. *
  1621. */
  1622. public function redirect($toUrl)
  1623. {
  1624. if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
  1625. Core\System::externalRedirect($toUrl);
  1626. } else {
  1627. $this->internalRedirect($toUrl);
  1628. }
  1629. }
  1630. }