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.

2400 lines
62KB

  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('include/autoloader.php');
  19. require_once('include/config.php');
  20. require_once('include/network.php');
  21. require_once('include/plugin.php');
  22. require_once('include/text.php');
  23. require_once('include/datetime.php');
  24. require_once('include/pgettext.php');
  25. require_once('include/nav.php');
  26. require_once('include/cache.php');
  27. require_once('library/Mobile_Detect/Mobile_Detect.php');
  28. require_once('include/features.php');
  29. require_once('include/identity.php');
  30. require_once('include/pidfile.php');
  31. require_once('update.php');
  32. require_once('include/dbstructure.php');
  33. define ( 'FRIENDICA_PLATFORM', 'Friendica');
  34. define ( 'FRIENDICA_CODENAME', 'Asparagus');
  35. define ( 'FRIENDICA_VERSION', '3.5-dev' );
  36. define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
  37. define ( 'DB_UPDATE_VERSION', 1202 );
  38. /**
  39. * @brief Constant with a HTML line break.
  40. *
  41. * Contains a HTML line break (br) element and a real carriage return with line
  42. * feed for the source.
  43. * This can be used in HTML and JavaScript where needed a line break.
  44. */
  45. define ( 'EOL', "<br />\r\n" );
  46. define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
  47. /**
  48. * @brief Image storage quality.
  49. *
  50. * Lower numbers save space at cost of image detail.
  51. * For ease of upgrade, please do not change here. Change jpeg quality with
  52. * $a->config['system']['jpeg_quality'] = n;
  53. * in .htconfig.php, where n is netween 1 and 100, and with very poor results
  54. * below about 50
  55. *
  56. */
  57. define ( 'JPEG_QUALITY', 100 );
  58. /**
  59. * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
  60. */
  61. define ( 'PNG_QUALITY', 8 );
  62. /**
  63. *
  64. * An alternate way of limiting picture upload sizes. Specify the maximum pixel
  65. * length that pictures are allowed to be (for non-square pictures, it will apply
  66. * to the longest side). Pictures longer than this length will be resized to be
  67. * this length (on the longest side, the other side will be scaled appropriately).
  68. * Modify this value using
  69. *
  70. * $a->config['system']['max_image_length'] = n;
  71. *
  72. * in .htconfig.php
  73. *
  74. * If you don't want to set a maximum length, set to -1. The default value is
  75. * defined by 'MAX_IMAGE_LENGTH' below.
  76. *
  77. */
  78. define ( 'MAX_IMAGE_LENGTH', -1 );
  79. /**
  80. * Not yet used
  81. */
  82. define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
  83. /**
  84. * @name SSL Policy
  85. *
  86. * SSL redirection policies
  87. * @{
  88. */
  89. define ( 'SSL_POLICY_NONE', 0 );
  90. define ( 'SSL_POLICY_FULL', 1 );
  91. define ( 'SSL_POLICY_SELFSIGN', 2 );
  92. /* @}*/
  93. /**
  94. * @name Logger
  95. *
  96. * log levels
  97. * @{
  98. */
  99. define ( 'LOGGER_NORMAL', 0 );
  100. define ( 'LOGGER_TRACE', 1 );
  101. define ( 'LOGGER_DEBUG', 2 );
  102. define ( 'LOGGER_DATA', 3 );
  103. define ( 'LOGGER_ALL', 4 );
  104. /* @}*/
  105. /**
  106. * @name Cache
  107. *
  108. * Cache levels
  109. * @{
  110. */
  111. define ( 'CACHE_MONTH', 0 );
  112. define ( 'CACHE_WEEK', 1 );
  113. define ( 'CACHE_DAY', 2 );
  114. define ( 'CACHE_HOUR', 3 );
  115. /* @}*/
  116. /**
  117. * @name Register
  118. *
  119. * Registration policies
  120. * @{
  121. */
  122. define ( 'REGISTER_CLOSED', 0 );
  123. define ( 'REGISTER_APPROVE', 1 );
  124. define ( 'REGISTER_OPEN', 2 );
  125. /** @}*/
  126. /**
  127. * @name Contact_is
  128. *
  129. * Relationship types
  130. * @{
  131. */
  132. define ( 'CONTACT_IS_FOLLOWER', 1);
  133. define ( 'CONTACT_IS_SHARING', 2);
  134. define ( 'CONTACT_IS_FRIEND', 3);
  135. /** @}*/
  136. /**
  137. * @name Update
  138. *
  139. * DB update return values
  140. * @{
  141. */
  142. define ( 'UPDATE_SUCCESS', 0);
  143. define ( 'UPDATE_FAILED', 1);
  144. /** @}*/
  145. /**
  146. * @name page/profile types
  147. *
  148. * PAGE_NORMAL is a typical personal profile account
  149. * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
  150. * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
  151. * write access to wall and comments (no email and not included in page owner's ACL lists)
  152. * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
  153. *
  154. * @{
  155. */
  156. define ( 'PAGE_NORMAL', 0 );
  157. define ( 'PAGE_SOAPBOX', 1 );
  158. define ( 'PAGE_COMMUNITY', 2 );
  159. define ( 'PAGE_FREELOVE', 3 );
  160. define ( 'PAGE_BLOG', 4 );
  161. define ( 'PAGE_PRVGROUP', 5 );
  162. /** @}*/
  163. /**
  164. * @name CP
  165. *
  166. * Type of the community page
  167. * @{
  168. */
  169. define ( 'CP_NO_COMMUNITY_PAGE', -1 );
  170. define ( 'CP_USERS_ON_SERVER', 0 );
  171. define ( 'CP_GLOBAL_COMMUNITY', 1 );
  172. /** @}*/
  173. /**
  174. * @name Network
  175. *
  176. * Network and protocol family types
  177. * @{
  178. */
  179. define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
  180. define ( 'NETWORK_ZOT', 'zot!'); // Zot!
  181. define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
  182. define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
  183. define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
  184. define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
  185. define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
  186. define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
  187. define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
  188. define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
  189. define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
  190. define ( 'NETWORK_GPLUS', 'goog'); // Google+
  191. define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
  192. define ( 'NETWORK_TWITTER', 'twit'); // Twitter
  193. define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
  194. define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
  195. define ( 'NETWORK_APPNET', 'apdn'); // app.net
  196. define ( 'NETWORK_NEWS', 'nntp'); // Network News Transfer Protocol
  197. define ( 'NETWORK_ICALENDAR', 'ical'); // iCalendar
  198. define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
  199. /** @}*/
  200. /**
  201. * These numbers are used in stored permissions
  202. * and existing allocations MUST NEVER BE CHANGED
  203. * OR RE-ASSIGNED! You may only add to them.
  204. */
  205. $netgroup_ids = array(
  206. NETWORK_DFRN => (-1),
  207. NETWORK_ZOT => (-2),
  208. NETWORK_OSTATUS => (-3),
  209. NETWORK_FEED => (-4),
  210. NETWORK_DIASPORA => (-5),
  211. NETWORK_MAIL => (-6),
  212. NETWORK_MAIL2 => (-7),
  213. NETWORK_FACEBOOK => (-8),
  214. NETWORK_LINKEDIN => (-9),
  215. NETWORK_XMPP => (-10),
  216. NETWORK_MYSPACE => (-11),
  217. NETWORK_GPLUS => (-12),
  218. NETWORK_PUMPIO => (-13),
  219. NETWORK_TWITTER => (-14),
  220. NETWORK_DIASPORA2 => (-15),
  221. NETWORK_STATUSNET => (-16),
  222. NETWORK_APPNET => (-17),
  223. NETWORK_NEWS => (-18),
  224. NETWORK_ICALENDAR => (-19),
  225. NETWORK_PHANTOM => (-127),
  226. );
  227. /**
  228. * Maximum number of "people who like (or don't like) this" that we will list by name
  229. */
  230. define ( 'MAX_LIKERS', 75);
  231. /**
  232. * Communication timeout
  233. */
  234. define ( 'ZCURL_TIMEOUT' , (-1));
  235. /**
  236. * @name Notify
  237. *
  238. * Email notification options
  239. * @{
  240. */
  241. define ( 'NOTIFY_INTRO', 0x0001 );
  242. define ( 'NOTIFY_CONFIRM', 0x0002 );
  243. define ( 'NOTIFY_WALL', 0x0004 );
  244. define ( 'NOTIFY_COMMENT', 0x0008 );
  245. define ( 'NOTIFY_MAIL', 0x0010 );
  246. define ( 'NOTIFY_SUGGEST', 0x0020 );
  247. define ( 'NOTIFY_PROFILE', 0x0040 );
  248. define ( 'NOTIFY_TAGSELF', 0x0080 );
  249. define ( 'NOTIFY_TAGSHARE', 0x0100 );
  250. define ( 'NOTIFY_POKE', 0x0200 );
  251. define ( 'NOTIFY_SHARE', 0x0400 );
  252. define ( 'NOTIFY_SYSTEM', 0x8000 );
  253. /* @}*/
  254. /**
  255. * @name Term
  256. *
  257. * Tag/term types
  258. * @{
  259. */
  260. define ( 'TERM_UNKNOWN', 0 );
  261. define ( 'TERM_HASHTAG', 1 );
  262. define ( 'TERM_MENTION', 2 );
  263. define ( 'TERM_CATEGORY', 3 );
  264. define ( 'TERM_PCATEGORY', 4 );
  265. define ( 'TERM_FILE', 5 );
  266. define ( 'TERM_SAVEDSEARCH', 6 );
  267. define ( 'TERM_CONVERSATION', 7 );
  268. define ( 'TERM_OBJ_POST', 1 );
  269. define ( 'TERM_OBJ_PHOTO', 2 );
  270. /**
  271. * @name Namespaces
  272. *
  273. * Various namespaces we may need to parse
  274. * @{
  275. */
  276. define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
  277. define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
  278. define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
  279. define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
  280. define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
  281. define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
  282. define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
  283. define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
  284. define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
  285. define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
  286. define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
  287. define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
  288. define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
  289. define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
  290. define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
  291. /* @}*/
  292. /**
  293. * @name Activity
  294. *
  295. * Activity stream defines
  296. * @{
  297. */
  298. define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
  299. define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
  300. define ( 'ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes' );
  301. define ( 'ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno' );
  302. define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe' );
  303. define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
  304. define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
  305. define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
  306. define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
  307. define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
  308. define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
  309. define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
  310. define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
  311. define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
  312. define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
  313. define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
  314. define ( 'ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share' );
  315. define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
  316. define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
  317. define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
  318. define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
  319. define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
  320. define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
  321. define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
  322. define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
  323. define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
  324. define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
  325. define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
  326. define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
  327. define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
  328. define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
  329. define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
  330. define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
  331. /* @}*/
  332. /**
  333. * @name Gravity
  334. *
  335. * Item weight for query ordering
  336. * @{
  337. */
  338. define ( 'GRAVITY_PARENT', 0);
  339. define ( 'GRAVITY_LIKE', 3);
  340. define ( 'GRAVITY_COMMENT', 6);
  341. /* @}*/
  342. /**
  343. * @name Priority
  344. *
  345. * Process priority for the worker
  346. * @{
  347. */
  348. define('PRIORITY_UNDEFINED', 0);
  349. define('PRIORITY_CRITICAL', 10);
  350. define('PRIORITY_HIGH', 20);
  351. define('PRIORITY_MEDIUM', 30);
  352. define('PRIORITY_LOW', 40);
  353. define('PRIORITY_NEGLIGIBLE',50);
  354. /* @}*/
  355. // Normally this constant is defined - but not if "pcntl" isn't installed
  356. if (!defined("SIGTERM"))
  357. define("SIGTERM", 15);
  358. /**
  359. *
  360. * Reverse the effect of magic_quotes_gpc if it is enabled.
  361. * Please disable magic_quotes_gpc so we don't have to do this.
  362. * See http://php.net/manual/en/security.magicquotes.disabling.php
  363. *
  364. */
  365. function startup() {
  366. error_reporting(E_ERROR | E_WARNING | E_PARSE);
  367. set_time_limit(0);
  368. // This has to be quite large to deal with embedded private photos
  369. ini_set('pcre.backtrack_limit', 500000);
  370. if (get_magic_quotes_gpc()) {
  371. $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
  372. while (list($key, $val) = each($process)) {
  373. foreach ($val as $k => $v) {
  374. unset($process[$key][$k]);
  375. if (is_array($v)) {
  376. $process[$key][stripslashes($k)] = $v;
  377. $process[] = &$process[$key][stripslashes($k)];
  378. } else {
  379. $process[$key][stripslashes($k)] = stripslashes($v);
  380. }
  381. }
  382. }
  383. unset($process);
  384. }
  385. }
  386. /**
  387. *
  388. * class: App
  389. *
  390. * @brief Our main application structure for the life of this page.
  391. *
  392. * Primarily deals with the URL that got us here
  393. * and tries to make some sense of it, and
  394. * stores our page contents and config storage
  395. * and anything else that might need to be passed around
  396. * before we spit the page out.
  397. *
  398. */
  399. class App {
  400. public $module_loaded = false;
  401. public $query_string;
  402. public $config;
  403. public $page;
  404. public $profile;
  405. public $profile_uid;
  406. public $user;
  407. public $cid;
  408. public $contact;
  409. public $contacts;
  410. public $page_contact;
  411. public $content;
  412. public $data = array();
  413. public $error = false;
  414. public $cmd;
  415. public $argv;
  416. public $argc;
  417. public $module;
  418. public $pager;
  419. public $strings;
  420. public $path;
  421. public $hooks;
  422. public $timezone;
  423. public $interactive = true;
  424. public $plugins;
  425. public $apps = array();
  426. public $identities;
  427. public $is_mobile = false;
  428. public $is_tablet = false;
  429. public $is_friendica_app;
  430. public $performance = array();
  431. public $callstack = array();
  432. public $theme_info = array();
  433. public $backend = true;
  434. public $nav_sel;
  435. public $category;
  436. // Allow themes to control internal parameters
  437. // by changing App values in theme.php
  438. public $sourcename = '';
  439. public $videowidth = 425;
  440. public $videoheight = 350;
  441. public $force_max_items = 0;
  442. public $theme_thread_allow = true;
  443. public $theme_events_in_profile = true;
  444. /**
  445. * @brief An array for all theme-controllable parameters
  446. *
  447. * Mostly unimplemented yet. Only options 'template_engine' and
  448. * beyond are used.
  449. */
  450. public $theme = array(
  451. 'sourcename' => '',
  452. 'videowidth' => 425,
  453. 'videoheight' => 350,
  454. 'force_max_items' => 0,
  455. 'thread_allow' => true,
  456. 'stylesheet' => '',
  457. 'template_engine' => 'smarty3',
  458. );
  459. /**
  460. * @brief An array of registered template engines ('name'=>'class name')
  461. */
  462. public $template_engines = array();
  463. /**
  464. * @brief An array of instanced template engines ('name'=>'instance')
  465. */
  466. public $template_engine_instance = array();
  467. public $process_id;
  468. private $ldelim = array(
  469. 'internal' => '',
  470. 'smarty3' => '{{'
  471. );
  472. private $rdelim = array(
  473. 'internal' => '',
  474. 'smarty3' => '}}'
  475. );
  476. private $scheme;
  477. private $hostname;
  478. private $baseurl;
  479. private $db;
  480. private $curl_code;
  481. private $curl_content_type;
  482. private $curl_headers;
  483. private $cached_profile_image;
  484. private $cached_profile_picdate;
  485. private static $a;
  486. /**
  487. * @brief App constructor.
  488. */
  489. function __construct() {
  490. global $default_timezone;
  491. $hostname = "";
  492. if (file_exists(".htpreconfig.php"))
  493. @include(".htpreconfig.php");
  494. $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
  495. date_default_timezone_set($this->timezone);
  496. $this->performance["start"] = microtime(true);
  497. $this->performance["database"] = 0;
  498. $this->performance["database_write"] = 0;
  499. $this->performance["network"] = 0;
  500. $this->performance["file"] = 0;
  501. $this->performance["rendering"] = 0;
  502. $this->performance["parser"] = 0;
  503. $this->performance["marktime"] = 0;
  504. $this->performance["markstart"] = microtime(true);
  505. $this->callstack["database"] = array();
  506. $this->callstack["network"] = array();
  507. $this->callstack["file"] = array();
  508. $this->callstack["rendering"] = array();
  509. $this->callstack["parser"] = array();
  510. $this->config = array();
  511. $this->page = array();
  512. $this->pager= array();
  513. $this->query_string = '';
  514. $this->process_id = uniqid("log", true);
  515. startup();
  516. set_include_path(
  517. 'include' . PATH_SEPARATOR
  518. . 'library' . PATH_SEPARATOR
  519. . 'library/phpsec' . PATH_SEPARATOR
  520. . 'library/langdet' . PATH_SEPARATOR
  521. . '.' );
  522. $this->scheme = 'http';
  523. if((x($_SERVER,'HTTPS') && $_SERVER['HTTPS']) ||
  524. (x($_SERVER['HTTP_FORWARDED']) && preg_match("/proto=https/", $_SERVER['HTTP_FORWARDED'])) ||
  525. (x($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
  526. (x($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
  527. (x($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
  528. (x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
  529. ) {
  530. $this->scheme = 'https';
  531. }
  532. if(x($_SERVER,'SERVER_NAME')) {
  533. $this->hostname = $_SERVER['SERVER_NAME'];
  534. if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
  535. $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
  536. /*
  537. * Figure out if we are running at the top of a domain
  538. * or in a sub-directory and adjust accordingly
  539. */
  540. $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
  541. if(isset($path) && strlen($path) && ($path != $this->path))
  542. $this->path = $path;
  543. }
  544. if ($hostname != "")
  545. $this->hostname = $hostname;
  546. if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
  547. $this->set_baseurl(array_pop($_SERVER["argv"]) );
  548. $_SERVER["argc"] --;
  549. }
  550. #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
  551. if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
  552. $this->query_string = substr($_SERVER['QUERY_STRING'],9);
  553. // removing trailing / - maybe a nginx problem
  554. if (substr($this->query_string, 0, 1) == "/")
  555. $this->query_string = substr($this->query_string, 1);
  556. } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
  557. $this->query_string = substr($_SERVER['QUERY_STRING'],2);
  558. // removing trailing / - maybe a nginx problem
  559. if (substr($this->query_string, 0, 1) == "/")
  560. $this->query_string = substr($this->query_string, 1);
  561. }
  562. if (x($_GET,'pagename'))
  563. $this->cmd = trim($_GET['pagename'],'/\\');
  564. elseif (x($_GET,'q'))
  565. $this->cmd = trim($_GET['q'],'/\\');
  566. // fix query_string
  567. $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
  568. // unix style "homedir"
  569. if(substr($this->cmd,0,1) === '~')
  570. $this->cmd = 'profile/' . substr($this->cmd,1);
  571. // Diaspora style profile url
  572. if(substr($this->cmd,0,2) === 'u/')
  573. $this->cmd = 'profile/' . substr($this->cmd,2);
  574. /*
  575. *
  576. * Break the URL path into C style argc/argv style arguments for our
  577. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  578. * will be 3 (integer) and $this->argv will contain:
  579. * [0] => 'module'
  580. * [1] => 'arg1'
  581. * [2] => 'arg2'
  582. *
  583. *
  584. * There will always be one argument. If provided a naked domain
  585. * URL, $this->argv[0] is set to "home".
  586. *
  587. */
  588. $this->argv = explode('/',$this->cmd);
  589. $this->argc = count($this->argv);
  590. if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
  591. $this->module = str_replace(".", "_", $this->argv[0]);
  592. $this->module = str_replace("-", "_", $this->module);
  593. }
  594. else {
  595. $this->argc = 1;
  596. $this->argv = array('home');
  597. $this->module = 'home';
  598. }
  599. /*
  600. * See if there is any page number information, and initialise
  601. * pagination
  602. */
  603. $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
  604. $this->pager['itemspage'] = 50;
  605. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  606. if($this->pager['start'] < 0)
  607. $this->pager['start'] = 0;
  608. $this->pager['total'] = 0;
  609. /*
  610. * Detect mobile devices
  611. */
  612. $mobile_detect = new Mobile_Detect();
  613. $this->is_mobile = $mobile_detect->isMobile();
  614. $this->is_tablet = $mobile_detect->isTablet();
  615. // Friendica-Client
  616. $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
  617. /*
  618. * register template engines
  619. */
  620. $dc = get_declared_classes();
  621. foreach ($dc as $k) {
  622. if (in_array("ITemplateEngine", class_implements($k))){
  623. $this->register_template_engine($k);
  624. }
  625. }
  626. self::$a = $this;
  627. }
  628. function get_basepath() {
  629. $basepath = get_config("system", "basepath");
  630. if ($basepath == "")
  631. $basepath = dirname(__FILE__);
  632. if ($basepath == "")
  633. $basepath = $_SERVER["DOCUMENT_ROOT"];
  634. if ($basepath == "")
  635. $basepath = $_SERVER["PWD"];
  636. return($basepath);
  637. }
  638. function get_scheme() {
  639. return($this->scheme);
  640. }
  641. function get_baseurl($ssl = false) {
  642. // Is the function called statically?
  643. if (!is_object($this))
  644. return(self::$a->get_baseurl($ssl));
  645. $scheme = $this->scheme;
  646. if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
  647. if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
  648. $scheme = 'https';
  649. // Basically, we have $ssl = true on any links which can only be seen by a logged in user
  650. // (and also the login link). Anything seen by an outsider will have it turned off.
  651. if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
  652. if($ssl)
  653. $scheme = 'https';
  654. else
  655. $scheme = 'http';
  656. }
  657. }
  658. if (get_config('config','hostname') != "")
  659. $this->hostname = get_config('config','hostname');
  660. $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
  661. return $this->baseurl;
  662. }
  663. function set_baseurl($url) {
  664. $parsed = @parse_url($url);
  665. $this->baseurl = $url;
  666. if($parsed) {
  667. $this->scheme = $parsed['scheme'];
  668. $hostname = $parsed['host'];
  669. if(x($parsed,'port'))
  670. $hostname .= ':' . $parsed['port'];
  671. if(x($parsed,'path'))
  672. $this->path = trim($parsed['path'],'\\/');
  673. if (file_exists(".htpreconfig.php"))
  674. @include(".htpreconfig.php");
  675. if (get_config('config','hostname') != "")
  676. $this->hostname = get_config('config','hostname');
  677. if (!isset($this->hostname) OR ($this->hostname == ""))
  678. $this->hostname = $hostname;
  679. }
  680. }
  681. function get_hostname() {
  682. if (get_config('config','hostname') != "")
  683. $this->hostname = get_config('config','hostname');
  684. return $this->hostname;
  685. }
  686. function set_hostname($h) {
  687. $this->hostname = $h;
  688. }
  689. function set_path($p) {
  690. $this->path = trim(trim($p),'/');
  691. }
  692. function get_path() {
  693. return $this->path;
  694. }
  695. function set_pager_total($n) {
  696. $this->pager['total'] = intval($n);
  697. }
  698. function set_pager_itemspage($n) {
  699. $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
  700. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  701. }
  702. function set_pager_page($n) {
  703. $this->pager['page'] = $n;
  704. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  705. }
  706. function init_pagehead() {
  707. $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
  708. // If the update is "deactivated" set it to the highest integer number (~24 days)
  709. if ($interval < 0)
  710. $interval = 2147483647;
  711. if($interval < 10000)
  712. $interval = 40000;
  713. // compose the page title from the sitename and the
  714. // current module called
  715. if (!$this->module=='')
  716. {
  717. $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
  718. } else {
  719. $this->page['title'] = $this->config['sitename'];
  720. }
  721. /* put the head template at the beginning of page['htmlhead']
  722. * since the code added by the modules frequently depends on it
  723. * being first
  724. */
  725. if(!isset($this->page['htmlhead']))
  726. $this->page['htmlhead'] = '';
  727. // If we're using Smarty, then doing replace_macros() will replace
  728. // any unrecognized variables with a blank string. Since we delay
  729. // replacing $stylesheet until later, we need to replace it now
  730. // with another variable name
  731. if($this->theme['template_engine'] === 'smarty3')
  732. $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
  733. else
  734. $stylesheet = '$stylesheet';
  735. $shortcut_icon = get_config("system", "shortcut_icon");
  736. if ($shortcut_icon == "")
  737. $shortcut_icon = "images/friendica-32.png";
  738. $touch_icon = get_config("system", "touch_icon");
  739. if ($touch_icon == "")
  740. $touch_icon = "images/friendica-128.png";
  741. // get data wich is needed for infinite scroll on the network page
  742. $invinite_scroll = infinite_scroll_data($this->module);
  743. $tpl = get_markup_template('head.tpl');
  744. $this->page['htmlhead'] = replace_macros($tpl,array(
  745. '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
  746. '$local_user' => local_user(),
  747. '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
  748. '$delitem' => t('Delete this item?'),
  749. '$comment' => t('Comment'),
  750. '$showmore' => t('show more'),
  751. '$showfewer' => t('show fewer'),
  752. '$update_interval' => $interval,
  753. '$shortcut_icon' => $shortcut_icon,
  754. '$touch_icon' => $touch_icon,
  755. '$stylesheet' => $stylesheet,
  756. '$infinite_scroll' => $invinite_scroll,
  757. )) . $this->page['htmlhead'];
  758. }
  759. function init_page_end() {
  760. if(!isset($this->page['end']))
  761. $this->page['end'] = '';
  762. $tpl = get_markup_template('end.tpl');
  763. $this->page['end'] = replace_macros($tpl,array(
  764. '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
  765. )) . $this->page['end'];
  766. }
  767. function set_curl_code($code) {
  768. $this->curl_code = $code;
  769. }
  770. function get_curl_code() {
  771. return $this->curl_code;
  772. }
  773. function set_curl_content_type($content_type) {
  774. $this->curl_content_type = $content_type;
  775. }
  776. function get_curl_content_type() {
  777. return $this->curl_content_type;
  778. }
  779. function set_curl_headers($headers) {
  780. $this->curl_headers = $headers;
  781. }
  782. function get_curl_headers() {
  783. return $this->curl_headers;
  784. }
  785. function get_cached_avatar_image($avatar_image){
  786. return $avatar_image;
  787. // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
  788. /*
  789. if($this->cached_profile_image[$avatar_image])
  790. return $this->cached_profile_image[$avatar_image];
  791. $path_parts = explode("/",$avatar_image);
  792. $common_filename = $path_parts[count($path_parts)-1];
  793. if($this->cached_profile_picdate[$common_filename]){
  794. $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
  795. } else {
  796. $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
  797. $common_filename);
  798. if(! dbm::is_result($r)){
  799. $this->cached_profile_image[$avatar_image] = $avatar_image;
  800. } else {
  801. $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
  802. $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
  803. }
  804. }
  805. return $this->cached_profile_image[$avatar_image];
  806. */
  807. }
  808. /**
  809. * @brief Removes the baseurl from an url. This avoids some mixed content problems.
  810. *
  811. * @param string $url
  812. *
  813. * @return string The cleaned url
  814. */
  815. function remove_baseurl($url){
  816. // Is the function called statically?
  817. if (!is_object($this))
  818. return(self::$a->remove_baseurl($url));
  819. $url = normalise_link($url);
  820. $base = normalise_link($this->get_baseurl());
  821. $url = str_replace($base."/", "", $url);
  822. return $url;
  823. }
  824. /**
  825. * @brief Register template engine class
  826. *
  827. * If $name is "", is used class static property $class::$name
  828. *
  829. * @param string $class
  830. * @param string $name
  831. */
  832. function register_template_engine($class, $name = '') {
  833. if ($name===""){
  834. $v = get_class_vars( $class );
  835. if(x($v,"name")) $name = $v['name'];
  836. }
  837. if ($name===""){
  838. echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
  839. killme();
  840. }
  841. $this->template_engines[$name] = $class;
  842. }
  843. /**
  844. * @brief Return template engine instance.
  845. *
  846. * If $name is not defined, return engine defined by theme,
  847. * or default
  848. *
  849. * @param strin $name Template engine name
  850. * @return object Template Engine instance
  851. */
  852. function template_engine($name = ''){
  853. if ($name!=="") {
  854. $template_engine = $name;
  855. } else {
  856. $template_engine = 'smarty3';
  857. if (x($this->theme, 'template_engine')) {
  858. $template_engine = $this->theme['template_engine'];
  859. }
  860. }
  861. if (isset($this->template_engines[$template_engine])){
  862. if(isset($this->template_engine_instance[$template_engine])){
  863. return $this->template_engine_instance[$template_engine];
  864. } else {
  865. $class = $this->template_engines[$template_engine];
  866. $obj = new $class;
  867. $this->template_engine_instance[$template_engine] = $obj;
  868. return $obj;
  869. }
  870. }
  871. echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
  872. }
  873. /**
  874. * @brief Returns the active template engine.
  875. *
  876. * @return string
  877. */
  878. function get_template_engine() {
  879. return $this->theme['template_engine'];
  880. }
  881. function set_template_engine($engine = 'smarty3') {
  882. $this->theme['template_engine'] = $engine;
  883. /*
  884. $this->theme['template_engine'] = 'smarty3';
  885. switch($engine) {
  886. case 'smarty3':
  887. if(is_writable('view/smarty3/'))
  888. $this->theme['template_engine'] = 'smarty3';
  889. break;
  890. default:
  891. break;
  892. }
  893. */
  894. }
  895. function get_template_ldelim($engine = 'smarty3') {
  896. return $this->ldelim[$engine];
  897. }
  898. function get_template_rdelim($engine = 'smarty3') {
  899. return $this->rdelim[$engine];
  900. }
  901. function save_timestamp($stamp, $value) {
  902. $duration = (float)(microtime(true)-$stamp);
  903. if (!isset($this->performance[$value])) {
  904. // Prevent ugly E_NOTICE
  905. $this->performance[$value] = 0;
  906. }
  907. $this->performance[$value] += (float)$duration;
  908. $this->performance["marktime"] += (float)$duration;
  909. $callstack = $this->callstack();
  910. if (!isset($this->callstack[$value][$callstack])) {
  911. // Prevent ugly E_NOTICE
  912. $this->callstack[$value][$callstack] = 0;
  913. }
  914. $this->callstack[$value][$callstack] += (float)$duration;
  915. }
  916. /**
  917. * @brief Log active processes into the "process" table
  918. */
  919. function start_process() {
  920. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
  921. $command = basename($trace[0]["file"]);
  922. $this->remove_inactive_processes();
  923. $r = q("SELECT `pid` FROM `process` WHERE `pid` = %d", intval(getmypid()));
  924. if(!dbm::is_result($r))
  925. q("INSERT INTO `process` (`pid`,`command`,`created`) VALUES (%d, '%s', '%s')",
  926. intval(getmypid()),
  927. dbesc($command),
  928. dbesc(datetime_convert()));
  929. }
  930. /**
  931. * @brief Remove inactive processes
  932. */
  933. function remove_inactive_processes() {
  934. $r = q("SELECT `pid` FROM `process`");
  935. if(dbm::is_result($r))
  936. foreach ($r AS $process)
  937. if (!posix_kill($process["pid"], 0))
  938. q("DELETE FROM `process` WHERE `pid` = %d", intval($process["pid"]));
  939. }
  940. /**
  941. * @brief Remove the active process from the "process" table
  942. */
  943. function end_process() {
  944. q("DELETE FROM `process` WHERE `pid` = %d", intval(getmypid()));
  945. }
  946. /**
  947. * @brief Returns a string with a callstack. Can be used for logging.
  948. *
  949. * @return string
  950. */
  951. function callstack() {
  952. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
  953. // We remove the first two items from the list since they contain data that we don't need.
  954. array_shift($trace);
  955. array_shift($trace);
  956. $callstack = array();
  957. foreach ($trace AS $func)
  958. $callstack[] = $func["function"];
  959. return implode(", ", $callstack);
  960. }
  961. function mark_timestamp($mark) {
  962. //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
  963. $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
  964. }
  965. function get_useragent() {
  966. return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
  967. }
  968. function is_friendica_app() {
  969. return($this->is_friendica_app);
  970. }
  971. /**
  972. * @brief Checks if the site is called via a backend process
  973. *
  974. * This isn't a perfect solution. But we need this check very early.
  975. * So we cannot wait until the modules are loaded.
  976. *
  977. * @return bool Is it a known backend?
  978. */
  979. function is_backend() {
  980. $backend = array();
  981. $backend[] = "_well_known";
  982. $backend[] = "api";
  983. $backend[] = "dfrn_notify";
  984. $backend[] = "fetch";
  985. $backend[] = "hcard";
  986. $backend[] = "hostxrd";
  987. $backend[] = "nodeinfo";
  988. $backend[] = "noscrape";
  989. $backend[] = "p";
  990. $backend[] = "poco";
  991. $backend[] = "post";
  992. $backend[] = "proxy";
  993. $backend[] = "pubsub";
  994. $backend[] = "pubsubhubbub";
  995. $backend[] = "receive";
  996. $backend[] = "rsd_xml";
  997. $backend[] = "salmon";
  998. $backend[] = "statistics_json";
  999. $backend[] = "xrd";
  1000. if (in_array($this->module, $backend))
  1001. return(true);
  1002. else
  1003. return($this->backend);
  1004. }
  1005. /**
  1006. * @brief Checks if the maximum number of database processes is reached
  1007. *
  1008. * @return bool Is the limit reached?
  1009. */
  1010. function max_processes_reached() {
  1011. // Is the function called statically?
  1012. if (!is_object($this))
  1013. return(self::$a->max_processes_reached());
  1014. if ($this->is_backend()) {
  1015. $process = "backend";
  1016. $max_processes = get_config('system', 'max_processes_backend');
  1017. if (intval($max_processes) == 0)
  1018. $max_processes = 5;
  1019. } else {
  1020. $process = "frontend";
  1021. $max_processes = get_config('system', 'max_processes_frontend');
  1022. if (intval($max_processes) == 0)
  1023. $max_processes = 20;
  1024. }
  1025. $processlist = dbm::processlist();
  1026. if ($processlist["list"] != "") {
  1027. logger("Processcheck: Processes: ".$processlist["amount"]." - Processlist: ".$processlist["list"], LOGGER_DEBUG);
  1028. if ($processlist["amount"] > $max_processes) {
  1029. logger("Processcheck: Maximum number of processes for ".$process." tasks (".$max_processes.") reached.", LOGGER_DEBUG);
  1030. return true;
  1031. }
  1032. }
  1033. return false;
  1034. }
  1035. /**
  1036. * @brief Checks if the maximum load is reached
  1037. *
  1038. * @return bool Is the load reached?
  1039. */
  1040. function maxload_reached() {
  1041. // Is the function called statically?
  1042. if (!is_object($this))
  1043. return(self::$a->maxload_reached());
  1044. if ($this->is_backend()) {
  1045. $process = "backend";
  1046. $maxsysload = intval(get_config('system', 'maxloadavg'));
  1047. if ($maxsysload < 1)
  1048. $maxsysload = 50;
  1049. } else {
  1050. $process = "frontend";
  1051. $maxsysload = intval(get_config('system','maxloadavg_frontend'));
  1052. if ($maxsysload < 1)
  1053. $maxsysload = 50;
  1054. }
  1055. $load = current_load();
  1056. if ($load) {
  1057. if (intval($load) > $maxsysload) {
  1058. logger('system: load '.$load.' for '.$process.' tasks ('.$maxsysload.') too high.');
  1059. return true;
  1060. }
  1061. }
  1062. return false;
  1063. }
  1064. /**
  1065. * @brief Checks if the process is already running
  1066. *
  1067. * @param string $taskname The name of the task that will be used for the name of the lockfile
  1068. * @param string $task The path and name of the php script
  1069. * @param int $timeout The timeout after which a task should be killed
  1070. *
  1071. * @return bool Is the process running?
  1072. */
  1073. function is_already_running($taskname, $task = "", $timeout = 540) {
  1074. $lockpath = get_lockpath();
  1075. if ($lockpath != '') {
  1076. $pidfile = new pidfile($lockpath, $taskname);
  1077. if ($pidfile->is_already_running()) {
  1078. logger("Already running");
  1079. if ($pidfile->running_time() > $timeout) {
  1080. $pidfile->kill();
  1081. logger("killed stale process");
  1082. // Calling a new instance
  1083. if ($task != "")
  1084. proc_run(PRIORITY_MEDIUM, $task);
  1085. }
  1086. return true;
  1087. }
  1088. }
  1089. return false;
  1090. }
  1091. function proc_run($args) {
  1092. // Add the php path if it is a php call
  1093. if (count($args) && ($args[0] === 'php' OR is_int($args[0]))) {
  1094. // If the last worker fork was less than 10 seconds before then don't fork another one.
  1095. // This should prevent the forking of masses of workers.
  1096. if (get_config("system", "worker")) {
  1097. if ((time() - get_config("system", "proc_run_started")) < 10)
  1098. return;
  1099. // Set the timestamp of the last proc_run
  1100. set_config("system", "proc_run_started", time());
  1101. }
  1102. $args[0] = ((x($this->config,'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php');
  1103. }
  1104. // add baseurl to args. cli scripts can't construct it
  1105. $args[] = $this->get_baseurl();
  1106. for($x = 0; $x < count($args); $x ++)
  1107. $args[$x] = escapeshellarg($args[$x]);
  1108. $cmdline = implode($args," ");
  1109. if(get_config('system','proc_windows'))
  1110. proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
  1111. else
  1112. proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
  1113. }
  1114. }
  1115. /**
  1116. * @brief Retrieve the App structure
  1117. *
  1118. * Useful in functions which require it but don't get it passed to them
  1119. */
  1120. function get_app() {
  1121. global $a;
  1122. return $a;
  1123. }
  1124. /**
  1125. * @brief Multi-purpose function to check variable state.
  1126. *
  1127. * Usage: x($var) or $x($array, 'key')
  1128. *
  1129. * returns false if variable/key is not set
  1130. * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
  1131. * e.g. x('') or x(0) returns 0;
  1132. *
  1133. * @param string|array $s variable to check
  1134. * @param string $k key inside the array to check
  1135. *
  1136. * @return bool|int
  1137. */
  1138. function x($s,$k = NULL) {
  1139. if($k != NULL) {
  1140. if((is_array($s)) && (array_key_exists($k,$s))) {
  1141. if($s[$k])
  1142. return (int) 1;
  1143. return (int) 0;
  1144. }
  1145. return false;
  1146. }
  1147. else {
  1148. if(isset($s)) {
  1149. if($s) {
  1150. return (int) 1;
  1151. }
  1152. return (int) 0;
  1153. }
  1154. return false;
  1155. }
  1156. }
  1157. /**
  1158. * @brief Called from db initialisation if db is dead.
  1159. */
  1160. function system_unavailable() {
  1161. include('system_unavailable.php');
  1162. system_down();
  1163. killme();
  1164. }
  1165. function clean_urls() {
  1166. global $a;
  1167. // if($a->config['system']['clean_urls'])
  1168. return true;
  1169. // return false;
  1170. }
  1171. function z_path() {
  1172. global $a;
  1173. $base = $a->get_baseurl();
  1174. if(! clean_urls())
  1175. $base .= '/?q=';
  1176. return $base;
  1177. }
  1178. /**
  1179. * @brief Returns the baseurl.
  1180. *
  1181. * @see App::get_baseurl()
  1182. *
  1183. * @return string
  1184. */
  1185. function z_root() {
  1186. global $a;
  1187. return $a->get_baseurl();
  1188. }
  1189. /**
  1190. * @brief Return absolut URL for given $path.
  1191. *
  1192. * @param string $path
  1193. *
  1194. * @return string
  1195. */
  1196. function absurl($path) {
  1197. if(strpos($path,'/') === 0)
  1198. return z_path() . $path;
  1199. return $path;
  1200. }
  1201. /**
  1202. * @brief Function to check if request was an AJAX (xmlhttprequest) request.
  1203. *
  1204. * @return boolean
  1205. */
  1206. function is_ajax() {
  1207. return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
  1208. }
  1209. function check_db() {
  1210. $build = get_config('system','build');
  1211. if(! x($build)) {
  1212. set_config('system','build',DB_UPDATE_VERSION);
  1213. $build = DB_UPDATE_VERSION;
  1214. }
  1215. if($build != DB_UPDATE_VERSION)
  1216. proc_run(PRIORITY_CRITICAL, 'include/dbupdate.php');
  1217. }
  1218. /**
  1219. * Sets the base url for use in cmdline programs which don't have
  1220. * $_SERVER variables
  1221. */
  1222. function check_url(&$a) {
  1223. $url = get_config('system','url');
  1224. // if the url isn't set or the stored url is radically different
  1225. // than the currently visited url, store the current value accordingly.
  1226. // "Radically different" ignores common variations such as http vs https
  1227. // and www.example.com vs example.com.
  1228. // We will only change the url to an ip address if there is no existing setting
  1229. if(! x($url))
  1230. $url = set_config('system','url',$a->get_baseurl());
  1231. if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
  1232. $url = set_config('system','url',$a->get_baseurl());
  1233. return;
  1234. }
  1235. /**
  1236. * @brief Automatic database updates
  1237. */
  1238. function update_db(&$a) {
  1239. $build = get_config('system','build');
  1240. if(! x($build))
  1241. $build = set_config('system','build',DB_UPDATE_VERSION);
  1242. if($build != DB_UPDATE_VERSION) {
  1243. $stored = intval($build);
  1244. $current = intval(DB_UPDATE_VERSION);
  1245. if($stored < $current) {
  1246. load_config('database');
  1247. // We're reporting a different version than what is currently installed.
  1248. // Run any existing update scripts to bring the database up to current.
  1249. // make sure that boot.php and update.php are the same release, we might be
  1250. // updating right this very second and the correct version of the update.php
  1251. // file may not be here yet. This can happen on a very busy site.
  1252. if(DB_UPDATE_VERSION == UPDATE_VERSION) {
  1253. // Compare the current structure with the defined structure
  1254. $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
  1255. if($t !== false)
  1256. return;
  1257. set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
  1258. // run old update routine (wich could modify the schema and
  1259. // conflits with new routine)
  1260. for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
  1261. $r = run_update_function($x);
  1262. if (!$r) break;
  1263. }
  1264. if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
  1265. // run new update routine
  1266. // it update the structure in one call
  1267. $retval = update_structure(false, true);
  1268. if($retval) {
  1269. update_fail(
  1270. DB_UPDATE_VERSION,
  1271. $retval
  1272. );
  1273. return;
  1274. } else {
  1275. set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
  1276. }
  1277. // run any left update_nnnn functions in update.php
  1278. for($x = $stored; $x < $current; $x ++) {
  1279. $r = run_update_function($x);
  1280. if (!$r) break;
  1281. }
  1282. }
  1283. }
  1284. }
  1285. return;
  1286. }
  1287. function run_update_function($x) {
  1288. if(function_exists('update_' . $x)) {
  1289. // There could be a lot of processes running or about to run.
  1290. // We want exactly one process to run the update command.
  1291. // So store the fact that we're taking responsibility
  1292. // after first checking to see if somebody else already has.
  1293. // If the update fails or times-out completely you may need to
  1294. // delete the config entry to try again.
  1295. $t = get_config('database','update_' . $x);
  1296. if($t !== false)
  1297. return false;
  1298. set_config('database','update_' . $x, time());
  1299. // call the specific update
  1300. $func = 'update_' . $x;
  1301. $retval = $func();
  1302. if($retval) {
  1303. //send the administrator an e-mail
  1304. update_fail(
  1305. $x,
  1306. sprintf(t('Update %s failed. See error logs.'), $x)
  1307. );
  1308. return false;
  1309. } else {
  1310. set_config('database','update_' . $x, 'success');
  1311. set_config('system','build', $x + 1);
  1312. return true;
  1313. }
  1314. } else {
  1315. set_config('database','update_' . $x, 'success');
  1316. set_config('system','build', $x + 1);
  1317. return true;
  1318. }
  1319. return true;
  1320. }
  1321. /**
  1322. * @brief Synchronise plugins:
  1323. *
  1324. * $a->config['system']['addon'] contains a comma-separated list of names
  1325. * of plugins/addons which are used on this system.
  1326. * Go through the database list of already installed addons, and if we have
  1327. * an entry, but it isn't in the config list, call the uninstall procedure
  1328. * and mark it uninstalled in the database (for now we'll remove it).
  1329. * Then go through the config list and if we have a plugin that isn't installed,
  1330. * call the install procedure and add it to the database.
  1331. *
  1332. * @param App $a
  1333. *
  1334. */
  1335. function check_plugins(&$a) {
  1336. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  1337. if(dbm::is_result($r))
  1338. $installed = $r;
  1339. else
  1340. $installed = array();
  1341. $plugins = get_config('system','addon');
  1342. $plugins_arr = array();
  1343. if($plugins)
  1344. $plugins_arr = explode(',',str_replace(' ', '',$plugins));
  1345. $a->plugins = $plugins_arr;
  1346. $installed_arr = array();
  1347. if(count($installed)) {
  1348. foreach($installed as $i) {
  1349. if(! in_array($i['name'],$plugins_arr)) {
  1350. uninstall_plugin($i['name']);
  1351. }
  1352. else {
  1353. $installed_arr[] = $i['name'];
  1354. }
  1355. }
  1356. }
  1357. if(count($plugins_arr)) {
  1358. foreach($plugins_arr as $p) {
  1359. if(! in_array($p,$installed_arr)) {
  1360. install_plugin($p);
  1361. }
  1362. }
  1363. }
  1364. load_hooks();
  1365. return;
  1366. }
  1367. function get_guid($size=16, $prefix = "") {
  1368. if ($prefix == "") {
  1369. $a = get_app();
  1370. $prefix = hash("crc32", $a->get_hostname());
  1371. }
  1372. while (strlen($prefix) < ($size - 13))
  1373. $prefix .= mt_rand();
  1374. if ($size >= 24) {
  1375. $prefix = substr($prefix, 0, $size - 22);
  1376. return(str_replace(".", "", uniqid($prefix, true)));
  1377. } else {
  1378. $prefix = substr($prefix, 0, max($size - 13, 0));
  1379. return(uniqid($prefix));
  1380. }
  1381. }
  1382. /**
  1383. * @brief Wrapper for adding a login box.
  1384. *
  1385. * @param bool $register
  1386. * If $register == true provide a registration link.
  1387. * This will most always depend on the value of $a->config['register_policy'].
  1388. * @param bool $hiddens
  1389. *
  1390. * @return string
  1391. * Returns the complete html for inserting into the page
  1392. *
  1393. * @hooks 'login_hook'
  1394. * string $o
  1395. */
  1396. function login($register = false, $hiddens=false) {
  1397. $a = get_app();
  1398. $o = "";
  1399. $reg = false;
  1400. if ($register) {
  1401. $reg = array(
  1402. 'title' => t('Create a New Account'),
  1403. 'desc' => t('Register')
  1404. );
  1405. }
  1406. $noid = get_config('system','no_openid');
  1407. $dest_url = $a->query_string;
  1408. if(local_user()) {
  1409. $tpl = get_markup_template("logout.tpl");
  1410. }
  1411. else {
  1412. $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
  1413. '$baseurl' => $a->get_baseurl(true)
  1414. ));
  1415. $tpl = get_markup_template("login.tpl");
  1416. $_SESSION['return_url'] = $a->query_string;
  1417. $a->module = 'login';
  1418. }
  1419. $o .= replace_macros($tpl, array(
  1420. '$dest_url' => $dest_url,
  1421. '$logout' => t('Logout'),
  1422. '$login' => t('Login'),
  1423. '$lname' => array('username', t('Nickname or Email: ') , '', ''),
  1424. '$lpassword' => array('password', t('Password: '), '', ''),
  1425. '$lremember' => array('remember', t('Remember me'), 0, ''),
  1426. '$openid' => !$noid,
  1427. '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
  1428. '$hiddens' => $hiddens,
  1429. '$register' => $reg,
  1430. '$lostpass' => t('Forgot your password?'),
  1431. '$lostlink' => t('Password Reset'),
  1432. '$tostitle' => t('Website Terms of Service'),
  1433. '$toslink' => t('terms of service'),
  1434. '$privacytitle' => t('Website Privacy Policy'),
  1435. '$privacylink' => t('privacy policy'),
  1436. ));
  1437. call_hooks('login_hook',$o);
  1438. return $o;
  1439. }
  1440. /**
  1441. * @brief Used to end the current process, after saving session state.
  1442. */
  1443. function killme() {
  1444. if (!get_app()->is_backend())
  1445. session_write_close();
  1446. exit;
  1447. }
  1448. /**
  1449. * @brief Redirect to another URL and terminate this process.
  1450. */
  1451. function goaway($s) {
  1452. if (!strstr(normalise_link($s), "http://"))
  1453. $s = App::get_baseurl()."/".$s;
  1454. header("Location: $s");
  1455. killme();
  1456. }
  1457. /**
  1458. * @brief Returns the user id of locally logged in user or false.
  1459. *
  1460. * @return int|bool user id or false
  1461. */
  1462. function local_user() {
  1463. if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
  1464. return intval($_SESSION['uid']);
  1465. return false;
  1466. }
  1467. /**
  1468. * @brief Returns contact id of authenticated site visitor or false
  1469. *
  1470. * @return int|bool visitor_id or false
  1471. */
  1472. function remote_user() {
  1473. if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
  1474. return intval($_SESSION['visitor_id']);
  1475. return false;
  1476. }
  1477. /**
  1478. * @brief Show an error message to user.
  1479. *
  1480. * This function save text in session, to be shown to the user at next page load
  1481. *
  1482. * @param string $s - Text of notice
  1483. */
  1484. function notice($s) {
  1485. $a = get_app();
  1486. if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
  1487. if($a->interactive)
  1488. $_SESSION['sysmsg'][] = $s;
  1489. }
  1490. /**
  1491. * @brief Show an info message to user.
  1492. *
  1493. * This function save text in session, to be shown to the user at next page load
  1494. *
  1495. * @param string $s - Text of notice
  1496. */
  1497. function info($s) {
  1498. $a = get_app();
  1499. if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
  1500. return;
  1501. if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
  1502. if($a->interactive)
  1503. $_SESSION['sysmsg_info'][] = $s;
  1504. }
  1505. /**
  1506. * @brief Wrapper around config to limit the text length of an incoming message
  1507. *
  1508. * @return int
  1509. */
  1510. function get_max_import_size() {
  1511. global $a;
  1512. return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
  1513. }
  1514. /**
  1515. * @brief Wrap calls to proc_close(proc_open()) and call hook
  1516. * so plugins can take part in process :)
  1517. *
  1518. * @param (string|integer) $cmd program to run or priority
  1519. *
  1520. * next args are passed as $cmd command line
  1521. * e.g.: proc_run("ls","-la","/tmp");
  1522. * or: proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $drop_id);
  1523. *
  1524. * @note $cmd and string args are surrounded with ""
  1525. *
  1526. * @hooks 'proc_run'
  1527. * array $arr
  1528. */
  1529. function proc_run($cmd){
  1530. $a = get_app();
  1531. $args = func_get_args();
  1532. $newargs = array();
  1533. if (!count($args))
  1534. return;
  1535. // expand any arrays
  1536. foreach($args as $arg) {
  1537. if(is_array($arg)) {
  1538. foreach($arg as $n) {
  1539. $newargs[] = $n;
  1540. }
  1541. } else
  1542. $newargs[] = $arg;
  1543. }
  1544. $args = $newargs;
  1545. $arr = array('args' => $args, 'run_cmd' => true);
  1546. call_hooks("proc_run", $arr);
  1547. if (!$arr['run_cmd'] OR !count($args))
  1548. return;
  1549. if (!get_config("system", "worker") OR
  1550. (($args[0] != 'php') AND !is_int($args[0]))) {
  1551. $a->proc_run($args);
  1552. return;
  1553. }
  1554. if (is_int($args[0]))
  1555. $priority = $args[0];
  1556. else
  1557. $priority = PRIORITY_MEDIUM;
  1558. $argv = $args;
  1559. array_shift($argv);
  1560. $parameters = json_encode($argv);
  1561. $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
  1562. dbesc($parameters));
  1563. if (!$found)
  1564. q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
  1565. VALUES ('%s', '%s', %d)",
  1566. dbesc($parameters),
  1567. dbesc(datetime_convert()),
  1568. intval($priority));
  1569. // Should we quit and wait for the poller to be called as a cronjob?
  1570. if (get_config("system", "worker_dont_fork"))
  1571. return;
  1572. // Checking number of workers
  1573. $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
  1574. // Get number of allowed number of worker threads
  1575. $queues = intval(get_config("system", "worker_queues"));
  1576. if ($queues == 0)
  1577. $queues = 4;
  1578. // If there are already enough workers running, don't fork another one
  1579. if ($workers[0]["workers"] >= $queues)
  1580. return;
  1581. // Now call the poller to execute the jobs that we just added to the queue
  1582. $args = array("php", "include/poller.php", "no_cron");
  1583. $a->proc_run($args);
  1584. }
  1585. function current_theme(){
  1586. $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
  1587. $a = get_app();
  1588. $page_theme = null;
  1589. // Find the theme that belongs to the user whose stuff we are looking at
  1590. if($a->profile_uid && ($a->profile_uid != local_user())) {
  1591. $r = q("select theme from user where uid = %d limit 1",
  1592. intval($a->profile_uid)
  1593. );
  1594. if(dbm::is_result($r))
  1595. $page_theme = $r[0]['theme'];
  1596. }
  1597. // Allow folks to over-rule user themes and always use their own on their own site.
  1598. // This works only if the user is on the same server
  1599. if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
  1600. if(get_pconfig(local_user(),'system','always_my_theme'))
  1601. $page_theme = null;
  1602. }
  1603. // $mobile_detect = new Mobile_Detect();
  1604. // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
  1605. $is_mobile = $a->is_mobile || $a->is_tablet;
  1606. $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
  1607. $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
  1608. if($is_mobile) {
  1609. if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  1610. $system_theme = $standard_system_theme;
  1611. $theme_name = $standard_theme_name;
  1612. }
  1613. else {
  1614. $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
  1615. $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
  1616. if($theme_name === '---') {
  1617. // user has selected to have the mobile theme be the same as the normal one
  1618. $system_theme = $standard_system_theme;
  1619. $theme_name = $standard_theme_name;
  1620. if($page_theme)
  1621. $theme_name = $page_theme;
  1622. }
  1623. }
  1624. }
  1625. else {
  1626. $system_theme = $standard_system_theme;
  1627. $theme_name = $standard_theme_name;
  1628. if($page_theme)
  1629. $theme_name = $page_theme;
  1630. }
  1631. if($theme_name &&
  1632. (file_exists('view/theme/' . $theme_name . '/style.css') ||
  1633. file_exists('view/theme/' . $theme_name . '/style.php')))
  1634. return($theme_name);
  1635. foreach($app_base_themes as $t) {
  1636. if(file_exists('view/theme/' . $t . '/style.css')||
  1637. file_exists('view/theme/' . $t . '/style.php'))
  1638. return($t);
  1639. }
  1640. $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
  1641. if(count($fallback))
  1642. return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
  1643. }
  1644. /**
  1645. * @brief Return full URL to theme which is currently in effect.
  1646. *
  1647. * Provide a sane default if nothing is chosen or the specified theme does not exist.
  1648. *
  1649. * @return string
  1650. */
  1651. function current_theme_url() {
  1652. global $a;
  1653. $t = current_theme();
  1654. $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
  1655. if (file_exists('view/theme/' . $t . '/style.php'))
  1656. return('view/theme/'.$t.'/style.pcss'.$opts);
  1657. return('view/theme/'.$t.'/style.css');
  1658. }
  1659. function feed_birthday($uid,$tz) {
  1660. /**
  1661. *
  1662. * Determine the next birthday, but only if the birthday is published
  1663. * in the default profile. We _could_ also look for a private profile that the
  1664. * recipient can see, but somebody could get mad at us if they start getting
  1665. * public birthday greetings when they haven't made this info public.
  1666. *
  1667. * Assuming we are able to publish this info, we are then going to convert
  1668. * the start time from the owner's timezone to UTC.
  1669. *
  1670. * This will potentially solve the problem found with some social networks
  1671. * where birthdays are converted to the viewer's timezone and salutations from
  1672. * elsewhere in the world show up on the wrong day. We will convert it to the
  1673. * viewer's timezone also, but first we are going to convert it from the birthday
  1674. * person's timezone to GMT - so the viewer may find the birthday starting at
  1675. * 6:00PM the day before, but that will correspond to midnight to the birthday person.
  1676. *
  1677. */
  1678. $birthday = '';
  1679. if(! strlen($tz))
  1680. $tz = 'UTC';
  1681. $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
  1682. intval($uid)
  1683. );
  1684. if(dbm::is_result($p)) {
  1685. $tmp_dob = substr($p[0]['dob'],5);
  1686. if(intval($tmp_dob)) {
  1687. $y = datetime_convert($tz,$tz,'now','Y');
  1688. $bd = $y . '-' . $tmp_dob . ' 00:00';
  1689. $t_dob = strtotime($bd);
  1690. $now = strtotime(datetime_convert($tz,$tz,'now'));
  1691. if($t_dob < $now)
  1692. $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
  1693. $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
  1694. }
  1695. }
  1696. return $birthday;
  1697. }
  1698. /**
  1699. * @brief Check if current user has admin role.
  1700. *
  1701. * @return bool true if user is an admin
  1702. */
  1703. function is_site_admin() {
  1704. $a = get_app();
  1705. $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
  1706. //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
  1707. if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
  1708. return true;
  1709. return false;
  1710. }
  1711. /**
  1712. * @brief Returns querystring as string from a mapped array.
  1713. *
  1714. * @param array $params mapped array with query parameters
  1715. * @param string $name of parameter, default null
  1716. *
  1717. * @return string
  1718. */
  1719. function build_querystring($params, $name=null) {
  1720. $ret = "";
  1721. foreach($params as $key=>$val) {
  1722. if(is_array($val)) {
  1723. if($name==null) {
  1724. $ret .= build_querystring($val, $key);
  1725. } else {
  1726. $ret .= build_querystring($val, $name."[$key]");
  1727. }
  1728. } else {
  1729. $val = urlencode($val);
  1730. if($name!=null) {
  1731. $ret.=$name."[$key]"."=$val&";
  1732. } else {
  1733. $ret.= "$key=$val&";
  1734. }
  1735. }
  1736. }
  1737. return $ret;
  1738. }
  1739. function explode_querystring($query) {
  1740. $arg_st = strpos($query, '?');
  1741. if($arg_st !== false) {
  1742. $base = substr($query, 0, $arg_st);
  1743. $arg_st += 1;
  1744. } else {
  1745. $base = '';
  1746. $arg_st = 0;
  1747. }
  1748. $args = explode('&', substr($query, $arg_st));
  1749. foreach($args as $k=>$arg) {
  1750. if($arg === '')
  1751. unset($args[$k]);
  1752. }
  1753. $args = array_values($args);
  1754. if(!$base) {
  1755. $base = $args[0];
  1756. unset($args[0]);
  1757. $args = array_values($args);
  1758. }
  1759. return array(
  1760. 'base' => $base,
  1761. 'args' => $args,
  1762. );
  1763. }
  1764. /**
  1765. * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
  1766. *
  1767. * Taken from http://webcheatsheet.com/php/get_current_page_url.php
  1768. */
  1769. function curPageURL() {
  1770. $pageURL = 'http';
  1771. if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
  1772. $pageURL .= "://";
  1773. if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
  1774. $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  1775. } else {
  1776. $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  1777. }
  1778. return $pageURL;
  1779. }
  1780. function random_digits($digits) {
  1781. $rn = '';
  1782. for($i = 0; $i < $digits; $i++) {
  1783. $rn .= rand(0,9);
  1784. }
  1785. return $rn;
  1786. }
  1787. function get_server() {
  1788. $server = get_config("system", "directory");
  1789. if ($server == "")
  1790. $server = "http://dir.friendi.ca";
  1791. return($server);
  1792. }
  1793. function get_cachefile($file, $writemode = true) {
  1794. $cache = get_itemcachepath();
  1795. if ((! $cache) || (! is_dir($cache)))
  1796. return("");
  1797. $subfolder = $cache."/".substr($file, 0, 2);
  1798. $cachepath = $subfolder."/".$file;
  1799. if ($writemode) {
  1800. if (!is_dir($subfolder)) {
  1801. mkdir($subfolder);
  1802. chmod($subfolder, 0777);
  1803. }
  1804. }
  1805. return($cachepath);
  1806. }
  1807. function clear_cache($basepath = "", $path = "") {
  1808. if ($path == "") {
  1809. $basepath = get_itemcachepath();
  1810. $path = $basepath;
  1811. }
  1812. if (($path == "") OR (!is_dir($path)))
  1813. return;
  1814. if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
  1815. return;
  1816. $cachetime = (int)get_config('system','itemcache_duration');
  1817. if ($cachetime == 0)
  1818. $cachetime = 86400;
  1819. if (is_writable($path)){
  1820. if ($dh = opendir($path)) {
  1821. while (($file = readdir($dh)) !== false) {
  1822. $fullpath = $path."/".$file;
  1823. if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
  1824. clear_cache($basepath, $fullpath);
  1825. if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
  1826. unlink($fullpath);
  1827. }
  1828. closedir($dh);
  1829. }
  1830. }
  1831. }
  1832. function get_itemcachepath() {
  1833. // Checking, if the cache is deactivated
  1834. $cachetime = (int)get_config('system','itemcache_duration');
  1835. if ($cachetime < 0)
  1836. return "";
  1837. $itemcache = get_config('system','itemcache');
  1838. if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
  1839. return($itemcache);
  1840. $temppath = get_temppath();
  1841. if ($temppath != "") {
  1842. $itemcache = $temppath."/itemcache";
  1843. if(!file_exists($itemcache) && !is_dir($itemcache)) {
  1844. mkdir($itemcache);
  1845. }
  1846. if (is_dir($itemcache) AND is_writable($itemcache)) {
  1847. set_config("system", "itemcache", $itemcache);
  1848. return($itemcache);
  1849. }
  1850. }
  1851. return "";
  1852. }
  1853. function get_lockpath() {
  1854. $lockpath = get_config('system','lockpath');
  1855. if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
  1856. return($lockpath);
  1857. $temppath = get_temppath();
  1858. if ($temppath != "") {
  1859. $lockpath = $temppath."/lock";
  1860. if (!is_dir($lockpath))
  1861. mkdir($lockpath);
  1862. elseif (!is_writable($lockpath))
  1863. $lockpath = $temppath;
  1864. if (is_dir($lockpath) AND is_writable($lockpath)) {
  1865. set_config("system", "lockpath", $lockpath);
  1866. return($lockpath);
  1867. }
  1868. }
  1869. return "";
  1870. }
  1871. function get_temppath() {
  1872. $a = get_app();
  1873. $temppath = get_config("system","temppath");
  1874. if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
  1875. return($temppath);
  1876. $temppath = sys_get_temp_dir();
  1877. if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
  1878. $temppath .= "/".$a->get_hostname();
  1879. if (!is_dir($temppath))
  1880. mkdir($temppath);
  1881. if (is_dir($temppath) AND is_writable($temppath)) {
  1882. set_config("system", "temppath", $temppath);
  1883. return($temppath);
  1884. }
  1885. }
  1886. return("");
  1887. }
  1888. function set_template_engine(&$a, $engine = 'internal') {
  1889. /// @note This function is no longer necessary, but keep it as a wrapper to the class method
  1890. /// to avoid breaking themes again unnecessarily
  1891. $a->set_template_engine($engine);
  1892. }
  1893. if(!function_exists('exif_imagetype')) {
  1894. function exif_imagetype($file) {
  1895. $size = getimagesize($file);
  1896. return($size[2]);
  1897. }
  1898. }
  1899. function validate_include(&$file) {
  1900. $orig_file = $file;
  1901. $file = realpath($file);
  1902. if (strpos($file, getcwd()) !== 0)
  1903. return false;
  1904. $file = str_replace(getcwd()."/", "", $file, $count);
  1905. if ($count != 1)
  1906. return false;
  1907. if ($orig_file !== $file)
  1908. return false;
  1909. $valid = false;
  1910. if (strpos($file, "include/") === 0)
  1911. $valid = true;
  1912. if (strpos($file, "addon/") === 0)
  1913. $valid = true;
  1914. if (!$valid)
  1915. return false;
  1916. return true;
  1917. }
  1918. function current_load() {
  1919. if (!function_exists('sys_getloadavg'))
  1920. return false;
  1921. $load_arr = sys_getloadavg();
  1922. if (!is_array($load_arr))
  1923. return false;
  1924. return max($load_arr[0], $load_arr[1]);
  1925. }
  1926. /**
  1927. * @brief get c-style args
  1928. *
  1929. * @return int
  1930. */
  1931. function argc() {
  1932. return get_app()->argc;
  1933. }
  1934. /**
  1935. * @brief Returns the value of a argv key
  1936. *
  1937. * @param int $x argv key
  1938. * @return string Value of the argv key
  1939. */
  1940. function argv($x) {
  1941. if(array_key_exists($x,get_app()->argv))
  1942. return get_app()->argv[$x];
  1943. return '';
  1944. }
  1945. /**
  1946. * @brief Get the data which is needed for infinite scroll
  1947. *
  1948. * For invinite scroll we need the page number of the actual page
  1949. * and the the URI where the content of the next page comes from.
  1950. * This data is needed for the js part in main.js.
  1951. * Note: infinite scroll does only work for the network page (module)
  1952. *
  1953. * @param string $module The name of the module (e.g. "network")
  1954. * @return array Of infinite scroll data
  1955. * 'pageno' => $pageno The number of the actual page
  1956. * 'reload_uri' => $reload_uri The URI of the content we have to load
  1957. */
  1958. function infinite_scroll_data($module) {
  1959. if (get_pconfig(local_user(),'system','infinite_scroll')
  1960. AND ($module == "network") AND ($_GET["mode"] != "minimal")) {
  1961. // get the page number
  1962. if (is_string($_GET["page"]))
  1963. $pageno = $_GET["page"];
  1964. else
  1965. $pageno = 1;
  1966. $reload_uri = "";
  1967. // try to get the uri from which we load the content
  1968. foreach ($_GET AS $param => $value)
  1969. if (($param != "page") AND ($param != "q"))
  1970. $reload_uri .= "&".$param."=".urlencode($value);
  1971. if (($a->page_offset != "") AND !strstr($reload_uri, "&offset="))
  1972. $reload_uri .= "&offset=".urlencode($a->page_offset);
  1973. $arr = array("pageno" => $pageno, "reload_uri" => $reload_uri);
  1974. return $arr;
  1975. }
  1976. }