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.

1668 lines
43KB

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