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.

873 lines
22KB

  1. <?php
  2. /**
  3. * @file boot.php
  4. * This file defines some global constants and includes the central App class.
  5. */
  6. /**
  7. * Friendica
  8. *
  9. * Friendica is a communications platform for integrated social communications
  10. * utilising decentralised communications and linkage to several indie social
  11. * projects - as well as popular mainstream providers.
  12. *
  13. * Our mission is to free our friends and families from the clutches of
  14. * data-harvesting corporations, and pave the way to a future where social
  15. * communications are free and open and flow between alternate providers as
  16. * easily as email does today.
  17. */
  18. require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
  19. use Friendica\App;
  20. use Friendica\BaseObject;
  21. use Friendica\Core\Addon;
  22. use Friendica\Core\Cache;
  23. use Friendica\Core\Config;
  24. use Friendica\Core\L10n;
  25. use Friendica\Core\PConfig;
  26. use Friendica\Core\Protocol;
  27. use Friendica\Core\System;
  28. use Friendica\Core\Update;
  29. use Friendica\Core\Worker;
  30. use Friendica\Database\DBA;
  31. use Friendica\Model\Contact;
  32. use Friendica\Model\Conversation;
  33. use Friendica\Util\DateTimeFormat;
  34. define('FRIENDICA_PLATFORM', 'Friendica');
  35. define('FRIENDICA_CODENAME', 'The Tazmans Flax-lily');
  36. define('FRIENDICA_VERSION', '2018.12-rc');
  37. define('DFRN_PROTOCOL_VERSION', '2.23');
  38. define('NEW_UPDATE_ROUTINE_VERSION', 1170);
  39. /**
  40. * @brief Constant with a HTML line break.
  41. *
  42. * Contains a HTML line break (br) element and a real carriage return with line
  43. * feed for the source.
  44. * This can be used in HTML and JavaScript where needed a line break.
  45. */
  46. define('EOL', "<br />\r\n");
  47. /**
  48. * @brief Image storage quality.
  49. *
  50. * Lower numbers save space at cost of image detail.
  51. * For ease of upgrade, please do not change here. Set system.jpegquality = n in config/local.config.php,
  52. * where n is between 1 and 100, and with very poor results below about 50
  53. */
  54. define('JPEG_QUALITY', 100);
  55. /**
  56. * system.png_quality = n where is between 0 (uncompressed) to 9
  57. */
  58. define('PNG_QUALITY', 8);
  59. /**
  60. * An alternate way of limiting picture upload sizes. Specify the maximum pixel
  61. * length that pictures are allowed to be (for non-square pictures, it will apply
  62. * to the longest side). Pictures longer than this length will be resized to be
  63. * this length (on the longest side, the other side will be scaled appropriately).
  64. * Modify this value using
  65. *
  66. * 'system' => [
  67. * 'max_image_length' => 'n',
  68. * ...
  69. * ],
  70. *
  71. * in config/local.config.php
  72. *
  73. * If you don't want to set a maximum length, set to -1. The default value is
  74. * defined by 'MAX_IMAGE_LENGTH' below.
  75. */
  76. define('MAX_IMAGE_LENGTH', -1);
  77. /**
  78. * Not yet used
  79. */
  80. define('DEFAULT_DB_ENGINE', 'InnoDB');
  81. /**
  82. * @name SSL Policy
  83. *
  84. * SSL redirection policies
  85. * @{
  86. */
  87. define('SSL_POLICY_NONE', 0);
  88. define('SSL_POLICY_FULL', 1);
  89. define('SSL_POLICY_SELFSIGN', 2);
  90. /* @}*/
  91. /**
  92. * @name Register
  93. *
  94. * Registration policies
  95. * @{
  96. */
  97. define('REGISTER_CLOSED', 0);
  98. define('REGISTER_APPROVE', 1);
  99. define('REGISTER_OPEN', 2);
  100. /**
  101. * @}
  102. */
  103. /**
  104. * @name CP
  105. *
  106. * Type of the community page
  107. * @{
  108. */
  109. define('CP_NO_INTERNAL_COMMUNITY', -2);
  110. define('CP_NO_COMMUNITY_PAGE', -1);
  111. define('CP_USERS_ON_SERVER', 0);
  112. define('CP_GLOBAL_COMMUNITY', 1);
  113. define('CP_USERS_AND_GLOBAL', 2);
  114. /**
  115. * @}
  116. */
  117. /**
  118. * These numbers are used in stored permissions
  119. * and existing allocations MUST NEVER BE CHANGED
  120. * OR RE-ASSIGNED! You may only add to them.
  121. */
  122. $netgroup_ids = [
  123. Protocol::DFRN => (-1),
  124. Protocol::ZOT => (-2),
  125. Protocol::OSTATUS => (-3),
  126. Protocol::FEED => (-4),
  127. Protocol::DIASPORA => (-5),
  128. Protocol::MAIL => (-6),
  129. Protocol::FACEBOOK => (-8),
  130. Protocol::LINKEDIN => (-9),
  131. Protocol::XMPP => (-10),
  132. Protocol::MYSPACE => (-11),
  133. Protocol::GPLUS => (-12),
  134. Protocol::PUMPIO => (-13),
  135. Protocol::TWITTER => (-14),
  136. Protocol::DIASPORA2 => (-15),
  137. Protocol::STATUSNET => (-16),
  138. Protocol::NEWS => (-18),
  139. Protocol::ICALENDAR => (-19),
  140. Protocol::PNUT => (-20),
  141. Protocol::PHANTOM => (-127),
  142. ];
  143. /**
  144. * Maximum number of "people who like (or don't like) this" that we will list by name
  145. */
  146. define('MAX_LIKERS', 75);
  147. /**
  148. * @name Notify
  149. *
  150. * Email notification options
  151. * @{
  152. */
  153. define('NOTIFY_INTRO', 0x0001);
  154. define('NOTIFY_CONFIRM', 0x0002);
  155. define('NOTIFY_WALL', 0x0004);
  156. define('NOTIFY_COMMENT', 0x0008);
  157. define('NOTIFY_MAIL', 0x0010);
  158. define('NOTIFY_SUGGEST', 0x0020);
  159. define('NOTIFY_PROFILE', 0x0040);
  160. define('NOTIFY_TAGSELF', 0x0080);
  161. define('NOTIFY_TAGSHARE', 0x0100);
  162. define('NOTIFY_POKE', 0x0200);
  163. define('NOTIFY_SHARE', 0x0400);
  164. define('SYSTEM_EMAIL', 0x4000);
  165. define('NOTIFY_SYSTEM', 0x8000);
  166. /* @}*/
  167. /**
  168. * @name Term
  169. *
  170. * Tag/term types
  171. * @{
  172. */
  173. define('TERM_UNKNOWN', 0);
  174. define('TERM_HASHTAG', 1);
  175. define('TERM_MENTION', 2);
  176. define('TERM_CATEGORY', 3);
  177. define('TERM_PCATEGORY', 4);
  178. define('TERM_FILE', 5);
  179. define('TERM_SAVEDSEARCH', 6);
  180. define('TERM_CONVERSATION', 7);
  181. define('TERM_OBJ_POST', 1);
  182. define('TERM_OBJ_PHOTO', 2);
  183. /**
  184. * @name Namespaces
  185. *
  186. * Various namespaces we may need to parse
  187. * @{
  188. */
  189. define('NAMESPACE_ZOT', 'http://purl.org/zot');
  190. define('NAMESPACE_DFRN', 'http://purl.org/macgirvin/dfrn/1.0');
  191. define('NAMESPACE_THREAD', 'http://purl.org/syndication/thread/1.0');
  192. define('NAMESPACE_TOMB', 'http://purl.org/atompub/tombstones/1.0');
  193. define('NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/');
  194. define('NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
  195. define('NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia');
  196. define('NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env');
  197. define('NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe');
  198. define('NAMESPACE_GEORSS', 'http://www.georss.org/georss');
  199. define('NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0');
  200. define('NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from');
  201. define('NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0');
  202. define('NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/');
  203. define('NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom');
  204. define('NAMESPACE_MASTODON', 'http://mastodon.social/schema/1.0');
  205. /* @}*/
  206. /**
  207. * @name Activity
  208. *
  209. * Activity stream defines
  210. * @{
  211. */
  212. define('ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like');
  213. define('ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike');
  214. define('ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes');
  215. define('ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno');
  216. define('ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe');
  217. define('ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart');
  218. define('ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend');
  219. define('ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend');
  220. define('ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend');
  221. define('ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow');
  222. define('ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following');
  223. define('ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join');
  224. define('ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post');
  225. define('ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update');
  226. define('ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag');
  227. define('ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite');
  228. define('ACTIVITY_UNFAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'unfavorite');
  229. define('ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share');
  230. define('ACTIVITY_DELETE', NAMESPACE_ACTIVITY_SCHEMA . 'delete');
  231. define('ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke');
  232. define('ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark');
  233. define('ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment');
  234. define('ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note');
  235. define('ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person');
  236. define('ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image');
  237. define('ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo');
  238. define('ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video');
  239. define('ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo');
  240. define('ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album');
  241. define('ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event');
  242. define('ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group');
  243. define('ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm');
  244. define('ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile');
  245. define('ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question');
  246. /* @}*/
  247. /**
  248. * @name Gravity
  249. *
  250. * Item weight for query ordering
  251. * @{
  252. */
  253. define('GRAVITY_PARENT', 0);
  254. define('GRAVITY_ACTIVITY', 3);
  255. define('GRAVITY_COMMENT', 6);
  256. define('GRAVITY_UNKNOWN', 9);
  257. /* @}*/
  258. /**
  259. * @name Priority
  260. *
  261. * Process priority for the worker
  262. * @{
  263. */
  264. define('PRIORITY_UNDEFINED', 0);
  265. define('PRIORITY_CRITICAL', 10);
  266. define('PRIORITY_HIGH', 20);
  267. define('PRIORITY_MEDIUM', 30);
  268. define('PRIORITY_LOW', 40);
  269. define('PRIORITY_NEGLIGIBLE', 50);
  270. /* @}*/
  271. /**
  272. * @name Social Relay settings
  273. *
  274. * See here: https://github.com/jaywink/social-relay
  275. * and here: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
  276. * @{
  277. */
  278. define('SR_SCOPE_NONE', '');
  279. define('SR_SCOPE_ALL', 'all');
  280. define('SR_SCOPE_TAGS', 'tags');
  281. /* @}*/
  282. // Normally this constant is defined - but not if "pcntl" isn't installed
  283. if (!defined("SIGTERM")) {
  284. define("SIGTERM", 15);
  285. }
  286. /**
  287. * Depending on the PHP version this constant does exist - or not.
  288. * See here: http://php.net/manual/en/curl.constants.php#117928
  289. */
  290. if (!defined('CURLE_OPERATION_TIMEDOUT')) {
  291. define('CURLE_OPERATION_TIMEDOUT', CURLE_OPERATION_TIMEOUTED);
  292. }
  293. /**
  294. * @brief Retrieve the App structure
  295. *
  296. * Useful in functions which require it but don't get it passed to them
  297. *
  298. * @return App
  299. */
  300. function get_app()
  301. {
  302. return BaseObject::getApp();
  303. }
  304. /**
  305. * Return the provided variable value if it exists and is truthy or the provided
  306. * default value instead.
  307. *
  308. * Works with initialized variables and potentially uninitialized array keys
  309. *
  310. * Usages:
  311. * - defaults($var, $default)
  312. * - defaults($array, 'key', $default)
  313. *
  314. * @param array $args
  315. * @brief Returns a defaut value if the provided variable or array key is falsy
  316. * @return mixed
  317. */
  318. function defaults(...$args)
  319. {
  320. if (count($args) < 2) {
  321. throw new BadFunctionCallException('defaults() requires at least 2 parameters');
  322. }
  323. if (count($args) > 3) {
  324. throw new BadFunctionCallException('defaults() cannot use more than 3 parameters');
  325. }
  326. if (count($args) === 3 && is_null($args[1])) {
  327. throw new BadFunctionCallException('defaults($arr, $key, $def) $key is null');
  328. }
  329. // The default value always is the last argument
  330. $return = array_pop($args);
  331. if (count($args) == 2 && is_array($args[0]) && !empty($args[0][$args[1]])) {
  332. $return = $args[0][$args[1]];
  333. }
  334. if (count($args) == 1 && !empty($args[0])) {
  335. $return = $args[0];
  336. }
  337. return $return;
  338. }
  339. /**
  340. * @brief Used to end the current process, after saving session state.
  341. * @deprecated
  342. */
  343. function killme()
  344. {
  345. exit();
  346. }
  347. /**
  348. * @brief Returns the user id of locally logged in user or false.
  349. *
  350. * @return int|bool user id or false
  351. */
  352. function local_user()
  353. {
  354. if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) {
  355. return intval($_SESSION['uid']);
  356. }
  357. return false;
  358. }
  359. /**
  360. * @brief Returns the public contact id of logged in user or false.
  361. *
  362. * @return int|bool public contact id or false
  363. */
  364. function public_contact()
  365. {
  366. static $public_contact_id = false;
  367. if (!$public_contact_id && !empty($_SESSION['authenticated'])) {
  368. if (!empty($_SESSION['my_address'])) {
  369. // Local user
  370. $public_contact_id = intval(Contact::getIdForURL($_SESSION['my_address'], 0, true));
  371. } elseif (!empty($_SESSION['visitor_home'])) {
  372. // Remote user
  373. $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0, true));
  374. }
  375. } elseif (empty($_SESSION['authenticated'])) {
  376. $public_contact_id = false;
  377. }
  378. return $public_contact_id;
  379. }
  380. /**
  381. * @brief Returns contact id of authenticated site visitor or false
  382. *
  383. * @return int|bool visitor_id or false
  384. */
  385. function remote_user()
  386. {
  387. // You cannot be both local and remote.
  388. // Unncommented by rabuzarus because remote authentication to local
  389. // profiles wasn't possible anymore (2018-04-12).
  390. // if (local_user()) {
  391. // return false;
  392. // }
  393. if (empty($_SESSION)) {
  394. return false;
  395. }
  396. if (!empty($_SESSION['authenticated']) && !empty($_SESSION['visitor_id'])) {
  397. return intval($_SESSION['visitor_id']);
  398. }
  399. return false;
  400. }
  401. /**
  402. * @brief Show an error message to user.
  403. *
  404. * This function save text in session, to be shown to the user at next page load
  405. *
  406. * @param string $s - Text of notice
  407. */
  408. function notice($s)
  409. {
  410. if (empty($_SESSION)) {
  411. return;
  412. }
  413. $a = get_app();
  414. if (empty($_SESSION['sysmsg'])) {
  415. $_SESSION['sysmsg'] = [];
  416. }
  417. if ($a->interactive) {
  418. $_SESSION['sysmsg'][] = $s;
  419. }
  420. }
  421. /**
  422. * @brief Show an info message to user.
  423. *
  424. * This function save text in session, to be shown to the user at next page load
  425. *
  426. * @param string $s - Text of notice
  427. */
  428. function info($s)
  429. {
  430. $a = get_app();
  431. if (local_user() && PConfig::get(local_user(), 'system', 'ignore_info')) {
  432. return;
  433. }
  434. if (empty($_SESSION['sysmsg_info'])) {
  435. $_SESSION['sysmsg_info'] = [];
  436. }
  437. if ($a->interactive) {
  438. $_SESSION['sysmsg_info'][] = $s;
  439. }
  440. }
  441. function feed_birthday($uid, $tz)
  442. {
  443. /**
  444. * Determine the next birthday, but only if the birthday is published
  445. * in the default profile. We _could_ also look for a private profile that the
  446. * recipient can see, but somebody could get mad at us if they start getting
  447. * public birthday greetings when they haven't made this info public.
  448. *
  449. * Assuming we are able to publish this info, we are then going to convert
  450. * the start time from the owner's timezone to UTC.
  451. *
  452. * This will potentially solve the problem found with some social networks
  453. * where birthdays are converted to the viewer's timezone and salutations from
  454. * elsewhere in the world show up on the wrong day. We will convert it to the
  455. * viewer's timezone also, but first we are going to convert it from the birthday
  456. * person's timezone to GMT - so the viewer may find the birthday starting at
  457. * 6:00PM the day before, but that will correspond to midnight to the birthday person.
  458. */
  459. $birthday = '';
  460. if (!strlen($tz)) {
  461. $tz = 'UTC';
  462. }
  463. $profile = DBA::selectFirst('profile', ['dob'], ['is-default' => true, 'uid' => $uid]);
  464. if (DBA::isResult($profile)) {
  465. $tmp_dob = substr($profile['dob'], 5);
  466. if (intval($tmp_dob)) {
  467. $y = DateTimeFormat::timezoneNow($tz, 'Y');
  468. $bd = $y . '-' . $tmp_dob . ' 00:00';
  469. $t_dob = strtotime($bd);
  470. $now = strtotime(DateTimeFormat::timezoneNow($tz));
  471. if ($t_dob < $now) {
  472. $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
  473. }
  474. $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
  475. }
  476. }
  477. return $birthday;
  478. }
  479. /**
  480. * @brief Check if current user has admin role.
  481. *
  482. * @return bool true if user is an admin
  483. */
  484. function is_site_admin()
  485. {
  486. $a = get_app();
  487. $admin_email = Config::get('config', 'admin_email');
  488. $adminlist = explode(',', str_replace(' ', '', $admin_email));
  489. return local_user() && $admin_email && in_array(defaults($a->user, 'email', ''), $adminlist);
  490. }
  491. /**
  492. * @brief Returns querystring as string from a mapped array.
  493. *
  494. * @param array $params mapped array with query parameters
  495. * @param string $name of parameter, default null
  496. *
  497. * @return string
  498. */
  499. function build_querystring($params, $name = null)
  500. {
  501. $ret = "";
  502. foreach ($params as $key => $val) {
  503. if (is_array($val)) {
  504. /// @TODO maybe not compare against null, use is_null()
  505. if ($name == null) {
  506. $ret .= build_querystring($val, $key);
  507. } else {
  508. $ret .= build_querystring($val, $name . "[$key]");
  509. }
  510. } else {
  511. $val = urlencode($val);
  512. /// @TODO maybe not compare against null, use is_null()
  513. if ($name != null) {
  514. /// @TODO two string concated, can be merged to one
  515. $ret .= $name . "[$key]" . "=$val&";
  516. } else {
  517. $ret .= "$key=$val&";
  518. }
  519. }
  520. }
  521. return $ret;
  522. }
  523. function explode_querystring($query)
  524. {
  525. $arg_st = strpos($query, '?');
  526. if ($arg_st !== false) {
  527. $base = substr($query, 0, $arg_st);
  528. $arg_st += 1;
  529. } else {
  530. $base = '';
  531. $arg_st = 0;
  532. }
  533. $args = explode('&', substr($query, $arg_st));
  534. foreach ($args as $k => $arg) {
  535. /// @TODO really compare type-safe here?
  536. if ($arg === '') {
  537. unset($args[$k]);
  538. }
  539. }
  540. $args = array_values($args);
  541. if (!$base) {
  542. $base = $args[0];
  543. unset($args[0]);
  544. $args = array_values($args);
  545. }
  546. return [
  547. 'base' => $base,
  548. 'args' => $args,
  549. ];
  550. }
  551. /**
  552. * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
  553. *
  554. * Taken from http://webcheatsheet.com/php/get_current_page_url.php
  555. */
  556. function curPageURL()
  557. {
  558. $pageURL = 'http';
  559. if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
  560. $pageURL .= "s";
  561. }
  562. $pageURL .= "://";
  563. if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
  564. $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
  565. } else {
  566. $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
  567. }
  568. return $pageURL;
  569. }
  570. function get_server()
  571. {
  572. $server = Config::get("system", "directory");
  573. if ($server == "") {
  574. $server = "https://dir.friendica.social";
  575. }
  576. return $server;
  577. }
  578. function get_temppath()
  579. {
  580. $a = get_app();
  581. $temppath = Config::get("system", "temppath");
  582. if (($temppath != "") && App::isDirectoryUsable($temppath)) {
  583. // We have a temp path and it is usable
  584. return App::getRealPath($temppath);
  585. }
  586. // We don't have a working preconfigured temp path, so we take the system path.
  587. $temppath = sys_get_temp_dir();
  588. // Check if it is usable
  589. if (($temppath != "") && App::isDirectoryUsable($temppath)) {
  590. // Always store the real path, not the path through symlinks
  591. $temppath = App::getRealPath($temppath);
  592. // To avoid any interferences with other systems we create our own directory
  593. $new_temppath = $temppath . "/" . $a->getHostName();
  594. if (!is_dir($new_temppath)) {
  595. /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
  596. mkdir($new_temppath);
  597. }
  598. if (App::isDirectoryUsable($new_temppath)) {
  599. // The new path is usable, we are happy
  600. Config::set("system", "temppath", $new_temppath);
  601. return $new_temppath;
  602. } else {
  603. // We can't create a subdirectory, strange.
  604. // But the directory seems to work, so we use it but don't store it.
  605. return $temppath;
  606. }
  607. }
  608. // Reaching this point means that the operating system is configured badly.
  609. return '';
  610. }
  611. function get_cachefile($file, $writemode = true)
  612. {
  613. $cache = get_itemcachepath();
  614. if ((!$cache) || (!is_dir($cache))) {
  615. return "";
  616. }
  617. $subfolder = $cache . "/" . substr($file, 0, 2);
  618. $cachepath = $subfolder . "/" . $file;
  619. if ($writemode) {
  620. if (!is_dir($subfolder)) {
  621. mkdir($subfolder);
  622. chmod($subfolder, 0777);
  623. }
  624. }
  625. return $cachepath;
  626. }
  627. function clear_cache($basepath = "", $path = "")
  628. {
  629. if ($path == "") {
  630. $basepath = get_itemcachepath();
  631. $path = $basepath;
  632. }
  633. if (($path == "") || (!is_dir($path))) {
  634. return;
  635. }
  636. if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
  637. return;
  638. }
  639. $cachetime = (int) Config::get('system', 'itemcache_duration');
  640. if ($cachetime == 0) {
  641. $cachetime = 86400;
  642. }
  643. if (is_writable($path)) {
  644. if ($dh = opendir($path)) {
  645. while (($file = readdir($dh)) !== false) {
  646. $fullpath = $path . "/" . $file;
  647. if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
  648. clear_cache($basepath, $fullpath);
  649. }
  650. if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
  651. unlink($fullpath);
  652. }
  653. }
  654. closedir($dh);
  655. }
  656. }
  657. }
  658. function get_itemcachepath()
  659. {
  660. // Checking, if the cache is deactivated
  661. $cachetime = (int) Config::get('system', 'itemcache_duration');
  662. if ($cachetime < 0) {
  663. return "";
  664. }
  665. $itemcache = Config::get('system', 'itemcache');
  666. if (($itemcache != "") && App::isDirectoryUsable($itemcache)) {
  667. return App::getRealPath($itemcache);
  668. }
  669. $temppath = get_temppath();
  670. if ($temppath != "") {
  671. $itemcache = $temppath . "/itemcache";
  672. if (!file_exists($itemcache) && !is_dir($itemcache)) {
  673. mkdir($itemcache);
  674. }
  675. if (App::isDirectoryUsable($itemcache)) {
  676. Config::set("system", "itemcache", $itemcache);
  677. return $itemcache;
  678. }
  679. }
  680. return "";
  681. }
  682. /**
  683. * @brief Returns the path where spool files are stored
  684. *
  685. * @return string Spool path
  686. */
  687. function get_spoolpath()
  688. {
  689. $spoolpath = Config::get('system', 'spoolpath');
  690. if (($spoolpath != "") && App::isDirectoryUsable($spoolpath)) {
  691. // We have a spool path and it is usable
  692. return $spoolpath;
  693. }
  694. // We don't have a working preconfigured spool path, so we take the temp path.
  695. $temppath = get_temppath();
  696. if ($temppath != "") {
  697. // To avoid any interferences with other systems we create our own directory
  698. $spoolpath = $temppath . "/spool";
  699. if (!is_dir($spoolpath)) {
  700. mkdir($spoolpath);
  701. }
  702. if (App::isDirectoryUsable($spoolpath)) {
  703. // The new path is usable, we are happy
  704. Config::set("system", "spoolpath", $spoolpath);
  705. return $spoolpath;
  706. } else {
  707. // We can't create a subdirectory, strange.
  708. // But the directory seems to work, so we use it but don't store it.
  709. return $temppath;
  710. }
  711. }
  712. // Reaching this point means that the operating system is configured badly.
  713. return "";
  714. }
  715. if (!function_exists('exif_imagetype')) {
  716. function exif_imagetype($file)
  717. {
  718. $size = getimagesize($file);
  719. return $size[2];
  720. }
  721. }
  722. function validate_include(&$file)
  723. {
  724. $orig_file = $file;
  725. $file = realpath($file);
  726. if (strpos($file, getcwd()) !== 0) {
  727. return false;
  728. }
  729. $file = str_replace(getcwd() . "/", "", $file, $count);
  730. if ($count != 1) {
  731. return false;
  732. }
  733. if ($orig_file !== $file) {
  734. return false;
  735. }
  736. $valid = false;
  737. if (strpos($file, "include/") === 0) {
  738. $valid = true;
  739. }
  740. if (strpos($file, "addon/") === 0) {
  741. $valid = true;
  742. }
  743. // Simply return flag
  744. return $valid;
  745. }
  746. /**
  747. * PHP 5 compatible dirname() with count parameter
  748. *
  749. * @see http://php.net/manual/en/function.dirname.php#113193
  750. *
  751. * @deprecated with PHP 7
  752. * @param string $path
  753. * @param int $levels
  754. * @return string
  755. */
  756. function rdirname($path, $levels = 1)
  757. {
  758. if ($levels > 1) {
  759. return dirname(rdirname($path, --$levels));
  760. } else {
  761. return dirname($path);
  762. }
  763. }