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.
 
 
 
 
 
 

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