Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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