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.

1583 lines
40KB

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