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.

1429 lines
37KB

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