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.

960 lines
26 KiB

  1. <?php
  2. namespace Friendica;
  3. use Friendica\Core\Config;
  4. use Friendica\Core\PConfig;
  5. /**
  6. *
  7. * class: App
  8. *
  9. * @brief Our main application structure for the life of this page.
  10. *
  11. * Primarily deals with the URL that got us here
  12. * and tries to make some sense of it, and
  13. * stores our page contents and config storage
  14. * and anything else that might need to be passed around
  15. * before we spit the page out.
  16. *
  17. */
  18. class App {
  19. public $module_loaded = false;
  20. public $query_string;
  21. public $config;
  22. public $page;
  23. public $profile;
  24. public $profile_uid;
  25. public $user;
  26. public $cid;
  27. public $contact;
  28. public $contacts;
  29. public $page_contact;
  30. public $content;
  31. public $data = array();
  32. public $error = false;
  33. public $cmd;
  34. public $argv;
  35. public $argc;
  36. public $module;
  37. public $pager;
  38. public $strings;
  39. public $path;
  40. public $hooks;
  41. public $timezone;
  42. public $interactive = true;
  43. public $plugins;
  44. public $apps = array();
  45. public $identities;
  46. public $is_mobile = false;
  47. public $is_tablet = false;
  48. public $is_friendica_app;
  49. public $performance = array();
  50. public $callstack = array();
  51. public $theme_info = array();
  52. public $backend = true;
  53. public $nav_sel;
  54. public $category;
  55. // Allow themes to control internal parameters
  56. // by changing App values in theme.php
  57. public $sourcename = '';
  58. public $videowidth = 425;
  59. public $videoheight = 350;
  60. public $force_max_items = 0;
  61. public $theme_thread_allow = true;
  62. public $theme_events_in_profile = true;
  63. /**
  64. * @brief An array for all theme-controllable parameters
  65. *
  66. * Mostly unimplemented yet. Only options 'template_engine' and
  67. * beyond are used.
  68. */
  69. public $theme = array(
  70. 'sourcename' => '',
  71. 'videowidth' => 425,
  72. 'videoheight' => 350,
  73. 'force_max_items' => 0,
  74. 'thread_allow' => true,
  75. 'stylesheet' => '',
  76. 'template_engine' => 'smarty3',
  77. );
  78. /**
  79. * @brief An array of registered template engines ('name'=>'class name')
  80. */
  81. public $template_engines = array();
  82. /**
  83. * @brief An array of instanced template engines ('name'=>'instance')
  84. */
  85. public $template_engine_instance = array();
  86. public $process_id;
  87. private $ldelim = array(
  88. 'internal' => '',
  89. 'smarty3' => '{{'
  90. );
  91. private $rdelim = array(
  92. 'internal' => '',
  93. 'smarty3' => '}}'
  94. );
  95. private $scheme;
  96. private $hostname;
  97. private $db;
  98. private $curl_code;
  99. private $curl_content_type;
  100. private $curl_headers;
  101. private $cached_profile_image;
  102. private $cached_profile_picdate;
  103. private static $a;
  104. /**
  105. * @brief App constructor.
  106. */
  107. function __construct() {
  108. global $default_timezone;
  109. $hostname = '';
  110. if (file_exists('.htpreconfig.php')) {
  111. include '.htpreconfig.php';
  112. }
  113. $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
  114. date_default_timezone_set($this->timezone);
  115. $this->performance['start'] = microtime(true);
  116. $this->performance['database'] = 0;
  117. $this->performance['database_write'] = 0;
  118. $this->performance['network'] = 0;
  119. $this->performance['file'] = 0;
  120. $this->performance['rendering'] = 0;
  121. $this->performance['parser'] = 0;
  122. $this->performance['marktime'] = 0;
  123. $this->performance['markstart'] = microtime(true);
  124. $this->callstack['database'] = array();
  125. $this->callstack['database_write'] = array();
  126. $this->callstack['network'] = array();
  127. $this->callstack['file'] = array();
  128. $this->callstack['rendering'] = array();
  129. $this->callstack['parser'] = array();
  130. $this->config = array();
  131. $this->page = array();
  132. $this->pager = array();
  133. $this->query_string = '';
  134. $this->process_id = uniqid('log', true);
  135. startup();
  136. set_include_path(
  137. get_include_path() . PATH_SEPARATOR
  138. . 'include' . PATH_SEPARATOR
  139. . 'library' . PATH_SEPARATOR
  140. . 'library/langdet' . PATH_SEPARATOR
  141. . '.');
  142. $this->scheme = 'http';
  143. if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
  144. (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
  145. (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
  146. (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
  147. (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
  148. (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
  149. ) {
  150. $this->scheme = 'https';
  151. }
  152. if (x($_SERVER, 'SERVER_NAME')) {
  153. $this->hostname = $_SERVER['SERVER_NAME'];
  154. if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
  155. $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
  156. }
  157. /*
  158. * Figure out if we are running at the top of a domain
  159. * or in a sub-directory and adjust accordingly
  160. */
  161. /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
  162. $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
  163. if (isset($path) && strlen($path) && ($path != $this->path)) {
  164. $this->path = $path;
  165. }
  166. }
  167. if ($hostname != '') {
  168. $this->hostname = $hostname;
  169. }
  170. if (is_array($_SERVER['argv']) && $_SERVER['argc'] > 1 && substr(end($_SERVER['argv']), 0, 4) == 'http') {
  171. $this->set_baseurl(array_pop($_SERVER['argv']));
  172. $_SERVER['argc'] --;
  173. }
  174. if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
  175. $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
  176. // removing trailing / - maybe a nginx problem
  177. $this->query_string = ltrim($this->query_string, '/');
  178. } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
  179. $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
  180. // removing trailing / - maybe a nginx problem
  181. $this->query_string = ltrim($this->query_string, '/');
  182. }
  183. if (x($_GET, 'pagename')) {
  184. $this->cmd = trim($_GET['pagename'], '/\\');
  185. } elseif (x($_GET, 'q')) {
  186. $this->cmd = trim($_GET['q'], '/\\');
  187. }
  188. // fix query_string
  189. $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
  190. // unix style "homedir"
  191. if (substr($this->cmd, 0, 1) === '~') {
  192. $this->cmd = 'profile/' . substr($this->cmd, 1);
  193. }
  194. // Diaspora style profile url
  195. if (substr($this->cmd, 0, 2) === 'u/') {
  196. $this->cmd = 'profile/' . substr($this->cmd, 2);
  197. }
  198. /*
  199. * Break the URL path into C style argc/argv style arguments for our
  200. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  201. * will be 3 (integer) and $this->argv will contain:
  202. * [0] => 'module'
  203. * [1] => 'arg1'
  204. * [2] => 'arg2'
  205. *
  206. *
  207. * There will always be one argument. If provided a naked domain
  208. * URL, $this->argv[0] is set to "home".
  209. */
  210. $this->argv = explode('/', $this->cmd);
  211. $this->argc = count($this->argv);
  212. if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
  213. $this->module = str_replace('.', '_', $this->argv[0]);
  214. $this->module = str_replace('-', '_', $this->module);
  215. } else {
  216. $this->argc = 1;
  217. $this->argv = array('home');
  218. $this->module = 'home';
  219. }
  220. // See if there is any page number information, and initialise pagination
  221. $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
  222. $this->pager['itemspage'] = 50;
  223. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  224. if ($this->pager['start'] < 0) {
  225. $this->pager['start'] = 0;
  226. }
  227. $this->pager['total'] = 0;
  228. // Detect mobile devices
  229. $mobile_detect = new \Mobile_Detect();
  230. $this->is_mobile = $mobile_detect->isMobile();
  231. $this->is_tablet = $mobile_detect->isTablet();
  232. // Friendica-Client
  233. $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)');
  234. // Register template engines
  235. $dc = get_declared_classes();
  236. foreach ($dc as $k) {
  237. if (in_array('ITemplateEngine', class_implements($k))) {
  238. $this->register_template_engine($k);
  239. }
  240. }
  241. self::$a = $this;
  242. }
  243. public static function get_basepath() {
  244. $basepath = get_config('system', 'basepath');
  245. if ($basepath == '') {
  246. $basepath = dirname(__FILE__);
  247. }
  248. if ($basepath == '') {
  249. $basepath = $_SERVER['DOCUMENT_ROOT'];
  250. }
  251. if ($basepath == '') {
  252. $basepath = $_SERVER['PWD'];
  253. }
  254. return $basepath;
  255. }
  256. function get_scheme() {
  257. return $this->scheme;
  258. }
  259. /**
  260. * @brief Retrieves the Friendica instance base URL
  261. *
  262. * This function assembles the base URL from multiple parts:
  263. * - Protocol is determined either by the request or a combination of
  264. * system.ssl_policy and the $ssl parameter.
  265. * - Host name is determined either by system.hostname or inferred from request
  266. * - Path is inferred from SCRIPT_NAME
  267. *
  268. * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
  269. *
  270. * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
  271. * @return string Friendica server base URL
  272. */
  273. function get_baseurl($ssl = false) {
  274. // Is the function called statically?
  275. if (!(isset($this) && get_class($this) == __CLASS__)) {
  276. return self::$a->get_baseurl($ssl);
  277. }
  278. $scheme = $this->scheme;
  279. if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
  280. $scheme = 'https';
  281. }
  282. // Basically, we have $ssl = true on any links which can only be seen by a logged in user
  283. // (and also the login link). Anything seen by an outsider will have it turned off.
  284. if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
  285. if ($ssl) {
  286. $scheme = 'https';
  287. } else {
  288. $scheme = 'http';
  289. }
  290. }
  291. if (Config::get('config', 'hostname') != '') {
  292. $this->hostname = Config::get('config', 'hostname');
  293. }
  294. return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
  295. }
  296. /**
  297. * @brief Initializes the baseurl components
  298. *
  299. * Clears the baseurl cache to prevent inconstistencies
  300. *
  301. * @param string $url
  302. */
  303. function set_baseurl($url) {
  304. $parsed = @parse_url($url);
  305. if ($parsed) {
  306. $this->scheme = $parsed['scheme'];
  307. $hostname = $parsed['host'];
  308. if (x($parsed, 'port')) {
  309. $hostname .= ':' . $parsed['port'];
  310. }
  311. if (x($parsed, 'path')) {
  312. $this->path = trim($parsed['path'], '\\/');
  313. }
  314. if (file_exists('.htpreconfig.php')) {
  315. include '.htpreconfig.php';
  316. }
  317. if (Config::get('config', 'hostname') != '') {
  318. $this->hostname = Config::get('config', 'hostname');
  319. }
  320. if (!isset($this->hostname) OR ( $this->hostname == '')) {
  321. $this->hostname = $hostname;
  322. }
  323. }
  324. }
  325. function get_hostname() {
  326. if (Config::get('config', 'hostname') != '') {
  327. $this->hostname = Config::get('config', 'hostname');
  328. }
  329. return $this->hostname;
  330. }
  331. function set_hostname($h) {
  332. $this->hostname = $h;
  333. }
  334. function set_path($p) {
  335. $this->path = trim(trim($p), '/');
  336. }
  337. function get_path() {
  338. return $this->path;
  339. }
  340. function set_pager_total($n) {
  341. $this->pager['total'] = intval($n);
  342. }
  343. function set_pager_itemspage($n) {
  344. $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
  345. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  346. }
  347. function set_pager_page($n) {
  348. $this->pager['page'] = $n;
  349. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  350. }
  351. function init_pagehead() {
  352. $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
  353. // If the update is 'deactivated' set it to the highest integer number (~24 days)
  354. if ($interval < 0) {
  355. $interval = 2147483647;
  356. }
  357. if ($interval < 10000) {
  358. $interval = 40000;
  359. }
  360. // compose the page title from the sitename and the
  361. // current module called
  362. if (!$this->module == '') {
  363. $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
  364. } else {
  365. $this->page['title'] = $this->config['sitename'];
  366. }
  367. /* put the head template at the beginning of page['htmlhead']
  368. * since the code added by the modules frequently depends on it
  369. * being first
  370. */
  371. if (!isset($this->page['htmlhead'])) {
  372. $this->page['htmlhead'] = '';
  373. }
  374. // If we're using Smarty, then doing replace_macros() will replace
  375. // any unrecognized variables with a blank string. Since we delay
  376. // replacing $stylesheet until later, we need to replace it now
  377. // with another variable name
  378. if ($this->theme['template_engine'] === 'smarty3') {
  379. $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
  380. } else {
  381. $stylesheet = '$stylesheet';
  382. }
  383. $shortcut_icon = Config::get('system', 'shortcut_icon');
  384. if ($shortcut_icon == '') {
  385. $shortcut_icon = 'images/friendica-32.png';
  386. }
  387. $touch_icon = Config::get('system', 'touch_icon');
  388. if ($touch_icon == '') {
  389. $touch_icon = 'images/friendica-128.png';
  390. }
  391. // get data wich is needed for infinite scroll on the network page
  392. $invinite_scroll = infinite_scroll_data($this->module);
  393. $tpl = get_markup_template('head.tpl');
  394. $this->page['htmlhead'] = replace_macros($tpl, array(
  395. '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
  396. '$local_user' => local_user(),
  397. '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
  398. '$delitem' => t('Delete this item?'),
  399. '$showmore' => t('show more'),
  400. '$showfewer' => t('show fewer'),
  401. '$update_interval' => $interval,
  402. '$shortcut_icon' => $shortcut_icon,
  403. '$touch_icon' => $touch_icon,
  404. '$stylesheet' => $stylesheet,
  405. '$infinite_scroll' => $invinite_scroll,
  406. )) . $this->page['htmlhead'];
  407. }
  408. function init_page_end() {
  409. if (!isset($this->page['end'])) {
  410. $this->page['end'] = '';
  411. }
  412. $tpl = get_markup_template('end.tpl');
  413. $this->page['end'] = replace_macros($tpl, array(
  414. '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
  415. )) . $this->page['end'];
  416. }
  417. function set_curl_code($code) {
  418. $this->curl_code = $code;
  419. }
  420. function get_curl_code() {
  421. return $this->curl_code;
  422. }
  423. function set_curl_content_type($content_type) {
  424. $this->curl_content_type = $content_type;
  425. }
  426. function get_curl_content_type() {
  427. return $this->curl_content_type;
  428. }
  429. function set_curl_headers($headers) {
  430. $this->curl_headers = $headers;
  431. }
  432. function get_curl_headers() {
  433. return $this->curl_headers;
  434. }
  435. function get_cached_avatar_image($avatar_image) {
  436. return $avatar_image;
  437. }
  438. /**
  439. * @brief Removes the baseurl from an url. This avoids some mixed content problems.
  440. *
  441. * @param string $orig_url
  442. *
  443. * @return string The cleaned url
  444. */
  445. function remove_baseurl($orig_url) {
  446. // Is the function called statically?
  447. if (!(isset($this) && get_class($this) == __CLASS__)) {
  448. return self::$a->remove_baseurl($orig_url);
  449. }
  450. // Remove the hostname from the url if it is an internal link
  451. $nurl = normalise_link($orig_url);
  452. $base = normalise_link($this->get_baseurl());
  453. $url = str_replace($base . '/', '', $nurl);
  454. // if it is an external link return the orignal value
  455. if ($url == normalise_link($orig_url)) {
  456. return $orig_url;
  457. } else {
  458. return $url;
  459. }
  460. }
  461. /**
  462. * @brief Register template engine class
  463. *
  464. * If $name is '', is used class static property $class::$name
  465. *
  466. * @param string $class
  467. * @param string $name
  468. */
  469. function register_template_engine($class, $name = '') {
  470. /// @TODO Really === and not just == ?
  471. if ($name === '') {
  472. $v = get_class_vars($class);
  473. if (x($v, 'name'))
  474. $name = $v['name'];
  475. }
  476. if ($name === '') {
  477. echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
  478. killme();
  479. }
  480. $this->template_engines[$name] = $class;
  481. }
  482. /**
  483. * @brief Return template engine instance.
  484. *
  485. * If $name is not defined, return engine defined by theme,
  486. * or default
  487. *
  488. * @param strin $name Template engine name
  489. * @return object Template Engine instance
  490. */
  491. function template_engine($name = '') {
  492. /// @TODO really type-check included?
  493. if ($name !== '') {
  494. $template_engine = $name;
  495. } else {
  496. $template_engine = 'smarty3';
  497. if (x($this->theme, 'template_engine')) {
  498. $template_engine = $this->theme['template_engine'];
  499. }
  500. }
  501. if (isset($this->template_engines[$template_engine])) {
  502. if (isset($this->template_engine_instance[$template_engine])) {
  503. return $this->template_engine_instance[$template_engine];
  504. } else {
  505. $class = $this->template_engines[$template_engine];
  506. $obj = new $class;
  507. $this->template_engine_instance[$template_engine] = $obj;
  508. return $obj;
  509. }
  510. }
  511. echo "template engine <tt>$template_engine</tt> is not registered!\n";
  512. killme();
  513. }
  514. /**
  515. * @brief Returns the active template engine.
  516. *
  517. * @return string
  518. */
  519. function get_template_engine() {
  520. return $this->theme['template_engine'];
  521. }
  522. function set_template_engine($engine = 'smarty3') {
  523. $this->theme['template_engine'] = $engine;
  524. }
  525. function get_template_ldelim($engine = 'smarty3') {
  526. return $this->ldelim[$engine];
  527. }
  528. function get_template_rdelim($engine = 'smarty3') {
  529. return $this->rdelim[$engine];
  530. }
  531. function save_timestamp($stamp, $value) {
  532. if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
  533. return;
  534. }
  535. $duration = (float) (microtime(true) - $stamp);
  536. if (!isset($this->performance[$value])) {
  537. // Prevent ugly E_NOTICE
  538. $this->performance[$value] = 0;
  539. }
  540. $this->performance[$value] += (float) $duration;
  541. $this->performance['marktime'] += (float) $duration;
  542. $callstack = $this->callstack();
  543. if (!isset($this->callstack[$value][$callstack])) {
  544. // Prevent ugly E_NOTICE
  545. $this->callstack[$value][$callstack] = 0;
  546. }
  547. $this->callstack[$value][$callstack] += (float) $duration;
  548. }
  549. /**
  550. * @brief Log active processes into the "process" table
  551. */
  552. function start_process() {
  553. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
  554. $command = basename($trace[0]['file']);
  555. $this->remove_inactive_processes();
  556. q('START TRANSACTION');
  557. $r = q('SELECT `pid` FROM `process` WHERE `pid` = %d', intval(getmypid()));
  558. if (!\dbm::is_result($r)) {
  559. q("INSERT INTO `process` (`pid`,`command`,`created`) VALUES (%d, '%s', '%s')", intval(getmypid()), dbesc($command), dbesc(datetime_convert()));
  560. }
  561. q('COMMIT');
  562. }
  563. /**
  564. * @brief Remove inactive processes
  565. */
  566. function remove_inactive_processes() {
  567. q('START TRANSACTION');
  568. $r = q('SELECT `pid` FROM `process`');
  569. if (\dbm::is_result($r)) {
  570. foreach ($r AS $process) {
  571. if (!posix_kill($process['pid'], 0)) {
  572. q('DELETE FROM `process` WHERE `pid` = %d', intval($process['pid']));
  573. }
  574. }
  575. }
  576. q('COMMIT');
  577. }
  578. /**
  579. * @brief Remove the active process from the "process" table
  580. */
  581. function end_process() {
  582. q('DELETE FROM `process` WHERE `pid` = %d', intval(getmypid()));
  583. }
  584. /**
  585. * @brief Returns a string with a callstack. Can be used for logging.
  586. *
  587. * @return string
  588. */
  589. function callstack() {
  590. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
  591. // We remove the first two items from the list since they contain data that we don't need.
  592. array_shift($trace);
  593. array_shift($trace);
  594. $callstack = array();
  595. foreach ($trace AS $func) {
  596. $callstack[] = $func['function'];
  597. }
  598. return implode(', ', $callstack);
  599. }
  600. function get_useragent() {
  601. return
  602. FRIENDICA_PLATFORM . " '" .
  603. FRIENDICA_CODENAME . "' " .
  604. FRIENDICA_VERSION . '-' .
  605. DB_UPDATE_VERSION . '; ' .
  606. $this->get_baseurl();
  607. }
  608. function is_friendica_app() {
  609. return $this->is_friendica_app;
  610. }
  611. /**
  612. * @brief Checks if the site is called via a backend process
  613. *
  614. * This isn't a perfect solution. But we need this check very early.
  615. * So we cannot wait until the modules are loaded.
  616. *
  617. * @return bool Is it a known backend?
  618. */
  619. function is_backend() {
  620. static $backends = array();
  621. $backends[] = '_well_known';
  622. $backends[] = 'api';
  623. $backends[] = 'dfrn_notify';
  624. $backends[] = 'fetch';
  625. $backends[] = 'hcard';
  626. $backends[] = 'hostxrd';
  627. $backends[] = 'nodeinfo';
  628. $backends[] = 'noscrape';
  629. $backends[] = 'p';
  630. $backends[] = 'poco';
  631. $backends[] = 'post';
  632. $backends[] = 'proxy';
  633. $backends[] = 'pubsub';
  634. $backends[] = 'pubsubhubbub';
  635. $backends[] = 'receive';
  636. $backends[] = 'rsd_xml';
  637. $backends[] = 'salmon';
  638. $backends[] = 'statistics_json';
  639. $backends[] = 'xrd';
  640. // Check if current module is in backend or backend flag is set
  641. return (in_array($this->module, $backends) || $this->backend);
  642. }
  643. /**
  644. * @brief Checks if the maximum number of database processes is reached
  645. *
  646. * @return bool Is the limit reached?
  647. */
  648. function max_processes_reached() {
  649. if ($this->is_backend()) {
  650. $process = 'backend';
  651. $max_processes = Config::get('system', 'max_processes_backend');
  652. if (intval($max_processes) == 0) {
  653. $max_processes = 5;
  654. }
  655. } else {
  656. $process = 'frontend';
  657. $max_processes = Config::get('system', 'max_processes_frontend');
  658. if (intval($max_processes) == 0) {
  659. $max_processes = 20;
  660. }
  661. }
  662. $processlist = \dbm::processlist();
  663. if ($processlist['list'] != '') {
  664. logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
  665. if ($processlist['amount'] > $max_processes) {
  666. logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
  667. return true;
  668. }
  669. }
  670. return false;
  671. }
  672. /**
  673. * @brief Checks if the minimal memory is reached
  674. *
  675. * @return bool Is the memory limit reached?
  676. */
  677. public function min_memory_reached() {
  678. $min_memory = Config::get('system', 'min_memory', 0);
  679. if ($min_memory == 0) {
  680. return false;
  681. }
  682. if (!is_readable('/proc/meminfo')) {
  683. return false;
  684. }
  685. $memdata = explode("\n", file_get_contents('/proc/meminfo'));
  686. $meminfo = array();
  687. foreach ($memdata as $line) {
  688. list($key, $val) = explode(':', $line);
  689. $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
  690. $meminfo[$key] = (int) ($meminfo[$key] / 1024);
  691. }
  692. if (!isset($meminfo['MemAvailable']) OR ! isset($meminfo['MemFree'])) {
  693. return false;
  694. }
  695. $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
  696. $reached = ($free < $min_memory);
  697. if ($reached) {
  698. logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
  699. }
  700. return $reached;
  701. }
  702. /**
  703. * @brief Checks if the maximum load is reached
  704. *
  705. * @return bool Is the load reached?
  706. */
  707. function maxload_reached() {
  708. if ($this->is_backend()) {
  709. $process = 'backend';
  710. $maxsysload = intval(Config::get('system', 'maxloadavg'));
  711. if ($maxsysload < 1) {
  712. $maxsysload = 50;
  713. }
  714. } else {
  715. $process = 'frontend';
  716. $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
  717. if ($maxsysload < 1) {
  718. $maxsysload = 50;
  719. }
  720. }
  721. $load = current_load();
  722. if ($load) {
  723. if (intval($load) > $maxsysload) {
  724. logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
  725. return true;
  726. }
  727. }
  728. return false;
  729. }
  730. function proc_run($args) {
  731. if (!function_exists('proc_open')) {
  732. return;
  733. }
  734. // If the last worker fork was less than 10 seconds before then don't fork another one.
  735. // This should prevent the forking of masses of workers.
  736. $cachekey = 'app:proc_run:started';
  737. $result = \Cache::get($cachekey);
  738. if (!is_null($result) AND ( time() - $result) < 10) {
  739. return;
  740. }
  741. // Set the timestamp of the last proc_run
  742. \Cache::set($cachekey, time(), CACHE_MINUTE);
  743. array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
  744. // add baseurl to args. cli scripts can't construct it
  745. $args[] = $this->get_baseurl();
  746. for ($x = 0; $x < count($args); $x ++) {
  747. $args[$x] = escapeshellarg($args[$x]);
  748. }
  749. $cmdline = implode($args, ' ');
  750. if ($this->min_memory_reached()) {
  751. return;
  752. }
  753. if (get_config('system', 'proc_windows')) {
  754. $resource = proc_open('cmd /c start /b ' . $cmdline, array(), $foo, dirname(__FILE__));
  755. } else {
  756. $resource = proc_open($cmdline . ' &', array(), $foo, dirname(__FILE__));
  757. }
  758. if (!is_resource($resource)) {
  759. logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
  760. return;
  761. }
  762. proc_close($resource);
  763. }
  764. /**
  765. * @brief Returns the system user that is executing the script
  766. *
  767. * This mostly returns something like "www-data".
  768. *
  769. * @return string system username
  770. */
  771. static function systemuser() {
  772. if (!function_exists('posix_getpwuid') OR ! function_exists('posix_geteuid')) {
  773. return '';
  774. }
  775. $processUser = posix_getpwuid(posix_geteuid());
  776. return $processUser['name'];
  777. }
  778. /**
  779. * @brief Checks if a given directory is usable for the system
  780. *
  781. * @return boolean the directory is usable
  782. */
  783. static function directory_usable($directory) {
  784. if ($directory == '') {
  785. logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
  786. return false;
  787. }
  788. if (!file_exists($directory)) {
  789. logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
  790. return false;
  791. }
  792. if (is_file($directory)) {
  793. logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
  794. return false;
  795. }
  796. if (!is_dir($directory)) {
  797. logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
  798. return false;
  799. }
  800. if (!is_writable($directory)) {
  801. logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
  802. return false;
  803. }
  804. return true;
  805. }
  806. }