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.

1700 lines
44KB

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