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