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.

2370 lines
65KB

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