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
40 KiB

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