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.

1943 lines
56KB

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