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.
 
 
 
 
 
 

2532 lines
65 KiB

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