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.
 
 
 
 
 
 

1578 lines
39 KiB

  1. <?php
  2. /** @file boot.php
  3. *
  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\Core\Addon;
  21. use Friendica\Core\System;
  22. use Friendica\Core\Cache;
  23. use Friendica\Core\Config;
  24. use Friendica\Core\PConfig;
  25. use Friendica\Core\Worker;
  26. use Friendica\Database\DBM;
  27. use Friendica\Model\Contact;
  28. use Friendica\Database\DBStructure;
  29. use Friendica\Module\Login;
  30. require_once 'include/network.php';
  31. require_once 'include/text.php';
  32. require_once 'include/datetime.php';
  33. require_once 'include/pgettext.php';
  34. define('FRIENDICA_PLATFORM', 'Friendica');
  35. define('FRIENDICA_CODENAME', 'Asparagus');
  36. define('FRIENDICA_VERSION', '3.6-dev');
  37. define('DFRN_PROTOCOL_VERSION', '2.23');
  38. define('DB_UPDATE_VERSION', 1247);
  39. define('NEW_UPDATE_ROUTINE_VERSION', 1170);
  40. /**
  41. * @brief Constants for the database update check
  42. */
  43. const DB_UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
  44. const DB_UPDATE_SUCCESSFUL = 1; // Database check was successful
  45. const DB_UPDATE_FAILED = 2; // Database check failed
  46. /**
  47. * @brief Constant with a HTML line break.
  48. *
  49. * Contains a HTML line break (br) element and a real carriage return with line
  50. * feed for the source.
  51. * This can be used in HTML and JavaScript where needed a line break.
  52. */
  53. define('EOL', "<br />\r\n");
  54. define('ATOM_TIME', 'Y-m-d\TH:i:s\Z');
  55. /**
  56. * @brief Image storage quality.
  57. *
  58. * Lower numbers save space at cost of image detail.
  59. * For ease of upgrade, please do not change here. Change jpeg quality with
  60. * $a->config['system']['jpeg_quality'] = n;
  61. * in .htconfig.php, where n is netween 1 and 100, and with very poor results
  62. * below about 50
  63. */
  64. define('JPEG_QUALITY', 100);
  65. /**
  66. * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
  67. */
  68. define('PNG_QUALITY', 8);
  69. /**
  70. * An alternate way of limiting picture upload sizes. Specify the maximum pixel
  71. * length that pictures are allowed to be (for non-square pictures, it will apply
  72. * to the longest side). Pictures longer than this length will be resized to be
  73. * this length (on the longest side, the other side will be scaled appropriately).
  74. * Modify this value using
  75. *
  76. * $a->config['system']['max_image_length'] = n;
  77. *
  78. * in .htconfig.php
  79. *
  80. * If you don't want to set a maximum length, set to -1. The default value is
  81. * defined by 'MAX_IMAGE_LENGTH' below.
  82. */
  83. define('MAX_IMAGE_LENGTH', -1);
  84. /**
  85. * Not yet used
  86. */
  87. define('DEFAULT_DB_ENGINE', 'InnoDB');
  88. /**
  89. * @name SSL Policy
  90. *
  91. * SSL redirection policies
  92. * @{
  93. */
  94. define('SSL_POLICY_NONE', 0);
  95. define('SSL_POLICY_FULL', 1);
  96. define('SSL_POLICY_SELFSIGN', 2);
  97. /* @}*/
  98. /**
  99. * @name Logger
  100. *
  101. * log levels
  102. * @{
  103. */
  104. define('LOGGER_NORMAL', 0);
  105. define('LOGGER_TRACE', 1);
  106. define('LOGGER_DEBUG', 2);
  107. define('LOGGER_DATA', 3);
  108. define('LOGGER_ALL', 4);
  109. /* @}*/
  110. /**
  111. * @name Cache
  112. *
  113. * Cache levels
  114. * @{
  115. */
  116. define('CACHE_MONTH', 0);
  117. define('CACHE_WEEK', 1);
  118. define('CACHE_DAY', 2);
  119. define('CACHE_HOUR', 3);
  120. define('CACHE_HALF_HOUR', 4);
  121. define('CACHE_QUARTER_HOUR', 5);
  122. define('CACHE_FIVE_MINUTES', 6);
  123. define('CACHE_MINUTE', 7);
  124. /* @}*/
  125. /**
  126. * @name Register
  127. *
  128. * Registration policies
  129. * @{
  130. */
  131. define('REGISTER_CLOSED', 0);
  132. define('REGISTER_APPROVE', 1);
  133. define('REGISTER_OPEN', 2);
  134. /**
  135. * @}
  136. */
  137. /**
  138. * @name Contact_is
  139. *
  140. * Relationship types
  141. * @{
  142. */
  143. define('CONTACT_IS_FOLLOWER', 1);
  144. define('CONTACT_IS_SHARING', 2);
  145. define('CONTACT_IS_FRIEND', 3);
  146. /**
  147. * @}
  148. */
  149. /**
  150. * @name Update
  151. *
  152. * DB update return values
  153. * @{
  154. */
  155. define('UPDATE_SUCCESS', 0);
  156. define('UPDATE_FAILED', 1);
  157. /**
  158. * @}
  159. */
  160. /**
  161. * @name page/profile types
  162. *
  163. * PAGE_NORMAL is a typical personal profile account
  164. * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
  165. * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
  166. * write access to wall and comments (no email and not included in page owner's ACL lists)
  167. * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
  168. *
  169. * @{
  170. */
  171. define('PAGE_NORMAL', 0);
  172. define('PAGE_SOAPBOX', 1);
  173. define('PAGE_COMMUNITY', 2);
  174. define('PAGE_FREELOVE', 3);
  175. define('PAGE_BLOG', 4);
  176. define('PAGE_PRVGROUP', 5);
  177. /**
  178. * @}
  179. */
  180. /**
  181. * @name account types
  182. *
  183. * ACCOUNT_TYPE_PERSON - the account belongs to a person
  184. * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
  185. *
  186. * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
  187. * Associated page type: PAGE_SOAPBOX
  188. *
  189. * ACCOUNT_TYPE_NEWS - the account is a news reflector
  190. * Associated page type: PAGE_SOAPBOX
  191. *
  192. * ACCOUNT_TYPE_COMMUNITY - the account is community forum
  193. * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
  194. * @{
  195. */
  196. define('ACCOUNT_TYPE_PERSON', 0);
  197. define('ACCOUNT_TYPE_ORGANISATION', 1);
  198. define('ACCOUNT_TYPE_NEWS', 2);
  199. define('ACCOUNT_TYPE_COMMUNITY', 3);
  200. /**
  201. * @}
  202. */
  203. /**
  204. * @name CP
  205. *
  206. * Type of the community page
  207. * @{
  208. */
  209. define('CP_NO_COMMUNITY_PAGE', -1);
  210. define('CP_USERS_ON_SERVER', 0);
  211. define('CP_GLOBAL_COMMUNITY', 1);
  212. define('CP_USERS_AND_GLOBAL', 2);
  213. /**
  214. * @}
  215. */
  216. /**
  217. * @name Protocols
  218. *
  219. * Different protocols that we are storing
  220. * @{
  221. */
  222. define('PROTOCOL_UNKNOWN', 0);
  223. define('PROTOCOL_DFRN', 1);
  224. define('PROTOCOL_DIASPORA', 2);
  225. define('PROTOCOL_OSTATUS_SALMON', 3);
  226. define('PROTOCOL_OSTATUS_FEED', 4); // Deprecated
  227. define('PROTOCOL_GS_CONVERSATION', 5); // Deprecated
  228. define('PROTOCOL_SPLITTED_CONV', 6);
  229. /**
  230. * @}
  231. */
  232. /**
  233. * @name Network
  234. *
  235. * Network and protocol family types
  236. * @{
  237. */
  238. define('NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
  239. define('NETWORK_ZOT', 'zot!'); // Zot! - Currently unsupported
  240. define('NETWORK_OSTATUS', 'stat'); // GNU-social, Pleroma, Mastodon, other OStatus implementations
  241. define('NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
  242. define('NETWORK_DIASPORA', 'dspr'); // Diaspora
  243. define('NETWORK_MAIL', 'mail'); // IMAP/POP
  244. define('NETWORK_FACEBOOK', 'face'); // Facebook API
  245. define('NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
  246. define('NETWORK_XMPP', 'xmpp'); // XMPP - Currently unsupported
  247. define('NETWORK_MYSPACE', 'mysp'); // MySpace - Currently unsupported
  248. define('NETWORK_GPLUS', 'goog'); // Google+
  249. define('NETWORK_PUMPIO', 'pump'); // pump.io
  250. define('NETWORK_TWITTER', 'twit'); // Twitter
  251. define('NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
  252. define('NETWORK_STATUSNET', 'stac'); // Statusnet connector
  253. define('NETWORK_APPNET', 'apdn'); // app.net - Dead protocol
  254. define('NETWORK_NEWS', 'nntp'); // Network News Transfer Protocol - Currently unsupported
  255. define('NETWORK_ICALENDAR', 'ical'); // iCalendar - Currently unsupported
  256. define('NETWORK_PNUT', 'pnut'); // pnut.io - Currently unsupported
  257. define('NETWORK_PHANTOM', 'unkn'); // Place holder
  258. /**
  259. * @}
  260. */
  261. /**
  262. * These numbers are used in stored permissions
  263. * and existing allocations MUST NEVER BE CHANGED
  264. * OR RE-ASSIGNED! You may only add to them.
  265. */
  266. $netgroup_ids = [
  267. NETWORK_DFRN => (-1),
  268. NETWORK_ZOT => (-2),
  269. NETWORK_OSTATUS => (-3),
  270. NETWORK_FEED => (-4),
  271. NETWORK_DIASPORA => (-5),
  272. NETWORK_MAIL => (-6),
  273. NETWORK_FACEBOOK => (-8),
  274. NETWORK_LINKEDIN => (-9),
  275. NETWORK_XMPP => (-10),
  276. NETWORK_MYSPACE => (-11),
  277. NETWORK_GPLUS => (-12),
  278. NETWORK_PUMPIO => (-13),
  279. NETWORK_TWITTER => (-14),
  280. NETWORK_DIASPORA2 => (-15),
  281. NETWORK_STATUSNET => (-16),
  282. NETWORK_APPNET => (-17),
  283. NETWORK_NEWS => (-18),
  284. NETWORK_ICALENDAR => (-19),
  285. NETWORK_PNUT => (-20),
  286. NETWORK_PHANTOM => (-127),
  287. ];
  288. /**
  289. * Maximum number of "people who like (or don't like) this" that we will list by name
  290. */
  291. define('MAX_LIKERS', 75);
  292. /**
  293. * Communication timeout
  294. */
  295. define('ZCURL_TIMEOUT', (-1));
  296. /**
  297. * @name Notify
  298. *
  299. * Email notification options
  300. * @{
  301. */
  302. define('NOTIFY_INTRO', 0x0001);
  303. define('NOTIFY_CONFIRM', 0x0002);
  304. define('NOTIFY_WALL', 0x0004);
  305. define('NOTIFY_COMMENT', 0x0008);
  306. define('NOTIFY_MAIL', 0x0010);
  307. define('NOTIFY_SUGGEST', 0x0020);
  308. define('NOTIFY_PROFILE', 0x0040);
  309. define('NOTIFY_TAGSELF', 0x0080);
  310. define('NOTIFY_TAGSHARE', 0x0100);
  311. define('NOTIFY_POKE', 0x0200);
  312. define('NOTIFY_SHARE', 0x0400);
  313. define('SYSTEM_EMAIL', 0x4000);
  314. define('NOTIFY_SYSTEM', 0x8000);
  315. /* @}*/
  316. /**
  317. * @name Term
  318. *
  319. * Tag/term types
  320. * @{
  321. */
  322. define('TERM_UNKNOWN', 0);
  323. define('TERM_HASHTAG', 1);
  324. define('TERM_MENTION', 2);
  325. define('TERM_CATEGORY', 3);
  326. define('TERM_PCATEGORY', 4);
  327. define('TERM_FILE', 5);
  328. define('TERM_SAVEDSEARCH', 6);
  329. define('TERM_CONVERSATION', 7);
  330. define('TERM_OBJ_POST', 1);
  331. define('TERM_OBJ_PHOTO', 2);
  332. /**
  333. * @name Namespaces
  334. *
  335. * Various namespaces we may need to parse
  336. * @{
  337. */
  338. define('NAMESPACE_ZOT', 'http://purl.org/zot');
  339. define('NAMESPACE_DFRN', 'http://purl.org/macgirvin/dfrn/1.0');
  340. define('NAMESPACE_THREAD', 'http://purl.org/syndication/thread/1.0');
  341. define('NAMESPACE_TOMB', 'http://purl.org/atompub/tombstones/1.0');
  342. define('NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/');
  343. define('NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
  344. define('NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia');
  345. define('NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env');
  346. define('NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe');
  347. define('NAMESPACE_GEORSS', 'http://www.georss.org/georss');
  348. define('NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0');
  349. define('NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from');
  350. define('NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0');
  351. define('NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/');
  352. define('NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom');
  353. define('NAMESPACE_MASTODON', 'http://mastodon.social/schema/1.0');
  354. /* @}*/
  355. /**
  356. * @name Activity
  357. *
  358. * Activity stream defines
  359. * @{
  360. */
  361. define('ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like');
  362. define('ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike');
  363. define('ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes');
  364. define('ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno');
  365. define('ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe');
  366. define('ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart');
  367. define('ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend');
  368. define('ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend');
  369. define('ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend');
  370. define('ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow');
  371. define('ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following');
  372. define('ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join');
  373. define('ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post');
  374. define('ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update');
  375. define('ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag');
  376. define('ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite');
  377. define('ACTIVITY_UNFAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'unfavorite');
  378. define('ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share');
  379. define('ACTIVITY_DELETE', NAMESPACE_ACTIVITY_SCHEMA . 'delete');
  380. define('ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke');
  381. define('ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark');
  382. define('ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment');
  383. define('ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note');
  384. define('ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person');
  385. define('ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image');
  386. define('ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo');
  387. define('ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video');
  388. define('ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo');
  389. define('ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album');
  390. define('ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event');
  391. define('ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group');
  392. define('ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm');
  393. define('ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile');
  394. define('ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question');
  395. /* @}*/
  396. /**
  397. * @name Gravity
  398. *
  399. * Item weight for query ordering
  400. * @{
  401. */
  402. define('GRAVITY_PARENT', 0);
  403. define('GRAVITY_LIKE', 3);
  404. define('GRAVITY_COMMENT', 6);
  405. /* @}*/
  406. /**
  407. * @name Priority
  408. *
  409. * Process priority for the worker
  410. * @{
  411. */
  412. define('PRIORITY_UNDEFINED', 0);
  413. define('PRIORITY_CRITICAL', 10);
  414. define('PRIORITY_HIGH', 20);
  415. define('PRIORITY_MEDIUM', 30);
  416. define('PRIORITY_LOW', 40);
  417. define('PRIORITY_NEGLIGIBLE', 50);
  418. /* @}*/
  419. /**
  420. * @name Social Relay settings
  421. *
  422. * See here: https://github.com/jaywink/social-relay
  423. * and here: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
  424. * @{
  425. */
  426. define('SR_SCOPE_NONE', '');
  427. define('SR_SCOPE_ALL', 'all');
  428. define('SR_SCOPE_TAGS', 'tags');
  429. /* @}*/
  430. /**
  431. * Lowest possible date time value
  432. */
  433. define('NULL_DATE', '0001-01-01 00:00:00');
  434. // Normally this constant is defined - but not if "pcntl" isn't installed
  435. if (!defined("SIGTERM")) {
  436. define("SIGTERM", 15);
  437. }
  438. /**
  439. * Depending on the PHP version this constant does exist - or not.
  440. * See here: http://php.net/manual/en/curl.constants.php#117928
  441. */
  442. if (!defined('CURLE_OPERATION_TIMEDOUT')) {
  443. define('CURLE_OPERATION_TIMEDOUT', CURLE_OPERATION_TIMEOUTED);
  444. }
  445. /**
  446. * Reverse the effect of magic_quotes_gpc if it is enabled.
  447. * Please disable magic_quotes_gpc so we don't have to do this.
  448. * See http://php.net/manual/en/security.magicquotes.disabling.php
  449. */
  450. function startup()
  451. {
  452. error_reporting(E_ERROR | E_WARNING | E_PARSE);
  453. set_time_limit(0);
  454. // This has to be quite large to deal with embedded private photos
  455. ini_set('pcre.backtrack_limit', 500000);
  456. if (get_magic_quotes_gpc()) {
  457. $process = [&$_GET, &$_POST, &$_COOKIE, &$_REQUEST];
  458. while (list($key, $val) = each($process)) {
  459. foreach ($val as $k => $v) {
  460. unset($process[$key][$k]);
  461. if (is_array($v)) {
  462. $process[$key][stripslashes($k)] = $v;
  463. $process[] = &$process[$key][stripslashes($k)];
  464. } else {
  465. $process[$key][stripslashes($k)] = stripslashes($v);
  466. }
  467. }
  468. }
  469. unset($process);
  470. }
  471. }
  472. /**
  473. * @brief Retrieve the App structure
  474. *
  475. * Useful in functions which require it but don't get it passed to them
  476. *
  477. * @return App
  478. */
  479. function get_app()
  480. {
  481. global $a;
  482. if (empty($a)) {
  483. $a = new App(dirname(__DIR__));
  484. }
  485. return $a;
  486. }
  487. /**
  488. * @brief Multi-purpose function to check variable state.
  489. *
  490. * Usage: x($var) or $x($array, 'key')
  491. *
  492. * returns false if variable/key is not set
  493. * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
  494. * e.g. x('') or x(0) returns 0;
  495. *
  496. * @param string|array $s variable to check
  497. * @param string $k key inside the array to check
  498. *
  499. * @return bool|int
  500. */
  501. function x($s, $k = null)
  502. {
  503. if ($k != null) {
  504. if ((is_array($s)) && (array_key_exists($k, $s))) {
  505. if ($s[$k]) {
  506. return (int) 1;
  507. }
  508. return (int) 0;
  509. }
  510. return false;
  511. } else {
  512. if (isset($s)) {
  513. if ($s) {
  514. return (int) 1;
  515. }
  516. return (int) 0;
  517. }
  518. return false;
  519. }
  520. }
  521. /**
  522. * Return the provided variable value if it exists and is truthy or the provided
  523. * default value instead.
  524. *
  525. * Works with initialized variables and potentially uninitialized array keys
  526. *
  527. * Usages:
  528. * - defaults($var, $default)
  529. * - defaults($array, 'key', $default)
  530. *
  531. * @brief Returns a defaut value if the provided variable or array key is falsy
  532. * @see x()
  533. * @return mixed
  534. */
  535. function defaults() {
  536. $args = func_get_args();
  537. if (count($args) < 2) {
  538. throw new BadFunctionCallException('defaults() requires at least 2 parameters');
  539. }
  540. if (count($args) > 3) {
  541. throw new BadFunctionCallException('defaults() cannot use more than 3 parameters');
  542. }
  543. if (count($args) === 3 && is_null($args[1])) {
  544. throw new BadFunctionCallException('defaults($arr, $key, $def) $key is null');
  545. }
  546. $default = array_pop($args);
  547. if (call_user_func_array('x', $args)) {
  548. if (count($args) === 1) {
  549. $return = $args[0];
  550. } else {
  551. $return = $args[0][$args[1]];
  552. }
  553. } else {
  554. $return = $default;
  555. }
  556. return $return;
  557. }
  558. /**
  559. * @brief Returns the baseurl.
  560. *
  561. * @see System::baseUrl()
  562. *
  563. * @return string
  564. * @TODO Function is deprecated and only used in some addons
  565. */
  566. function z_root()
  567. {
  568. return System::baseUrl();
  569. }
  570. /**
  571. * @brief Return absolut URL for given $path.
  572. *
  573. * @param string $path given path
  574. *
  575. * @return string
  576. */
  577. function absurl($path)
  578. {
  579. if (strpos($path, '/') === 0) {
  580. return z_path() . $path;
  581. }
  582. return $path;
  583. }
  584. /**
  585. * @brief Function to check if request was an AJAX (xmlhttprequest) request.
  586. *
  587. * @return boolean
  588. */
  589. function is_ajax()
  590. {
  591. return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
  592. }
  593. /**
  594. * @brief Function to check if request was an AJAX (xmlhttprequest) request.
  595. *
  596. * @param boolean $via_worker boolean Is the check run via the worker?
  597. */
  598. function check_db($via_worker)
  599. {
  600. $build = Config::get('system', 'build');
  601. if (empty($build)) {
  602. Config::set('system', 'build', DB_UPDATE_VERSION - 1);
  603. $build = DB_UPDATE_VERSION;
  604. }
  605. // We don't support upgrading from very old versions anymore
  606. if ($build < NEW_UPDATE_ROUTINE_VERSION) {
  607. die('You try to update from a version prior to database version 1170. The direct upgrade path is not supported. Please update to version 3.5.4 before updating to this version.');
  608. }
  609. if ($build != DB_UPDATE_VERSION) {
  610. // When we cannot execute the database update via the worker, we will do it directly
  611. if (!Worker::add(PRIORITY_CRITICAL, 'DBUpdate') && $via_worker) {
  612. update_db();
  613. }
  614. }
  615. }
  616. /**
  617. * Sets the base url for use in cmdline programs which don't have
  618. * $_SERVER variables
  619. *
  620. * @param object $a App
  621. */
  622. function check_url(App $a)
  623. {
  624. $url = Config::get('system', 'url');
  625. // if the url isn't set or the stored url is radically different
  626. // than the currently visited url, store the current value accordingly.
  627. // "Radically different" ignores common variations such as http vs https
  628. // and www.example.com vs example.com.
  629. // We will only change the url to an ip address if there is no existing setting
  630. if (empty($url) || (!link_compare($url, System::baseUrl())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $a->get_hostname))) {
  631. Config::set('system', 'url', System::baseUrl());
  632. }
  633. return;
  634. }
  635. /**
  636. * @brief Automatic database updates
  637. * @param object $a App
  638. */
  639. function update_db()
  640. {
  641. $build = Config::get('system', 'build');
  642. if (empty($build) || ($build > DB_UPDATE_VERSION)) {
  643. $build = DB_UPDATE_VERSION - 1;
  644. Config::set('system', 'build', $build);
  645. }
  646. if ($build != DB_UPDATE_VERSION) {
  647. require_once 'update.php';
  648. $stored = intval($build);
  649. $current = intval(DB_UPDATE_VERSION);
  650. if ($stored < $current) {
  651. Config::load('database');
  652. // Compare the current structure with the defined structure
  653. $t = Config::get('database', 'dbupdate_' . DB_UPDATE_VERSION);
  654. if (!is_null($t)) {
  655. return;
  656. }
  657. Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, time());
  658. // run update routine
  659. // it update the structure in one call
  660. $retval = DBStructure::update(false, true);
  661. if ($retval) {
  662. DBStructure::updateFail(
  663. DB_UPDATE_VERSION,
  664. $retval
  665. );
  666. return;
  667. } else {
  668. Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, 'success');
  669. }
  670. // run any left update_nnnn functions in update.php
  671. for ($x = $stored + 1; $x <= $current; $x++) {
  672. $r = run_update_function($x);
  673. if (!$r) {
  674. break;
  675. }
  676. }
  677. }
  678. }
  679. return;
  680. }
  681. function run_update_function($x)
  682. {
  683. if (function_exists('update_' . $x)) {
  684. // There could be a lot of processes running or about to run.
  685. // We want exactly one process to run the update command.
  686. // So store the fact that we're taking responsibility
  687. // after first checking to see if somebody else already has.
  688. // If the update fails or times-out completely you may need to
  689. // delete the config entry to try again.
  690. $t = Config::get('database', 'update_' . $x);
  691. if (!is_null($t)) {
  692. return false;
  693. }
  694. Config::set('database', 'update_' . $x, time());
  695. // call the specific update
  696. $func = 'update_' . $x;
  697. $retval = $func();
  698. if ($retval) {
  699. //send the administrator an e-mail
  700. DBStructure::updateFail(
  701. $x,
  702. sprintf(t('Update %s failed. See error logs.'), $x)
  703. );
  704. return false;
  705. } else {
  706. Config::set('database', 'update_' . $x, 'success');
  707. Config::set('system', 'build', $x);
  708. return true;
  709. }
  710. } else {
  711. Config::set('database', 'update_' . $x, 'success');
  712. Config::set('system', 'build', $x);
  713. return true;
  714. }
  715. }
  716. /**
  717. * @brief Synchronise addons:
  718. *
  719. * $a->config['system']['addon'] contains a comma-separated list of names
  720. * of addons which are used on this system.
  721. * Go through the database list of already installed addons, and if we have
  722. * an entry, but it isn't in the config list, call the uninstall procedure
  723. * and mark it uninstalled in the database (for now we'll remove it).
  724. * Then go through the config list and if we have a addon that isn't installed,
  725. * call the install procedure and add it to the database.
  726. *
  727. * @param object $a App
  728. */
  729. function check_addons(App $a)
  730. {
  731. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  732. if (DBM::is_result($r)) {
  733. $installed = $r;
  734. } else {
  735. $installed = [];
  736. }
  737. $addons = Config::get('system', 'addon');
  738. $addons_arr = [];
  739. if ($addons) {
  740. $addons_arr = explode(',', str_replace(' ', '', $addons));
  741. }
  742. $a->addons = $addons_arr;
  743. $installed_arr = [];
  744. if (count($installed)) {
  745. foreach ($installed as $i) {
  746. if (!in_array($i['name'], $addons_arr)) {
  747. Addon::uninstall($i['name']);
  748. } else {
  749. $installed_arr[] = $i['name'];
  750. }
  751. }
  752. }
  753. if (count($addons_arr)) {
  754. foreach ($addons_arr as $p) {
  755. if (!in_array($p, $installed_arr)) {
  756. Addon::install($p);
  757. }
  758. }
  759. }
  760. Addon::loadHooks();
  761. return;
  762. }
  763. function get_guid($size = 16, $prefix = "")
  764. {
  765. if ($prefix == "") {
  766. $a = get_app();
  767. $prefix = hash("crc32", $a->get_hostname());
  768. }
  769. while (strlen($prefix) < ($size - 13)) {
  770. $prefix .= mt_rand();
  771. }
  772. if ($size >= 24) {
  773. $prefix = substr($prefix, 0, $size - 22);
  774. return(str_replace(".", "", uniqid($prefix, true)));
  775. } else {
  776. $prefix = substr($prefix, 0, max($size - 13, 0));
  777. return(uniqid($prefix));
  778. }
  779. }
  780. /**
  781. * @brief Used to end the current process, after saving session state.
  782. */
  783. function killme()
  784. {
  785. if (!get_app()->is_backend()) {
  786. session_write_close();
  787. }
  788. exit();
  789. }
  790. /**
  791. * @brief Redirect to another URL and terminate this process.
  792. */
  793. function goaway($path)
  794. {
  795. if (strstr(normalise_link($path), 'http://')) {
  796. $url = $path;
  797. } else {
  798. $url = System::baseUrl() . '/' . ltrim($path, '/');
  799. }
  800. header("Location: $url");
  801. killme();
  802. }
  803. /**
  804. * @brief Returns the user id of locally logged in user or false.
  805. *
  806. * @return int|bool user id or false
  807. */
  808. function local_user()
  809. {
  810. if (x($_SESSION, 'authenticated') && x($_SESSION, 'uid')) {
  811. return intval($_SESSION['uid']);
  812. }
  813. return false;
  814. }
  815. /**
  816. * @brief Returns the public contact id of logged in user or false.
  817. *
  818. * @return int|bool public contact id or false
  819. */
  820. function public_contact()
  821. {
  822. static $public_contact_id = false;
  823. if (!$public_contact_id && x($_SESSION, 'authenticated')) {
  824. if (x($_SESSION, 'my_address')) {
  825. // Local user
  826. $public_contact_id = intval(Contact::getIdForURL($_SESSION['my_address'], 0));
  827. } elseif (x($_SESSION, 'visitor_home')) {
  828. // Remote user
  829. $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0));
  830. }
  831. } elseif (!x($_SESSION, 'authenticated')) {
  832. $public_contact_id = false;
  833. }
  834. return $public_contact_id;
  835. }
  836. /**
  837. * @brief Returns contact id of authenticated site visitor or false
  838. *
  839. * @return int|bool visitor_id or false
  840. */
  841. function remote_user()
  842. {
  843. // You cannot be both local and remote
  844. if (local_user()) {
  845. return false;
  846. }
  847. if (x($_SESSION, 'authenticated') && x($_SESSION, 'visitor_id')) {
  848. return intval($_SESSION['visitor_id']);
  849. }
  850. return false;
  851. }
  852. /**
  853. * @brief Show an error message to user.
  854. *
  855. * This function save text in session, to be shown to the user at next page load
  856. *
  857. * @param string $s - Text of notice
  858. */
  859. function notice($s)
  860. {
  861. $a = get_app();
  862. if (!x($_SESSION, 'sysmsg')) {
  863. $_SESSION['sysmsg'] = [];
  864. }
  865. if ($a->interactive) {
  866. $_SESSION['sysmsg'][] = $s;
  867. }
  868. }
  869. /**
  870. * @brief Show an info message to user.
  871. *
  872. * This function save text in session, to be shown to the user at next page load
  873. *
  874. * @param string $s - Text of notice
  875. */
  876. function info($s)
  877. {
  878. $a = get_app();
  879. if (local_user() && PConfig::get(local_user(), 'system', 'ignore_info')) {
  880. return;
  881. }
  882. if (!x($_SESSION, 'sysmsg_info')) {
  883. $_SESSION['sysmsg_info'] = [];
  884. }
  885. if ($a->interactive) {
  886. $_SESSION['sysmsg_info'][] = $s;
  887. }
  888. }
  889. /**
  890. * @brief Wrapper around config to limit the text length of an incoming message
  891. *
  892. * @return int
  893. */
  894. function get_max_import_size()
  895. {
  896. $a = get_app();
  897. return (x($a->config, 'max_import_size') ? $a->config['max_import_size'] : 0);
  898. }
  899. function current_theme()
  900. {
  901. $app_base_themes = ['duepuntozero', 'dispy', 'quattro'];
  902. $a = get_app();
  903. $page_theme = null;
  904. // Find the theme that belongs to the user whose stuff we are looking at
  905. if ($a->profile_uid && ($a->profile_uid != local_user())) {
  906. $r = q(
  907. "select theme from user where uid = %d limit 1",
  908. intval($a->profile_uid)
  909. );
  910. if (DBM::is_result($r)) {
  911. $page_theme = $r[0]['theme'];
  912. }
  913. }
  914. // Allow folks to over-rule user themes and always use their own on their own site.
  915. // This works only if the user is on the same server
  916. if ($page_theme && local_user() && (local_user() != $a->profile_uid)) {
  917. if (PConfig::get(local_user(), 'system', 'always_my_theme')) {
  918. $page_theme = null;
  919. }
  920. }
  921. // $mobile_detect = new Mobile_Detect();
  922. // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
  923. $is_mobile = $a->is_mobile || $a->is_tablet;
  924. $standard_system_theme = Config::get('system', 'theme', '');
  925. $standard_theme_name = ((isset($_SESSION) && x($_SESSION, 'theme')) ? $_SESSION['theme'] : $standard_system_theme);
  926. if ($is_mobile) {
  927. if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  928. $theme_name = $standard_theme_name;
  929. } else {
  930. $system_theme = Config::get('system', 'mobile-theme', '');
  931. if ($system_theme == '') {
  932. $system_theme = $standard_system_theme;
  933. }
  934. $theme_name = ((isset($_SESSION) && x($_SESSION, 'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
  935. if ($theme_name === '---') {
  936. // user has selected to have the mobile theme be the same as the normal one
  937. $theme_name = $standard_theme_name;
  938. if ($page_theme) {
  939. $theme_name = $page_theme;
  940. }
  941. }
  942. }
  943. } else {
  944. $theme_name = $standard_theme_name;
  945. if ($page_theme) {
  946. $theme_name = $page_theme;
  947. }
  948. }
  949. if ($theme_name
  950. && (file_exists('view/theme/' . $theme_name . '/style.css')
  951. || file_exists('view/theme/' . $theme_name . '/style.php'))
  952. ) {
  953. return($theme_name);
  954. }
  955. foreach ($app_base_themes as $t) {
  956. if (file_exists('view/theme/' . $t . '/style.css')
  957. || file_exists('view/theme/' . $t . '/style.php')
  958. ) {
  959. return($t);
  960. }
  961. }
  962. $fallback = array_merge(glob('view/theme/*/style.css'), glob('view/theme/*/style.php'));
  963. if (count($fallback)) {
  964. return (str_replace('view/theme/', '', substr($fallback[0], 0, -10)));
  965. }
  966. /// @TODO No final return statement?
  967. }
  968. /**
  969. * @brief Return full URL to theme which is currently in effect.
  970. *
  971. * Provide a sane default if nothing is chosen or the specified theme does not exist.
  972. *
  973. * @return string
  974. */
  975. function current_theme_url()
  976. {
  977. $a = get_app();
  978. $t = current_theme();
  979. $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
  980. if (file_exists('view/theme/' . $t . '/style.php')) {
  981. return('view/theme/' . $t . '/style.pcss' . $opts);
  982. }
  983. return('view/theme/' . $t . '/style.css');
  984. }
  985. function feed_birthday($uid, $tz)
  986. {
  987. /**
  988. * Determine the next birthday, but only if the birthday is published
  989. * in the default profile. We _could_ also look for a private profile that the
  990. * recipient can see, but somebody could get mad at us if they start getting
  991. * public birthday greetings when they haven't made this info public.
  992. *
  993. * Assuming we are able to publish this info, we are then going to convert
  994. * the start time from the owner's timezone to UTC.
  995. *
  996. * This will potentially solve the problem found with some social networks
  997. * where birthdays are converted to the viewer's timezone and salutations from
  998. * elsewhere in the world show up on the wrong day. We will convert it to the
  999. * viewer's timezone also, but first we are going to convert it from the birthday
  1000. * person's timezone to GMT - so the viewer may find the birthday starting at
  1001. * 6:00PM the day before, but that will correspond to midnight to the birthday person.
  1002. */
  1003. $birthday = '';
  1004. if (!strlen($tz)) {
  1005. $tz = 'UTC';
  1006. }
  1007. $p = q(
  1008. "SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
  1009. intval($uid)
  1010. );
  1011. if (DBM::is_result($p)) {
  1012. $tmp_dob = substr($p[0]['dob'], 5);
  1013. if (intval($tmp_dob)) {
  1014. $y = datetime_convert($tz, $tz, 'now', 'Y');
  1015. $bd = $y . '-' . $tmp_dob . ' 00:00';
  1016. $t_dob = strtotime($bd);
  1017. $now = strtotime(datetime_convert($tz, $tz, 'now'));
  1018. if ($t_dob < $now) {
  1019. $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
  1020. }
  1021. $birthday = datetime_convert($tz, 'UTC', $bd, ATOM_TIME);
  1022. }
  1023. }
  1024. return $birthday;
  1025. }
  1026. /**
  1027. * @brief Check if current user has admin role.
  1028. *
  1029. * @return bool true if user is an admin
  1030. */
  1031. function is_site_admin()
  1032. {
  1033. $a = get_app();
  1034. $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
  1035. //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
  1036. if (local_user() && x($a->user, 'email') && x($a->config, 'admin_email') && in_array($a->user['email'], $adminlist)) {
  1037. return true;
  1038. }
  1039. return false;
  1040. }
  1041. /**
  1042. * @brief Returns querystring as string from a mapped array.
  1043. *
  1044. * @param array $params mapped array with query parameters
  1045. * @param string $name of parameter, default null
  1046. *
  1047. * @return string
  1048. */
  1049. function build_querystring($params, $name = null)
  1050. {
  1051. $ret = "";
  1052. foreach ($params as $key => $val) {
  1053. if (is_array($val)) {
  1054. /// @TODO maybe not compare against null, use is_null()
  1055. if ($name == null) {
  1056. $ret .= build_querystring($val, $key);
  1057. } else {
  1058. $ret .= build_querystring($val, $name . "[$key]");
  1059. }
  1060. } else {
  1061. $val = urlencode($val);
  1062. /// @TODO maybe not compare against null, use is_null()
  1063. if ($name != null) {
  1064. /// @TODO two string concated, can be merged to one
  1065. $ret .= $name . "[$key]" . "=$val&";
  1066. } else {
  1067. $ret .= "$key=$val&";
  1068. }
  1069. }
  1070. }
  1071. return $ret;
  1072. }
  1073. function explode_querystring($query)
  1074. {
  1075. $arg_st = strpos($query, '?');
  1076. if ($arg_st !== false) {
  1077. $base = substr($query, 0, $arg_st);
  1078. $arg_st += 1;
  1079. } else {
  1080. $base = '';
  1081. $arg_st = 0;
  1082. }
  1083. $args = explode('&', substr($query, $arg_st));
  1084. foreach ($args as $k => $arg) {
  1085. /// @TODO really compare type-safe here?
  1086. if ($arg === '') {
  1087. unset($args[$k]);
  1088. }
  1089. }
  1090. $args = array_values($args);
  1091. if (!$base) {
  1092. $base = $args[0];
  1093. unset($args[0]);
  1094. $args = array_values($args);
  1095. }
  1096. return [
  1097. 'base' => $base,
  1098. 'args' => $args,
  1099. ];
  1100. }
  1101. /**
  1102. * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
  1103. *
  1104. * Taken from http://webcheatsheet.com/php/get_current_page_url.php
  1105. */
  1106. function curPageURL()
  1107. {
  1108. $pageURL = 'http';
  1109. if ($_SERVER["HTTPS"] == "on") {
  1110. $pageURL .= "s";
  1111. }
  1112. $pageURL .= "://";
  1113. if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
  1114. $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
  1115. } else {
  1116. $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
  1117. }
  1118. return $pageURL;
  1119. }
  1120. function random_digits($digits)
  1121. {
  1122. $rn = '';
  1123. for ($i = 0; $i < $digits; $i++) {
  1124. /// @TODO rand() is different to mt_rand() and maybe lesser "random"
  1125. $rn .= rand(0, 9);
  1126. }
  1127. return $rn;
  1128. }
  1129. function get_server()
  1130. {
  1131. $server = Config::get("system", "directory");
  1132. if ($server == "") {
  1133. $server = "http://dir.friendica.social";
  1134. }
  1135. return($server);
  1136. }
  1137. function get_temppath()
  1138. {
  1139. $a = get_app();
  1140. $temppath = Config::get("system", "temppath");
  1141. if (($temppath != "") && App::directory_usable($temppath)) {
  1142. // We have a temp path and it is usable
  1143. return App::realpath($temppath);
  1144. }
  1145. // We don't have a working preconfigured temp path, so we take the system path.
  1146. $temppath = sys_get_temp_dir();
  1147. // Check if it is usable
  1148. if (($temppath != "") && App::directory_usable($temppath)) {
  1149. // Always store the real path, not the path through symlinks
  1150. $temppath = App::realpath($temppath);
  1151. // To avoid any interferences with other systems we create our own directory
  1152. $new_temppath = $temppath . "/" . $a->get_hostname();
  1153. if (!is_dir($new_temppath)) {
  1154. /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
  1155. mkdir($new_temppath);
  1156. }
  1157. if (App::directory_usable($new_temppath)) {
  1158. // The new path is usable, we are happy
  1159. Config::set("system", "temppath", $new_temppath);
  1160. return $new_temppath;
  1161. } else {
  1162. // We can't create a subdirectory, strange.
  1163. // But the directory seems to work, so we use it but don't store it.
  1164. return $temppath;
  1165. }
  1166. }
  1167. // Reaching this point means that the operating system is configured badly.
  1168. return '';
  1169. }
  1170. function get_cachefile($file, $writemode = true)
  1171. {
  1172. $cache = get_itemcachepath();
  1173. if ((!$cache) || (!is_dir($cache))) {
  1174. return("");
  1175. }
  1176. $subfolder = $cache . "/" . substr($file, 0, 2);
  1177. $cachepath = $subfolder . "/" . $file;
  1178. if ($writemode) {
  1179. if (!is_dir($subfolder)) {
  1180. mkdir($subfolder);
  1181. chmod($subfolder, 0777);
  1182. }
  1183. }
  1184. /// @TODO no need to put braces here
  1185. return $cachepath;
  1186. }
  1187. function clear_cache($basepath = "", $path = "")
  1188. {
  1189. if ($path == "") {
  1190. $basepath = get_itemcachepath();
  1191. $path = $basepath;
  1192. }
  1193. if (($path == "") || (!is_dir($path))) {
  1194. return;
  1195. }
  1196. if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
  1197. return;
  1198. }
  1199. $cachetime = (int) Config::get('system', 'itemcache_duration');
  1200. if ($cachetime == 0) {
  1201. $cachetime = 86400;
  1202. }
  1203. if (is_writable($path)) {
  1204. if ($dh = opendir($path)) {
  1205. while (($file = readdir($dh)) !== false) {
  1206. $fullpath = $path . "/" . $file;
  1207. if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
  1208. clear_cache($basepath, $fullpath);
  1209. }
  1210. if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
  1211. unlink($fullpath);
  1212. }
  1213. }
  1214. closedir($dh);
  1215. }
  1216. }
  1217. }
  1218. function get_itemcachepath()
  1219. {
  1220. // Checking, if the cache is deactivated
  1221. $cachetime = (int) Config::get('system', 'itemcache_duration');
  1222. if ($cachetime < 0) {
  1223. return "";
  1224. }
  1225. $itemcache = Config::get('system', 'itemcache');
  1226. if (($itemcache != "") && App::directory_usable($itemcache)) {
  1227. return App::realpath($itemcache);
  1228. }
  1229. $temppath = get_temppath();
  1230. if ($temppath != "") {
  1231. $itemcache = $temppath . "/itemcache";
  1232. if (!file_exists($itemcache) && !is_dir($itemcache)) {
  1233. mkdir($itemcache);
  1234. }
  1235. if (App::directory_usable($itemcache)) {
  1236. Config::set("system", "itemcache", $itemcache);
  1237. return $itemcache;
  1238. }
  1239. }
  1240. return "";
  1241. }
  1242. /**
  1243. * @brief Returns the path where spool files are stored
  1244. *
  1245. * @return string Spool path
  1246. */
  1247. function get_spoolpath()
  1248. {
  1249. $spoolpath = Config::get('system', 'spoolpath');
  1250. if (($spoolpath != "") && App::directory_usable($spoolpath)) {
  1251. // We have a spool path and it is usable
  1252. return $spoolpath;
  1253. }
  1254. // We don't have a working preconfigured spool path, so we take the temp path.
  1255. $temppath = get_temppath();
  1256. if ($temppath != "") {
  1257. // To avoid any interferences with other systems we create our own directory
  1258. $spoolpath = $temppath . "/spool";
  1259. if (!is_dir($spoolpath)) {
  1260. mkdir($spoolpath);
  1261. }
  1262. if (App::directory_usable($spoolpath)) {
  1263. // The new path is usable, we are happy
  1264. Config::set("system", "spoolpath", $spoolpath);
  1265. return $spoolpath;
  1266. } else {
  1267. // We can't create a subdirectory, strange.
  1268. // But the directory seems to work, so we use it but don't store it.
  1269. return $temppath;
  1270. }
  1271. }
  1272. // Reaching this point means that the operating system is configured badly.
  1273. return "";
  1274. }
  1275. if (!function_exists('exif_imagetype')) {
  1276. function exif_imagetype($file)
  1277. {
  1278. $size = getimagesize($file);
  1279. return $size[2];
  1280. }
  1281. }
  1282. function validate_include(&$file)
  1283. {
  1284. $orig_file = $file;
  1285. $file = realpath($file);
  1286. if (strpos($file, getcwd()) !== 0) {
  1287. return false;
  1288. }
  1289. $file = str_replace(getcwd() . "/", "", $file, $count);
  1290. if ($count != 1) {
  1291. return false;
  1292. }
  1293. if ($orig_file !== $file) {
  1294. return false;
  1295. }
  1296. $valid = false;
  1297. if (strpos($file, "include/") === 0) {
  1298. $valid = true;
  1299. }
  1300. if (strpos($file, "addon/") === 0) {
  1301. $valid = true;
  1302. }
  1303. // Simply return flag
  1304. return ($valid);
  1305. }
  1306. function current_load()
  1307. {
  1308. if (!function_exists('sys_getloadavg')) {
  1309. return false;
  1310. }
  1311. $load_arr = sys_getloadavg();
  1312. if (!is_array($load_arr)) {
  1313. return false;
  1314. }
  1315. return max($load_arr[0], $load_arr[1]);
  1316. }
  1317. /**
  1318. * @brief get c-style args
  1319. *
  1320. * @return int
  1321. */
  1322. function argc()
  1323. {
  1324. return get_app()->argc;
  1325. }
  1326. /**
  1327. * @brief Returns the value of a argv key
  1328. *
  1329. * @param int $x argv key
  1330. * @return string Value of the argv key
  1331. */
  1332. function argv($x)
  1333. {
  1334. if (array_key_exists($x, get_app()->argv)) {
  1335. return get_app()->argv[$x];
  1336. }
  1337. return '';
  1338. }
  1339. /**
  1340. * @brief Get the data which is needed for infinite scroll
  1341. *
  1342. * For invinite scroll we need the page number of the actual page
  1343. * and the the URI where the content of the next page comes from.
  1344. * This data is needed for the js part in main.js.
  1345. * Note: infinite scroll does only work for the network page (module)
  1346. *
  1347. * @param string $module The name of the module (e.g. "network")
  1348. * @return array Of infinite scroll data
  1349. * 'pageno' => $pageno The number of the actual page
  1350. * 'reload_uri' => $reload_uri The URI of the content we have to load
  1351. */
  1352. function infinite_scroll_data($module)
  1353. {
  1354. if (PConfig::get(local_user(), 'system', 'infinite_scroll')
  1355. && $module == 'network'
  1356. && defaults($_GET, 'mode', '') != 'minimal'
  1357. ) {
  1358. // get the page number
  1359. $pageno = defaults($_GET, 'page', 1);
  1360. $reload_uri = "";
  1361. // try to get the uri from which we load the content
  1362. foreach ($_GET as $param => $value) {
  1363. if (($param != "page") && ($param != "q")) {
  1364. $reload_uri .= "&" . $param . "=" . urlencode($value);
  1365. }
  1366. }
  1367. $a = get_app();
  1368. if ($a->page_offset != "" && !strstr($reload_uri, "&offset=")) {
  1369. $reload_uri .= "&offset=" . urlencode($a->page_offset);
  1370. }
  1371. $arr = ["pageno" => $pageno, "reload_uri" => $reload_uri];
  1372. return $arr;
  1373. }
  1374. }