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.
 
 
 
 
 
 

2020 lines
55 KiB

  1. <?php
  2. require_once('include/config.php');
  3. require_once('include/network.php');
  4. require_once('include/plugin.php');
  5. require_once('include/text.php');
  6. require_once('include/datetime.php');
  7. require_once('include/pgettext.php');
  8. require_once('include/nav.php');
  9. require_once('include/cache.php');
  10. require_once('library/Mobile_Detect/Mobile_Detect.php');
  11. require_once('include/features.php');
  12. define ( 'FRIENDICA_PLATFORM', 'Friendica');
  13. define ( 'FRIENDICA_VERSION', '3.1.1589' );
  14. define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
  15. define ( 'DB_UPDATE_VERSION', 1159 );
  16. define ( 'EOL', "<br />\r\n" );
  17. define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
  18. /**
  19. *
  20. * Image storage quality. Lower numbers save space at cost of image detail.
  21. * For ease of upgrade, please do not change here. Change jpeg quality with
  22. * $a->config['system']['jpeg_quality'] = n;
  23. * in .htconfig.php, where n is netween 1 and 100, and with very poor results
  24. * below about 50
  25. *
  26. */
  27. define ( 'JPEG_QUALITY', 100 );
  28. /**
  29. * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
  30. */
  31. define ( 'PNG_QUALITY', 8 );
  32. /**
  33. *
  34. * An alternate way of limiting picture upload sizes. Specify the maximum pixel
  35. * length that pictures are allowed to be (for non-square pictures, it will apply
  36. * to the longest side). Pictures longer than this length will be resized to be
  37. * this length (on the longest side, the other side will be scaled appropriately).
  38. * Modify this value using
  39. *
  40. * $a->config['system']['max_image_length'] = n;
  41. *
  42. * in .htconfig.php
  43. *
  44. * If you don't want to set a maximum length, set to -1. The default value is
  45. * defined by 'MAX_IMAGE_LENGTH' below.
  46. *
  47. */
  48. define ( 'MAX_IMAGE_LENGTH', -1 );
  49. /**
  50. * Not yet used
  51. */
  52. define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
  53. /**
  54. * SSL redirection policies
  55. */
  56. define ( 'SSL_POLICY_NONE', 0 );
  57. define ( 'SSL_POLICY_FULL', 1 );
  58. define ( 'SSL_POLICY_SELFSIGN', 2 );
  59. /**
  60. * log levels
  61. */
  62. define ( 'LOGGER_NORMAL', 0 );
  63. define ( 'LOGGER_TRACE', 1 );
  64. define ( 'LOGGER_DEBUG', 2 );
  65. define ( 'LOGGER_DATA', 3 );
  66. define ( 'LOGGER_ALL', 4 );
  67. /**
  68. * registration policies
  69. */
  70. define ( 'REGISTER_CLOSED', 0 );
  71. define ( 'REGISTER_APPROVE', 1 );
  72. define ( 'REGISTER_OPEN', 2 );
  73. /**
  74. * relationship types
  75. */
  76. define ( 'CONTACT_IS_FOLLOWER', 1);
  77. define ( 'CONTACT_IS_SHARING', 2);
  78. define ( 'CONTACT_IS_FRIEND', 3);
  79. /**
  80. * DB update return values
  81. */
  82. define ( 'UPDATE_SUCCESS', 0);
  83. define ( 'UPDATE_FAILED', 1);
  84. /**
  85. *
  86. * page/profile types
  87. *
  88. * PAGE_NORMAL is a typical personal profile account
  89. * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
  90. * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
  91. * write access to wall and comments (no email and not included in page owner's ACL lists)
  92. * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
  93. *
  94. */
  95. define ( 'PAGE_NORMAL', 0 );
  96. define ( 'PAGE_SOAPBOX', 1 );
  97. define ( 'PAGE_COMMUNITY', 2 );
  98. define ( 'PAGE_FREELOVE', 3 );
  99. define ( 'PAGE_BLOG', 4 );
  100. define ( 'PAGE_PRVGROUP', 5 );
  101. /**
  102. * Network and protocol family types
  103. */
  104. define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
  105. define ( 'NETWORK_ZOT', 'zot!'); // Zot!
  106. define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
  107. define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
  108. define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
  109. define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
  110. define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
  111. define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
  112. define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
  113. define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
  114. define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
  115. define ( 'NETWORK_GPLUS', 'goog'); // Google+
  116. define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
  117. /**
  118. * These numbers are used in stored permissions
  119. * and existing allocations MUST NEVER BE CHANGED
  120. * OR RE-ASSIGNED! You may only add to them.
  121. */
  122. $netgroup_ids = array(
  123. NETWORK_DFRN => (-1),
  124. NETWORK_ZOT => (-2),
  125. NETWORK_OSTATUS => (-3),
  126. NETWORK_FEED => (-4),
  127. NETWORK_DIASPORA => (-5),
  128. NETWORK_MAIL => (-6),
  129. NETWORK_MAIL2 => (-7),
  130. NETWORK_FACEBOOK => (-8),
  131. NETWORK_LINKEDIN => (-9),
  132. NETWORK_XMPP => (-10),
  133. NETWORK_MYSPACE => (-11),
  134. NETWORK_GPLUS => (-12),
  135. NETWORK_PHANTOM => (-127),
  136. );
  137. /**
  138. * Maximum number of "people who like (or don't like) this" that we will list by name
  139. */
  140. define ( 'MAX_LIKERS', 75);
  141. /**
  142. * Communication timeout
  143. */
  144. define ( 'ZCURL_TIMEOUT' , (-1));
  145. /**
  146. * email notification options
  147. */
  148. define ( 'NOTIFY_INTRO', 0x0001 );
  149. define ( 'NOTIFY_CONFIRM', 0x0002 );
  150. define ( 'NOTIFY_WALL', 0x0004 );
  151. define ( 'NOTIFY_COMMENT', 0x0008 );
  152. define ( 'NOTIFY_MAIL', 0x0010 );
  153. define ( 'NOTIFY_SUGGEST', 0x0020 );
  154. define ( 'NOTIFY_PROFILE', 0x0040 );
  155. define ( 'NOTIFY_TAGSELF', 0x0080 );
  156. define ( 'NOTIFY_TAGSHARE', 0x0100 );
  157. define ( 'NOTIFY_POKE', 0x0200 );
  158. define ( 'NOTIFY_SYSTEM', 0x8000 );
  159. /**
  160. * Tag/term types
  161. */
  162. define ( 'TERM_UNKNOWN', 0 );
  163. define ( 'TERM_HASHTAG', 1 );
  164. define ( 'TERM_MENTION', 2 );
  165. define ( 'TERM_CATEGORY', 3 );
  166. define ( 'TERM_PCATEGORY', 4 );
  167. define ( 'TERM_FILE', 5 );
  168. define ( 'TERM_SAVEDSEARCH', 6 );
  169. define ( 'TERM_OBJ_POST', 1 );
  170. define ( 'TERM_OBJ_PHOTO', 2 );
  171. /**
  172. * various namespaces we may need to parse
  173. */
  174. define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
  175. define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
  176. define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
  177. define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
  178. define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
  179. define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
  180. define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
  181. define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
  182. define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
  183. define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
  184. define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
  185. define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
  186. define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
  187. define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
  188. define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
  189. /**
  190. * activity stream defines
  191. */
  192. define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
  193. define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
  194. define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
  195. define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
  196. define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
  197. define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
  198. define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
  199. define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
  200. define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
  201. define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
  202. define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
  203. define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
  204. define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
  205. define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
  206. define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
  207. define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
  208. define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
  209. define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
  210. define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
  211. define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
  212. define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
  213. define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
  214. define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
  215. define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
  216. define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
  217. /**
  218. * item weight for query ordering
  219. */
  220. define ( 'GRAVITY_PARENT', 0);
  221. define ( 'GRAVITY_LIKE', 3);
  222. define ( 'GRAVITY_COMMENT', 6);
  223. /**
  224. *
  225. * Reverse the effect of magic_quotes_gpc if it is enabled.
  226. * Please disable magic_quotes_gpc so we don't have to do this.
  227. * See http://php.net/manual/en/security.magicquotes.disabling.php
  228. *
  229. */
  230. function startup() {
  231. error_reporting(E_ERROR | E_WARNING | E_PARSE);
  232. set_time_limit(0);
  233. // This has to be quite large to deal with embedded private photos
  234. ini_set('pcre.backtrack_limit', 500000);
  235. if (get_magic_quotes_gpc()) {
  236. $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
  237. while (list($key, $val) = each($process)) {
  238. foreach ($val as $k => $v) {
  239. unset($process[$key][$k]);
  240. if (is_array($v)) {
  241. $process[$key][stripslashes($k)] = $v;
  242. $process[] = &$process[$key][stripslashes($k)];
  243. } else {
  244. $process[$key][stripslashes($k)] = stripslashes($v);
  245. }
  246. }
  247. }
  248. unset($process);
  249. }
  250. }
  251. /**
  252. *
  253. * class: App
  254. *
  255. * Our main application structure for the life of this page
  256. * Primarily deals with the URL that got us here
  257. * and tries to make some sense of it, and
  258. * stores our page contents and config storage
  259. * and anything else that might need to be passed around
  260. * before we spit the page out.
  261. *
  262. */
  263. if(! class_exists('App')) {
  264. class App {
  265. public $module_loaded = false;
  266. public $query_string;
  267. public $config;
  268. public $page;
  269. public $profile;
  270. public $user;
  271. public $cid;
  272. public $contact;
  273. public $contacts;
  274. public $page_contact;
  275. public $content;
  276. public $data = array();
  277. public $error = false;
  278. public $cmd;
  279. public $argv;
  280. public $argc;
  281. public $module;
  282. public $pager;
  283. public $strings;
  284. public $path;
  285. public $hooks;
  286. public $timezone;
  287. public $interactive = true;
  288. public $plugins;
  289. public $apps = array();
  290. public $identities;
  291. public $is_mobile;
  292. public $is_tablet;
  293. public $performance = array();
  294. public $nav_sel;
  295. public $category;
  296. // Allow themes to control internal parameters
  297. // by changing App values in theme.php
  298. public $sourcename = '';
  299. public $videowidth = 425;
  300. public $videoheight = 350;
  301. public $force_max_items = 0;
  302. public $theme_thread_allow = true;
  303. // An array for all theme-controllable parameters
  304. // Mostly unimplemented yet. Only options 'stylesheet' and
  305. // beyond are used.
  306. public $theme = array(
  307. 'sourcename' => '',
  308. 'videowidth' => 425,
  309. 'videoheight' => 350,
  310. 'force_max_items' => 0,
  311. 'thread_allow' => true,
  312. 'stylesheet' => '',
  313. 'template_engine' => 'internal',
  314. );
  315. private $ldelim = array(
  316. 'internal' => '',
  317. 'smarty3' => '{{'
  318. );
  319. private $rdelim = array(
  320. 'internal' => '',
  321. 'smarty3' => '}}'
  322. );
  323. private $scheme;
  324. private $hostname;
  325. private $baseurl;
  326. private $db;
  327. private $curl_code;
  328. private $curl_headers;
  329. private $cached_profile_image;
  330. private $cached_profile_picdate;
  331. function __construct() {
  332. global $default_timezone, $argv, $argc;
  333. $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
  334. date_default_timezone_set($this->timezone);
  335. $this->performance["start"] = microtime(true);
  336. $this->performance["database"] = 0;
  337. $this->performance["network"] = 0;
  338. $this->performance["rendering"] = 0;
  339. $this->performance["parser"] = 0;
  340. $this->performance["marktime"] = 0;
  341. $this->performance["markstart"] = microtime(true);
  342. $this->config = array();
  343. $this->page = array();
  344. $this->pager= array();
  345. $this->query_string = '';
  346. startup();
  347. $this->scheme = 'http';
  348. if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
  349. $this->scheme = 'https';
  350. elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
  351. $this->scheme = 'https';
  352. if(x($_SERVER,'SERVER_NAME')) {
  353. $this->hostname = $_SERVER['SERVER_NAME'];
  354. // See bug 437 - this didn't work so disabling it
  355. //if(stristr($this->hostname,'xn--')) {
  356. // PHP or webserver may have converted idn to punycode, so
  357. // convert punycode back to utf-8
  358. // require_once('library/simplepie/idn/idna_convert.class.php');
  359. // $x = new idna_convert();
  360. // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
  361. //}
  362. if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
  363. $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
  364. /**
  365. * Figure out if we are running at the top of a domain
  366. * or in a sub-directory and adjust accordingly
  367. */
  368. $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
  369. if(isset($path) && strlen($path) && ($path != $this->path))
  370. $this->path = $path;
  371. }
  372. if (is_array($argv) && $argc>1 && substr(end($argv), 0, 4)=="http" ) {
  373. $this->set_baseurl(array_pop($argv) );
  374. $argc --;
  375. }
  376. set_include_path(
  377. "include/$this->hostname" . PATH_SEPARATOR
  378. . 'include' . PATH_SEPARATOR
  379. . 'library' . PATH_SEPARATOR
  380. . 'library/phpsec' . PATH_SEPARATOR
  381. . 'library/langdet' . PATH_SEPARATOR
  382. . '.' );
  383. if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
  384. $this->query_string = substr($_SERVER['QUERY_STRING'],2);
  385. // removing trailing / - maybe a nginx problem
  386. if (substr($this->query_string, 0, 1) == "/")
  387. $this->query_string = substr($this->query_string, 1);
  388. }
  389. if(x($_GET,'q'))
  390. $this->cmd = trim($_GET['q'],'/\\');
  391. // unix style "homedir"
  392. if(substr($this->cmd,0,1) === '~')
  393. $this->cmd = 'profile/' . substr($this->cmd,1);
  394. // Diaspora style profile url
  395. if(substr($this->cmd,0,2) === 'u/')
  396. $this->cmd = 'profile/' . substr($this->cmd,2);
  397. /**
  398. *
  399. * Break the URL path into C style argc/argv style arguments for our
  400. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  401. * will be 3 (integer) and $this->argv will contain:
  402. * [0] => 'module'
  403. * [1] => 'arg1'
  404. * [2] => 'arg2'
  405. *
  406. *
  407. * There will always be one argument. If provided a naked domain
  408. * URL, $this->argv[0] is set to "home".
  409. *
  410. */
  411. $this->argv = explode('/',$this->cmd);
  412. $this->argc = count($this->argv);
  413. if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
  414. $this->module = str_replace(".", "_", $this->argv[0]);
  415. $this->module = str_replace("-", "_", $this->module);
  416. }
  417. else {
  418. $this->argc = 1;
  419. $this->argv = array('home');
  420. $this->module = 'home';
  421. }
  422. /**
  423. * See if there is any page number information, and initialise
  424. * pagination
  425. */
  426. $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
  427. $this->pager['itemspage'] = 50;
  428. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  429. if($this->pager['start'] < 0)
  430. $this->pager['start'] = 0;
  431. $this->pager['total'] = 0;
  432. /**
  433. * Detect mobile devices
  434. */
  435. $mobile_detect = new Mobile_Detect();
  436. $this->is_mobile = $mobile_detect->isMobile();
  437. $this->is_tablet = $mobile_detect->isTablet();
  438. }
  439. function get_basepath() {
  440. $basepath = get_config("system", "basepath");
  441. if ($basepath == "")
  442. $basepath = $_SERVER["DOCUMENT_ROOT"];
  443. if ($basepath == "")
  444. $basepath = $_SERVER["PWD"];
  445. return($basepath);
  446. }
  447. function get_baseurl($ssl = false) {
  448. $scheme = $this->scheme;
  449. if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
  450. if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
  451. $scheme = 'https';
  452. // Basically, we have $ssl = true on any links which can only be seen by a logged in user
  453. // (and also the login link). Anything seen by an outsider will have it turned off.
  454. if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
  455. if($ssl)
  456. $scheme = 'https';
  457. else
  458. $scheme = 'http';
  459. }
  460. }
  461. $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
  462. return $this->baseurl;
  463. }
  464. function set_baseurl($url) {
  465. $parsed = @parse_url($url);
  466. $this->baseurl = $url;
  467. if($parsed) {
  468. $this->scheme = $parsed['scheme'];
  469. $this->hostname = $parsed['host'];
  470. if(x($parsed,'port'))
  471. $this->hostname .= ':' . $parsed['port'];
  472. if(x($parsed,'path'))
  473. $this->path = trim($parsed['path'],'\\/');
  474. }
  475. }
  476. function get_hostname() {
  477. return $this->hostname;
  478. }
  479. function set_hostname($h) {
  480. $this->hostname = $h;
  481. }
  482. function set_path($p) {
  483. $this->path = trim(trim($p),'/');
  484. }
  485. function get_path() {
  486. return $this->path;
  487. }
  488. function set_pager_total($n) {
  489. $this->pager['total'] = intval($n);
  490. }
  491. function set_pager_itemspage($n) {
  492. $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
  493. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  494. }
  495. function init_pagehead() {
  496. $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
  497. if($interval < 10000)
  498. $interval = 40000;
  499. $this->page['title'] = $this->config['sitename'];
  500. /* put the head template at the beginning of page['htmlhead']
  501. * since the code added by the modules frequently depends on it
  502. * being first
  503. */
  504. if(!isset($this->page['htmlhead']))
  505. $this->page['htmlhead'] = '';
  506. // If we're using Smarty, then doing replace_macros() will replace
  507. // any unrecognized variables with a blank string. Since we delay
  508. // replacing $stylesheet until later, we need to replace it now
  509. // with another variable name
  510. if($this->theme['template_engine'] === 'smarty3')
  511. $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
  512. else
  513. $stylesheet = '$stylesheet';
  514. $tpl = get_markup_template('head.tpl');
  515. $this->page['htmlhead'] = replace_macros($tpl,array(
  516. '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
  517. '$local_user' => local_user(),
  518. '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
  519. '$delitem' => t('Delete this item?'),
  520. '$comment' => t('Comment'),
  521. '$showmore' => t('show more'),
  522. '$showfewer' => t('show fewer'),
  523. '$update_interval' => $interval,
  524. '$stylesheet' => $stylesheet
  525. )) . $this->page['htmlhead'];
  526. }
  527. function init_page_end() {
  528. if(!isset($this->page['end']))
  529. $this->page['end'] = '';
  530. $tpl = get_markup_template('end.tpl');
  531. $this->page['end'] = replace_macros($tpl,array(
  532. '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
  533. )) . $this->page['end'];
  534. }
  535. function set_curl_code($code) {
  536. $this->curl_code = $code;
  537. }
  538. function get_curl_code() {
  539. return $this->curl_code;
  540. }
  541. function set_curl_headers($headers) {
  542. $this->curl_headers = $headers;
  543. }
  544. function get_curl_headers() {
  545. return $this->curl_headers;
  546. }
  547. function get_cached_avatar_image($avatar_image){
  548. if($this->cached_profile_image[$avatar_image])
  549. return $this->cached_profile_image[$avatar_image];
  550. $path_parts = explode("/",$avatar_image);
  551. $common_filename = $path_parts[count($path_parts)-1];
  552. if($this->cached_profile_picdate[$common_filename]){
  553. $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
  554. } else {
  555. $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like \"%%/%s\"",
  556. $common_filename);
  557. if(! count($r)){
  558. $this->cached_profile_image[$avatar_image] = $avatar_image;
  559. } else {
  560. $this->cached_profile_picdate[$common_filename] = "?rev=" . urlencode($r[0]['picdate']);
  561. $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
  562. }
  563. }
  564. return $this->cached_profile_image[$avatar_image];
  565. }
  566. function get_template_engine() {
  567. return $this->theme['template_engine'];
  568. }
  569. function set_template_engine($engine = 'internal') {
  570. $this->theme['template_engine'] = 'internal';
  571. switch($engine) {
  572. case 'smarty3':
  573. if(is_writable('view/smarty3/'))
  574. $this->theme['template_engine'] = 'smarty3';
  575. break;
  576. default:
  577. break;
  578. }
  579. }
  580. function get_template_ldelim($engine = 'internal') {
  581. return $this->ldelim[$engine];
  582. }
  583. function get_template_rdelim($engine = 'internal') {
  584. return $this->rdelim[$engine];
  585. }
  586. function save_timestamp($stamp, $value) {
  587. $duration = (float)(microtime(true)-$stamp);
  588. $this->performance[$value] += (float)$duration;
  589. $this->performance["marktime"] += (float)$duration;
  590. }
  591. function mark_timestamp($mark) {
  592. //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
  593. $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
  594. }
  595. }
  596. }
  597. // retrieve the App structure
  598. // useful in functions which require it but don't get it passed to them
  599. if(! function_exists('get_app')) {
  600. function get_app() {
  601. global $a;
  602. return $a;
  603. }
  604. };
  605. // Multi-purpose function to check variable state.
  606. // Usage: x($var) or $x($array,'key')
  607. // returns false if variable/key is not set
  608. // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
  609. // e.g. x('') or x(0) returns 0;
  610. if(! function_exists('x')) {
  611. function x($s,$k = NULL) {
  612. if($k != NULL) {
  613. if((is_array($s)) && (array_key_exists($k,$s))) {
  614. if($s[$k])
  615. return (int) 1;
  616. return (int) 0;
  617. }
  618. return false;
  619. }
  620. else {
  621. if(isset($s)) {
  622. if($s) {
  623. return (int) 1;
  624. }
  625. return (int) 0;
  626. }
  627. return false;
  628. }
  629. }
  630. }
  631. // called from db initialisation if db is dead.
  632. if(! function_exists('system_unavailable')) {
  633. function system_unavailable() {
  634. include('system_unavailable.php');
  635. system_down();
  636. killme();
  637. }
  638. }
  639. function clean_urls() {
  640. global $a;
  641. // if($a->config['system']['clean_urls'])
  642. return true;
  643. // return false;
  644. }
  645. function z_path() {
  646. global $a;
  647. $base = $a->get_baseurl();
  648. if(! clean_urls())
  649. $base .= '/?q=';
  650. return $base;
  651. }
  652. function z_root() {
  653. global $a;
  654. return $a->get_baseurl();
  655. }
  656. function absurl($path) {
  657. if(strpos($path,'/') === 0)
  658. return z_path() . $path;
  659. return $path;
  660. }
  661. function is_ajax() {
  662. return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
  663. }
  664. // Primarily involved with database upgrade, but also sets the
  665. // base url for use in cmdline programs which don't have
  666. // $_SERVER variables
  667. if(! function_exists('check_config')) {
  668. function check_config(&$a) {
  669. $url = get_config('system','url');
  670. // if the url isn't set or the stored url is radically different
  671. // than the currently visited url, store the current value accordingly.
  672. // "Radically different" ignores common variations such as http vs https
  673. // and www.example.com vs example.com.
  674. // We will only change the url to an ip address if there is no existing setting
  675. if(! x($url))
  676. $url = set_config('system','url',$a->get_baseurl());
  677. if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
  678. $url = set_config('system','url',$a->get_baseurl());
  679. $build = get_config('system','build');
  680. if(! x($build))
  681. $build = set_config('system','build',DB_UPDATE_VERSION);
  682. if($build != DB_UPDATE_VERSION) {
  683. $stored = intval($build);
  684. $current = intval(DB_UPDATE_VERSION);
  685. if(($stored < $current) && file_exists('update.php')) {
  686. load_config('database');
  687. // We're reporting a different version than what is currently installed.
  688. // Run any existing update scripts to bring the database up to current.
  689. require_once('update.php');
  690. // make sure that boot.php and update.php are the same release, we might be
  691. // updating right this very second and the correct version of the update.php
  692. // file may not be here yet. This can happen on a very busy site.
  693. if(DB_UPDATE_VERSION == UPDATE_VERSION) {
  694. for($x = $stored; $x < $current; $x ++) {
  695. if(function_exists('update_' . $x)) {
  696. // There could be a lot of processes running or about to run.
  697. // We want exactly one process to run the update command.
  698. // So store the fact that we're taking responsibility
  699. // after first checking to see if somebody else already has.
  700. // If the update fails or times-out completely you may need to
  701. // delete the config entry to try again.
  702. $t = get_config('database','update_' . $x);
  703. if($t !== false)
  704. break;
  705. set_config('database','update_' . $x, time());
  706. // call the specific update
  707. $func = 'update_' . $x;
  708. $retval = $func();
  709. if($retval) {
  710. //send the administrator an e-mail
  711. $email_tpl = get_intltext_template("update_fail_eml.tpl");
  712. $email_msg = replace_macros($email_tpl, array(
  713. '$sitename' => $a->config['sitename'],
  714. '$siteurl' => $a->get_baseurl(),
  715. '$update' => $x,
  716. '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
  717. ));
  718. $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
  719. require_once('include/email.php');
  720. $subject = email_header_encode($subject,'UTF-8');
  721. mail($a->config['admin_email'], $subject, $email_msg,
  722. 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
  723. . 'Content-type: text/plain; charset=UTF-8' . "\n"
  724. . 'Content-transfer-encoding: 8bit' );
  725. //try the logger
  726. logger('CRITICAL: Update Failed: '. $x);
  727. break;
  728. }
  729. else {
  730. set_config('database','update_' . $x, 'success');
  731. set_config('system','build', $x + 1);
  732. }
  733. }
  734. }
  735. }
  736. }
  737. }
  738. return;
  739. }
  740. }
  741. if(! function_exists('check_plugins')) {
  742. function check_plugins(&$a) {
  743. /**
  744. *
  745. * Synchronise plugins:
  746. *
  747. * $a->config['system']['addon'] contains a comma-separated list of names
  748. * of plugins/addons which are used on this system.
  749. * Go through the database list of already installed addons, and if we have
  750. * an entry, but it isn't in the config list, call the uninstall procedure
  751. * and mark it uninstalled in the database (for now we'll remove it).
  752. * Then go through the config list and if we have a plugin that isn't installed,
  753. * call the install procedure and add it to the database.
  754. *
  755. */
  756. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  757. if(count($r))
  758. $installed = $r;
  759. else
  760. $installed = array();
  761. $plugins = get_config('system','addon');
  762. $plugins_arr = array();
  763. if($plugins)
  764. $plugins_arr = explode(',',str_replace(' ', '',$plugins));
  765. $a->plugins = $plugins_arr;
  766. $installed_arr = array();
  767. if(count($installed)) {
  768. foreach($installed as $i) {
  769. if(! in_array($i['name'],$plugins_arr)) {
  770. uninstall_plugin($i['name']);
  771. }
  772. else {
  773. $installed_arr[] = $i['name'];
  774. }
  775. }
  776. }
  777. if(count($plugins_arr)) {
  778. foreach($plugins_arr as $p) {
  779. if(! in_array($p,$installed_arr)) {
  780. install_plugin($p);
  781. }
  782. }
  783. }
  784. load_hooks();
  785. return;
  786. }
  787. }
  788. function get_guid($size=16) {
  789. $exists = true; // assume by default that we don't have a unique guid
  790. do {
  791. $s = random_string($size);
  792. $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
  793. if(! count($r))
  794. $exists = false;
  795. } while($exists);
  796. q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
  797. return $s;
  798. }
  799. // wrapper for adding a login box. If $register == true provide a registration
  800. // link. This will most always depend on the value of $a->config['register_policy'].
  801. // returns the complete html for inserting into the page
  802. if(! function_exists('login')) {
  803. function login($register = false, $hiddens=false) {
  804. $a = get_app();
  805. $o = "";
  806. $reg = false;
  807. if ($register) {
  808. $reg = array(
  809. 'title' => t('Create a New Account'),
  810. 'desc' => t('Register')
  811. );
  812. }
  813. $noid = get_config('system','no_openid');
  814. $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
  815. if(local_user()) {
  816. $tpl = get_markup_template("logout.tpl");
  817. }
  818. else {
  819. $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
  820. '$baseurl' => $a->get_baseurl(true)
  821. ));
  822. $tpl = get_markup_template("login.tpl");
  823. $_SESSION['return_url'] = $a->query_string;
  824. $a->module = 'login';
  825. }
  826. $o .= replace_macros($tpl, array(
  827. '$dest_url' => $dest_url,
  828. '$logout' => t('Logout'),
  829. '$login' => t('Login'),
  830. '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
  831. '$lpassword' => array('password', t('Password: '), '', ''),
  832. '$lremember' => array('remember', t('Remember me'), 0, ''),
  833. '$openid' => !$noid,
  834. '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
  835. '$hiddens' => $hiddens,
  836. '$register' => $reg,
  837. '$lostpass' => t('Forgot your password?'),
  838. '$lostlink' => t('Password Reset'),
  839. '$tostitle' => t('Website Terms of Service'),
  840. '$toslink' => t('terms of service'),
  841. '$privacytitle' => t('Website Privacy Policy'),
  842. '$privacylink' => t('privacy policy'),
  843. ));
  844. call_hooks('login_hook',$o);
  845. return $o;
  846. }
  847. }
  848. // Used to end the current process, after saving session state.
  849. if(! function_exists('killme')) {
  850. function killme() {
  851. session_write_close();
  852. exit;
  853. }
  854. }
  855. // redirect to another URL and terminate this process.
  856. if(! function_exists('goaway')) {
  857. function goaway($s) {
  858. header("Location: $s");
  859. killme();
  860. }
  861. }
  862. // Returns the uid of locally logged in user or false.
  863. if(! function_exists('local_user')) {
  864. function local_user() {
  865. if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
  866. return intval($_SESSION['uid']);
  867. return false;
  868. }
  869. }
  870. // Returns contact id of authenticated site visitor or false
  871. if(! function_exists('remote_user')) {
  872. function remote_user() {
  873. if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
  874. return intval($_SESSION['visitor_id']);
  875. return false;
  876. }
  877. }
  878. // contents of $s are displayed prominently on the page the next time
  879. // a page is loaded. Usually used for errors or alerts.
  880. if(! function_exists('notice')) {
  881. /**
  882. * Show an error message to user.
  883. *
  884. * This function save text in session, to be shown to the user at next page load
  885. *
  886. * @param string $s - Text of notice
  887. */
  888. function notice($s) {
  889. $a = get_app();
  890. if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
  891. if($a->interactive)
  892. $_SESSION['sysmsg'][] = $s;
  893. }
  894. }
  895. if(! function_exists('info')) {
  896. /**
  897. * Show an info message to user.
  898. *
  899. * This function save text in session, to be shown to the user at next page load
  900. *
  901. * @param string $s - Text of notice
  902. */
  903. function info($s) {
  904. $a = get_app();
  905. if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
  906. if($a->interactive)
  907. $_SESSION['sysmsg_info'][] = $s;
  908. }
  909. }
  910. // wrapper around config to limit the text length of an incoming message
  911. if(! function_exists('get_max_import_size')) {
  912. function get_max_import_size() {
  913. global $a;
  914. return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
  915. }
  916. }
  917. /**
  918. *
  919. * Function : profile_load
  920. * @parameter App $a
  921. * @parameter string $nickname
  922. * @parameter int $profile
  923. *
  924. * Summary: Loads a profile into the page sidebar.
  925. * The function requires a writeable copy of the main App structure, and the nickname
  926. * of a registered local account.
  927. *
  928. * If the viewer is an authenticated remote viewer, the profile displayed is the
  929. * one that has been configured for his/her viewing in the Contact manager.
  930. * Passing a non-zero profile ID can also allow a preview of a selected profile
  931. * by the owner.
  932. *
  933. * Profile information is placed in the App structure for later retrieval.
  934. * Honours the owner's chosen theme for display.
  935. *
  936. * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
  937. * the theme is chosen before the _init() function of a theme is run, which will usually
  938. * load a lot of theme-specific content
  939. *
  940. */
  941. if(! function_exists('profile_load')) {
  942. function profile_load(&$a, $nickname, $profile = 0) {
  943. $user = q("select uid from user where nickname = '%s' limit 1",
  944. dbesc($nickname)
  945. );
  946. if(! ($user && count($user))) {
  947. logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
  948. notice( t('Requested account is not available.') . EOL );
  949. $a->error = 404;
  950. return;
  951. }
  952. if(remote_user() && count($_SESSION['remote'])) {
  953. foreach($_SESSION['remote'] as $visitor) {
  954. if($visitor['uid'] == $user[0]['uid']) {
  955. $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
  956. intval($visitor['cid'])
  957. );
  958. if(count($r))
  959. $profile = $r[0]['profile-id'];
  960. break;
  961. }
  962. }
  963. }
  964. $r = null;
  965. if($profile) {
  966. $profile_int = intval($profile);
  967. $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
  968. left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
  969. WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
  970. dbesc($nickname),
  971. intval($profile_int)
  972. );
  973. }
  974. if((! $r) && (! count($r))) {
  975. $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
  976. left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
  977. WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
  978. dbesc($nickname)
  979. );
  980. }
  981. if(($r === false) || (! count($r))) {
  982. logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
  983. notice( t('Requested profile is not available.') . EOL );
  984. $a->error = 404;
  985. return;
  986. }
  987. // fetch user tags if this isn't the default profile
  988. if(! $r[0]['is-default']) {
  989. $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
  990. intval($r[0]['profile_uid'])
  991. );
  992. if($x && count($x))
  993. $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
  994. }
  995. $a->profile = $r[0];
  996. $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
  997. $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
  998. $_SESSION['theme'] = $a->profile['theme'];
  999. $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
  1000. /**
  1001. * load/reload current theme info
  1002. */
  1003. $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
  1004. $theme_info_file = "view/theme/".current_theme()."/theme.php";
  1005. if (file_exists($theme_info_file)){
  1006. require_once($theme_info_file);
  1007. }
  1008. if(! (x($a->page,'aside')))
  1009. $a->page['aside'] = '';
  1010. if(local_user() && local_user() == $a->profile['uid']) {
  1011. $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
  1012. '$editprofile' => t('Edit profile'),
  1013. '$profid' => $a->profile['id']
  1014. ));
  1015. }
  1016. $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
  1017. $a->page['aside'] .= profile_sidebar($a->profile, $block);
  1018. /*if(! $block)
  1019. $a->page['aside'] .= contact_block();*/
  1020. return;
  1021. }
  1022. }
  1023. /**
  1024. *
  1025. * Function: profile_sidebar
  1026. *
  1027. * Formats a profile for display in the sidebar.
  1028. * It is very difficult to templatise the HTML completely
  1029. * because of all the conditional logic.
  1030. *
  1031. * @parameter: array $profile
  1032. *
  1033. * Returns HTML string stuitable for sidebar inclusion
  1034. * Exceptions: Returns empty string if passed $profile is wrong type or not populated
  1035. *
  1036. */
  1037. if(! function_exists('profile_sidebar')) {
  1038. function profile_sidebar($profile, $block = 0) {
  1039. $a = get_app();
  1040. $o = '';
  1041. $location = false;
  1042. $address = false;
  1043. $pdesc = true;
  1044. if((! is_array($profile)) && (! count($profile)))
  1045. return $o;
  1046. $profile['picdate'] = urlencode($profile['picdate']);
  1047. call_hooks('profile_sidebar_enter', $profile);
  1048. // don't show connect link to yourself
  1049. $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
  1050. // don't show connect link to authenticated visitors either
  1051. if(remote_user() && count($_SESSION['remote'])) {
  1052. foreach($_SESSION['remote'] as $visitor) {
  1053. if($visitor['uid'] == $profile['uid']) {
  1054. $connect = false;
  1055. break;
  1056. }
  1057. }
  1058. }
  1059. if(get_my_url() && $profile['unkmail'])
  1060. $wallmessage = t('Message');
  1061. else
  1062. $wallmessage = false;
  1063. // show edit profile to yourself
  1064. if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
  1065. $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
  1066. $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
  1067. local_user());
  1068. $profile['menu'] = array(
  1069. 'chg_photo' => t('Change profile photo'),
  1070. 'cr_new' => t('Create New Profile'),
  1071. 'entries' => array(),
  1072. );
  1073. if(count($r)) {
  1074. foreach($r as $rr) {
  1075. $profile['menu']['entries'][] = array(
  1076. 'photo' => $rr['thumb'],
  1077. 'id' => $rr['id'],
  1078. 'alt' => t('Profile Image'),
  1079. 'profile_name' => $rr['profile-name'],
  1080. 'isdefault' => $rr['is-default'],
  1081. 'visibile_to_everybody' => t('visible to everybody'),
  1082. 'edit_visibility' => t('Edit visibility'),
  1083. );
  1084. }
  1085. }
  1086. }
  1087. if((x($profile,'address') == 1)
  1088. || (x($profile,'locality') == 1)
  1089. || (x($profile,'region') == 1)
  1090. || (x($profile,'postal-code') == 1)
  1091. || (x($profile,'country-name') == 1))
  1092. $location = t('Location:');
  1093. $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
  1094. $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
  1095. $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
  1096. if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
  1097. $location = $pdesc = $gender = $marital = $homepage = False;
  1098. }
  1099. $firstname = ((strpos($profile['name'],' '))
  1100. ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
  1101. $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
  1102. $diaspora = array(
  1103. 'podloc' => $a->get_baseurl(),
  1104. 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
  1105. 'nickname' => $profile['nickname'],
  1106. 'fullname' => $profile['name'],
  1107. 'firstname' => $firstname,
  1108. 'lastname' => $lastname,
  1109. 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
  1110. 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
  1111. 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
  1112. );
  1113. if (!$block){
  1114. $contact_block = contact_block();
  1115. }
  1116. $p = array();
  1117. foreach($profile as $k => $v) {
  1118. $k = str_replace('-','_',$k);
  1119. $p[$k] = $v;
  1120. }
  1121. if($a->theme['template_engine'] === 'internal')
  1122. $location = template_escape($location);
  1123. $tpl = get_markup_template('profile_vcard.tpl');
  1124. $o .= replace_macros($tpl, array(
  1125. '$profile' => $p,
  1126. '$connect' => $connect,
  1127. '$wallmessage' => $wallmessage,
  1128. '$location' => $location,
  1129. '$gender' => $gender,
  1130. '$pdesc' => $pdesc,
  1131. '$marital' => $marital,
  1132. '$homepage' => $homepage,
  1133. '$diaspora' => $diaspora,
  1134. '$contact_block' => $contact_block,
  1135. ));
  1136. $arr = array('profile' => &$profile, 'entry' => &$o);
  1137. call_hooks('profile_sidebar', $arr);
  1138. return $o;
  1139. }
  1140. }
  1141. if(! function_exists('get_birthdays')) {
  1142. function get_birthdays() {
  1143. $a = get_app();
  1144. $o = '';
  1145. if(! local_user() || $a->is_mobile || $a->is_tablet)
  1146. return $o;
  1147. // $mobile_detect = new Mobile_Detect();
  1148. // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
  1149. // if($is_mobile)
  1150. // return $o;
  1151. $bd_format = t('g A l F d') ; // 8 AM Friday January 18
  1152. $bd_short = t('F d');
  1153. $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
  1154. LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid`
  1155. WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
  1156. ORDER BY `start` ASC ",
  1157. intval(local_user()),
  1158. dbesc(datetime_convert('UTC','UTC','now + 6 days')),
  1159. dbesc(datetime_convert('UTC','UTC','now'))
  1160. );
  1161. if($r && count($r)) {
  1162. $total = 0;
  1163. $now = strtotime('now');
  1164. $cids = array();
  1165. $istoday = false;
  1166. foreach($r as $rr) {
  1167. if(strlen($rr['name']))
  1168. $total ++;
  1169. if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
  1170. $istoday = true;
  1171. }
  1172. $classtoday = $istoday ? ' birthday-today ' : '';
  1173. if($total) {
  1174. foreach($r as &$rr) {
  1175. if(! strlen($rr['name']))
  1176. continue;
  1177. // avoid duplicates
  1178. if(in_array($rr['cid'],$cids))
  1179. continue;
  1180. $cids[] = $rr['cid'];
  1181. $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
  1182. $sparkle = '';
  1183. $url = $rr['url'];
  1184. if($rr['network'] === NETWORK_DFRN) {
  1185. $sparkle = " sparkle";
  1186. $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
  1187. }
  1188. $rr['link'] = $url;
  1189. $rr['title'] = $rr['name'];
  1190. $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
  1191. $rr['startime'] = Null;
  1192. $rr['today'] = $today;
  1193. }
  1194. }
  1195. }
  1196. $tpl = get_markup_template("birthdays_reminder.tpl");
  1197. return replace_macros($tpl, array(
  1198. '$baseurl' => $a->get_baseurl(),
  1199. '$classtoday' => $classtoday,
  1200. '$count' => $total,
  1201. '$event_reminders' => t('Birthday Reminders'),
  1202. '$event_title' => t('Birthdays this week:'),
  1203. '$events' => $r,
  1204. '$lbr' => '{', // raw brackets mess up if/endif macro processing
  1205. '$rbr' => '}'
  1206. ));
  1207. }
  1208. }
  1209. if(! function_exists('get_events')) {
  1210. function get_events() {
  1211. require_once('include/bbcode.php');
  1212. $a = get_app();
  1213. if(! local_user() || $a->is_mobile || $a->is_tablet)
  1214. return $o;
  1215. // $mobile_detect = new Mobile_Detect();
  1216. // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
  1217. // if($is_mobile)
  1218. // return $o;
  1219. $bd_format = t('g A l F d') ; // 8 AM Friday January 18
  1220. $bd_short = t('F d');
  1221. $r = q("SELECT `event`.* FROM `event`
  1222. WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
  1223. ORDER BY `start` ASC ",
  1224. intval(local_user()),
  1225. dbesc(datetime_convert('UTC','UTC','now + 6 days')),
  1226. dbesc(datetime_convert('UTC','UTC','now - 1 days'))
  1227. );
  1228. if($r && count($r)) {
  1229. $now = strtotime('now');
  1230. $istoday = false;
  1231. foreach($r as $rr) {
  1232. if(strlen($rr['name']))
  1233. $total ++;
  1234. $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
  1235. if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
  1236. $istoday = true;
  1237. }
  1238. $classtoday = (($istoday) ? 'event-today' : '');
  1239. foreach($r as &$rr) {
  1240. if($rr['adjust'])
  1241. $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
  1242. else
  1243. $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
  1244. $md .= "/#link-".$rr['id'];
  1245. $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
  1246. if(! $title)
  1247. $title = t('[No description]');
  1248. $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
  1249. $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
  1250. $rr['link'] = $md;
  1251. $rr['title'] = $title;
  1252. $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
  1253. $rr['startime'] = $strt;
  1254. $rr['today'] = $today;
  1255. }
  1256. }
  1257. $tpl = get_markup_template("events_reminder.tpl");
  1258. return replace_macros($tpl, array(
  1259. '$baseurl' => $a->get_baseurl(),
  1260. '$classtoday' => $classtoday,
  1261. '$count' => count($r),
  1262. '$event_reminders' => t('Event Reminders'),
  1263. '$event_title' => t('Events this week:'),
  1264. '$events' => $r,
  1265. ));
  1266. }
  1267. }
  1268. /**
  1269. *
  1270. * Wrap calls to proc_close(proc_open()) and call hook
  1271. * so plugins can take part in process :)
  1272. *
  1273. * args:
  1274. * $cmd program to run
  1275. * next args are passed as $cmd command line
  1276. *
  1277. * e.g.: proc_run("ls","-la","/tmp");
  1278. *
  1279. * $cmd and string args are surrounded with ""
  1280. */
  1281. if(! function_exists('proc_run')) {
  1282. function proc_run($cmd){
  1283. $a = get_app();
  1284. $args = func_get_args();
  1285. $newargs = array();
  1286. if(! count($args))
  1287. return;
  1288. // expand any arrays
  1289. foreach($args as $arg) {
  1290. if(is_array($arg)) {
  1291. foreach($arg as $n) {
  1292. $newargs[] = $n;
  1293. }
  1294. }
  1295. else
  1296. $newargs[] = $arg;
  1297. }
  1298. $args = $newargs;
  1299. $arr = array('args' => $args, 'run_cmd' => true);
  1300. call_hooks("proc_run", $arr);
  1301. if(! $arr['run_cmd'])
  1302. return;
  1303. if(count($args) && $args[0] === 'php')
  1304. $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
  1305. // add baseurl to args. cli scripts can't construct it
  1306. $args[] = $a->get_baseurl();
  1307. for($x = 0; $x < count($args); $x ++)
  1308. $args[$x] = escapeshellarg($args[$x]);
  1309. $cmdline = implode($args," ");
  1310. if(get_config('system','proc_windows'))
  1311. proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
  1312. else
  1313. proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
  1314. }
  1315. }
  1316. if(! function_exists('current_theme')) {
  1317. function current_theme(){
  1318. $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
  1319. $a = get_app();
  1320. // $mobile_detect = new Mobile_Detect();
  1321. // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
  1322. $is_mobile = $a->is_mobile || $a->is_tablet;
  1323. if($is_mobile) {
  1324. if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  1325. $system_theme = '';
  1326. $theme_name = '';
  1327. }
  1328. else {
  1329. $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
  1330. $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
  1331. if($theme_name === '---') {
  1332. // user has selected to have the mobile theme be the same as the normal one
  1333. $system_theme = '';
  1334. $theme_name = '';
  1335. }
  1336. }
  1337. }
  1338. if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
  1339. $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
  1340. $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
  1341. }
  1342. if($theme_name &&
  1343. (file_exists('view/theme/' . $theme_name . '/style.css') ||
  1344. file_exists('view/theme/' . $theme_name . '/style.php')))
  1345. return($theme_name);
  1346. foreach($app_base_themes as $t) {
  1347. if(file_exists('view/theme/' . $t . '/style.css')||
  1348. file_exists('view/theme/' . $t . '/style.php'))
  1349. return($t);
  1350. }
  1351. $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
  1352. if(count($fallback))
  1353. return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
  1354. }
  1355. }
  1356. /*
  1357. * Return full URL to theme which is currently in effect.
  1358. * Provide a sane default if nothing is chosen or the specified theme does not exist.
  1359. */
  1360. if(! function_exists('current_theme_url')) {
  1361. function current_theme_url() {
  1362. global $a;
  1363. $t = current_theme();
  1364. if (file_exists('view/theme/' . $t . '/style.php'))
  1365. return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
  1366. return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
  1367. }
  1368. }
  1369. if(! function_exists('feed_birthday')) {
  1370. function feed_birthday($uid,$tz) {
  1371. /**
  1372. *
  1373. * Determine the next birthday, but only if the birthday is published
  1374. * in the default profile. We _could_ also look for a private profile that the
  1375. * recipient can see, but somebody could get mad at us if they start getting
  1376. * public birthday greetings when they haven't made this info public.
  1377. *
  1378. * Assuming we are able to publish this info, we are then going to convert
  1379. * the start time from the owner's timezone to UTC.
  1380. *
  1381. * This will potentially solve the problem found with some social networks
  1382. * where birthdays are converted to the viewer's timezone and salutations from
  1383. * elsewhere in the world show up on the wrong day. We will convert it to the
  1384. * viewer's timezone also, but first we are going to convert it from the birthday
  1385. * person's timezone to GMT - so the viewer may find the birthday starting at
  1386. * 6:00PM the day before, but that will correspond to midnight to the birthday person.
  1387. *
  1388. */
  1389. $birthday = '';
  1390. if(! strlen($tz))
  1391. $tz = 'UTC';
  1392. $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
  1393. intval($uid)
  1394. );
  1395. if($p && count($p)) {
  1396. $tmp_dob = substr($p[0]['dob'],5);
  1397. if(intval($tmp_dob)) {
  1398. $y = datetime_convert($tz,$tz,'now','Y');
  1399. $bd = $y . '-' . $tmp_dob . ' 00:00';
  1400. $t_dob = strtotime($bd);
  1401. $now = strtotime(datetime_convert($tz,$tz,'now'));
  1402. if($t_dob < $now)
  1403. $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
  1404. $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
  1405. }
  1406. }
  1407. return $birthday;
  1408. }
  1409. }
  1410. if(! function_exists('is_site_admin')) {
  1411. function is_site_admin() {
  1412. $a = get_app();
  1413. if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
  1414. return true;
  1415. return false;
  1416. }
  1417. }
  1418. if(! function_exists('load_contact_links')) {
  1419. function load_contact_links($uid) {
  1420. $a = get_app();
  1421. $ret = array();
  1422. if(! $uid || x($a->contacts,'empty'))
  1423. return;
  1424. $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
  1425. intval($uid)
  1426. );
  1427. if(count($r)) {
  1428. foreach($r as $rr){
  1429. $url = normalise_link($rr['url']);
  1430. $ret[$url] = $rr;
  1431. }
  1432. }
  1433. else
  1434. $ret['empty'] = true;
  1435. $a->contacts = $ret;
  1436. return;
  1437. }
  1438. }
  1439. if(! function_exists('profile_tabs')){
  1440. function profile_tabs($a, $is_owner=False, $nickname=Null){
  1441. //echo "<pre>"; var_dump($a->user); killme();
  1442. if (is_null($nickname))
  1443. $nickname = $a->user['nickname'];
  1444. if(x($_GET,'tab'))
  1445. $tab = notags(trim($_GET['tab']));
  1446. $url = $a->get_baseurl() . '/profile/' . $nickname;
  1447. $tabs = array(
  1448. array(
  1449. 'label'=>t('Status'),
  1450. 'url' => $url,
  1451. 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
  1452. 'title' => t('Status Messages and Posts'),
  1453. 'id' => 'status-tab',
  1454. ),
  1455. array(
  1456. 'label' => t('Profile'),
  1457. 'url' => $url.'/?tab=profile',
  1458. 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
  1459. 'title' => t('Profile Details'),
  1460. 'id' => 'profile-tab',
  1461. ),
  1462. array(
  1463. 'label' => t('Photos'),
  1464. 'url' => $a->get_baseurl() . '/photos/' . $nickname,
  1465. 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
  1466. 'title' => t('Photo Albums'),
  1467. 'id' => 'photo-tab',
  1468. ),
  1469. );
  1470. if ($is_owner){
  1471. $tabs[] = array(
  1472. 'label' => t('Events'),
  1473. 'url' => $a->get_baseurl() . '/events',
  1474. 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
  1475. 'title' => t('Events and Calendar'),
  1476. 'id' => 'events-tab',
  1477. );
  1478. $tabs[] = array(
  1479. 'label' => t('Personal Notes'),
  1480. 'url' => $a->get_baseurl() . '/notes',
  1481. 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
  1482. 'title' => t('Only You Can See This'),
  1483. 'id' => 'notes-tab',
  1484. );
  1485. }
  1486. $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
  1487. call_hooks('profile_tabs', $arr);
  1488. $tpl = get_markup_template('common_tabs.tpl');
  1489. return replace_macros($tpl,array('$tabs' => $arr['tabs']));
  1490. }
  1491. }
  1492. function get_my_url() {
  1493. if(x($_SESSION,'my_url'))
  1494. return $_SESSION['my_url'];
  1495. return false;
  1496. }
  1497. function zrl_init(&$a) {
  1498. $tmp_str = get_my_url();
  1499. if(validate_url($tmp_str)) {
  1500. proc_run('php','include/gprobe.php',bin2hex($tmp_str));
  1501. $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
  1502. call_hooks('zrl_init',$arr);
  1503. }
  1504. }
  1505. function zrl($s,$force = false) {
  1506. if(! strlen($s))
  1507. return $s;
  1508. if((! strpos($s,'/profile/')) && (! $force))
  1509. return $s;
  1510. if($force && substr($s,-1,1) !== '/')
  1511. $s = $s . '/';
  1512. $achar = strpos($s,'?') ? '&' : '?';
  1513. $mine = get_my_url();
  1514. if($mine and ! link_compare($mine,$s))
  1515. return $s . $achar . 'zrl=' . urlencode($mine);
  1516. return $s;
  1517. }
  1518. /**
  1519. * returns querystring as string from a mapped array
  1520. *
  1521. * @param params Array
  1522. * @return string
  1523. */
  1524. function build_querystring($params, $name=null) {
  1525. $ret = "";
  1526. foreach($params as $key=>$val) {
  1527. if(is_array($val)) {
  1528. if($name==null) {
  1529. $ret .= build_querystring($val, $key);
  1530. } else {
  1531. $ret .= build_querystring($val, $name."[$key]");
  1532. }
  1533. } else {
  1534. $val = urlencode($val);
  1535. if($name!=null) {
  1536. $ret.=$name."[$key]"."=$val&";
  1537. } else {
  1538. $ret.= "$key=$val&";
  1539. }
  1540. }
  1541. }
  1542. return $ret;
  1543. }
  1544. /**
  1545. * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
  1546. *
  1547. * Taken from http://webcheatsheet.com/php/get_current_page_url.php
  1548. */
  1549. function curPageURL() {
  1550. $pageURL = 'http';
  1551. if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
  1552. $pageURL .= "://";
  1553. if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
  1554. $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  1555. } else {
  1556. $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  1557. }
  1558. return $pageURL;
  1559. }
  1560. function random_digits($digits) {
  1561. $rn = '';
  1562. for($i = 0; $i < $digits; $i++) {
  1563. $rn .= rand(0,9);
  1564. }
  1565. return $rn;
  1566. }
  1567. function get_cachefile($file, $writemode = true) {
  1568. $cache = get_config("system","itemcache");
  1569. if ($cache == "")
  1570. return("");
  1571. if (!is_dir($cache))
  1572. return("");
  1573. $subfolder = $cache."/".substr($file, 0, 2);
  1574. $cachepath = $subfolder."/".$file;
  1575. if ($writemode) {
  1576. if (!is_dir($subfolder)) {
  1577. mkdir($subfolder);
  1578. chmod($subfolder, 0777);
  1579. }
  1580. }
  1581. return($cachepath);
  1582. }
  1583. function clear_cache($basepath = "", $path = "") {
  1584. if ($path == "") {
  1585. $basepath = get_config('system','itemcache');
  1586. $path = $basepath;
  1587. }
  1588. if (($path == "") OR (!is_dir($path)))
  1589. return;
  1590. if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
  1591. return;
  1592. $cachetime = (int)get_config('system','itemcache_duration');
  1593. if ($cachetime == 0)
  1594. $cachetime = 86400;
  1595. if ($dh = opendir($path)) {
  1596. while (($file = readdir($dh)) !== false) {
  1597. $fullpath = $path."/".$file;
  1598. if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
  1599. clear_cache($basepath, $fullpath);
  1600. if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
  1601. unlink($fullpath);
  1602. }
  1603. closedir($dh);
  1604. }
  1605. }
  1606. function set_template_engine(&$a, $engine = 'internal') {
  1607. // This function is no longer necessary, but keep it as a wrapper to the class method
  1608. // to avoid breaking themes again unnecessarily
  1609. $a->set_template_engine($engine);
  1610. }