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.
 
 
 
 
 
 

850 lines
25 KiB

  1. <?php
  2. /**
  3. * @file include/event.php
  4. * @brief functions specific to event handling
  5. */
  6. require_once('include/bbcode.php');
  7. require_once('include/map.php');
  8. require_once('include/datetime.php');
  9. function format_event_html($ev, $simple = false) {
  10. if(! ((is_array($ev)) && count($ev)))
  11. return '';
  12. $bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
  13. $event_start = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
  14. $ev['start'] , $bd_format ))
  15. : day_translate(datetime_convert('UTC', 'UTC',
  16. $ev['start'] , $bd_format)));
  17. $event_end = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
  18. $ev['finish'] , $bd_format ))
  19. : day_translate(datetime_convert('UTC', 'UTC',
  20. $ev['finish'] , $bd_format )));
  21. if ($simple) {
  22. $o = "<h3>".bbcode($ev['summary'])."</h3>";
  23. $o .= "<p>".bbcode($ev['desc'])."</p>";
  24. $o .= "<h4>".t('Starts:')."</h4><p>".$event_start."</p>";
  25. if(! $ev['nofinish'])
  26. $o .= "<h4>".t('Finishes:')."</h4><p>".$event_end."</p>";
  27. if(strlen($ev['location']))
  28. $o .= "<h4>".t('Location:')."</h4><p>".$ev['location']."</p>";
  29. return $o;
  30. }
  31. $o = '<div class="vevent">' . "\r\n";
  32. $o .= '<p class="summary event-summary">' . bbcode($ev['summary']) . '</p>' . "\r\n";
  33. $o .= '<p class="description event-description">' . bbcode($ev['desc']) . '</p>' . "\r\n";
  34. $o .= '<p class="event-start">' . t('Starts:') . ' <abbr class="dtstart" title="'
  35. . datetime_convert('UTC','UTC',$ev['start'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
  36. . '" >'.$event_start
  37. . '</abbr></p>' . "\r\n";
  38. if(! $ev['nofinish'])
  39. $o .= '<p class="event-end" >' . t('Finishes:') . ' <abbr class="dtend" title="'
  40. . datetime_convert('UTC','UTC',$ev['finish'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
  41. . '" >'.$event_end
  42. . '</abbr></p>' . "\r\n";
  43. if(strlen($ev['location'])){
  44. $o .= '<p class="event-location"> ' . t('Location:') . ' <span class="location">'
  45. . bbcode($ev['location'])
  46. . '</span></p>' . "\r\n";
  47. if (strpos($ev['location'], "[map") !== False) {
  48. $map = generate_named_map($ev['location']);
  49. if ($map!==$ev['location']) $o.=$map;
  50. }
  51. }
  52. $o .= '</div>' . "\r\n";
  53. return $o;
  54. }
  55. /*
  56. function parse_event($h) {
  57. require_once('include/Scrape.php');
  58. require_once('include/html2bbcode');
  59. $h = '<html><body>' . $h . '</body></html>';
  60. $ret = array();
  61. try {
  62. $dom = HTML5_Parser::parse($h);
  63. } catch (DOMException $e) {
  64. logger('parse_event: parse error: ' . $e);
  65. }
  66. if(! $dom)
  67. return $ret;
  68. $items = $dom->getElementsByTagName('*');
  69. foreach($items as $item) {
  70. if(attribute_contains($item->getAttribute('class'), 'vevent')) {
  71. $level2 = $item->getElementsByTagName('*');
  72. foreach($level2 as $x) {
  73. if(attribute_contains($x->getAttribute('class'),'dtstart') && $x->getAttribute('title')) {
  74. $ret['start'] = $x->getAttribute('title');
  75. if(! strpos($ret['start'],'Z'))
  76. $ret['adjust'] = true;
  77. }
  78. if(attribute_contains($x->getAttribute('class'),'dtend') && $x->getAttribute('title'))
  79. $ret['finish'] = $x->getAttribute('title');
  80. if(attribute_contains($x->getAttribute('class'),'description'))
  81. $ret['desc'] = $x->textContent;
  82. if(attribute_contains($x->getAttribute('class'),'location'))
  83. $ret['location'] = $x->textContent;
  84. }
  85. }
  86. }
  87. // sanitise
  88. if((x($ret,'desc')) && ((strpos($ret['desc'],'<') !== false) || (strpos($ret['desc'],'>') !== false))) {
  89. $config = HTMLPurifier_Config::createDefault();
  90. $config->set('Cache.DefinitionImpl', null);
  91. $purifier = new HTMLPurifier($config);
  92. $ret['desc'] = html2bbcode($purifier->purify($ret['desc']));
  93. }
  94. if((x($ret,'location')) && ((strpos($ret['location'],'<') !== false) || (strpos($ret['location'],'>') !== false))) {
  95. $config = HTMLPurifier_Config::createDefault();
  96. $config->set('Cache.DefinitionImpl', null);
  97. $purifier = new HTMLPurifier($config);
  98. $ret['location'] = html2bbcode($purifier->purify($ret['location']));
  99. }
  100. if(x($ret,'start'))
  101. $ret['start'] = datetime_convert('UTC','UTC',$ret['start']);
  102. if(x($ret,'finish'))
  103. $ret['finish'] = datetime_convert('UTC','UTC',$ret['finish']);
  104. return $ret;
  105. }
  106. */
  107. function format_event_bbcode($ev) {
  108. $o = '';
  109. if($ev['summary'])
  110. $o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';
  111. if($ev['desc'])
  112. $o .= '[event-description]' . $ev['desc'] . '[/event-description]';
  113. if($ev['start'])
  114. $o .= '[event-start]' . $ev['start'] . '[/event-start]';
  115. if(($ev['finish']) && (! $ev['nofinish']))
  116. $o .= '[event-finish]' . $ev['finish'] . '[/event-finish]';
  117. if($ev['location'])
  118. $o .= '[event-location]' . $ev['location'] . '[/event-location]';
  119. if($ev['adjust'])
  120. $o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
  121. return $o;
  122. }
  123. function bbtovcal($s) {
  124. $o = '';
  125. $ev = bbtoevent($s);
  126. if($ev['desc'])
  127. $o = format_event_html($ev);
  128. return $o;
  129. }
  130. function bbtoevent($s) {
  131. $ev = array();
  132. $match = '';
  133. if(preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is",$s,$match))
  134. $ev['summary'] = $match[1];
  135. $match = '';
  136. if(preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is",$s,$match))
  137. $ev['desc'] = $match[1];
  138. $match = '';
  139. if(preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is",$s,$match))
  140. $ev['start'] = $match[1];
  141. $match = '';
  142. if(preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is",$s,$match))
  143. $ev['finish'] = $match[1];
  144. $match = '';
  145. if(preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is",$s,$match))
  146. $ev['location'] = $match[1];
  147. $match = '';
  148. if(preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",$s,$match))
  149. $ev['adjust'] = $match[1];
  150. $ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
  151. return $ev;
  152. }
  153. function sort_by_date($a) {
  154. usort($a,'ev_compare');
  155. return $a;
  156. }
  157. function ev_compare($a,$b) {
  158. $date_a = (($a['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$a['start']) : $a['start']);
  159. $date_b = (($b['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$b['start']) : $b['start']);
  160. if($date_a === $date_b)
  161. return strcasecmp($a['desc'],$b['desc']);
  162. return strcmp($date_a,$date_b);
  163. }
  164. function event_delete($event_id) {
  165. if ($event_id == 0)
  166. return;
  167. q("DELETE FROM `event` WHERE `id` = %d", intval($event_id));
  168. logger("Deleted event ".$event_id, LOGGER_DEBUG);
  169. }
  170. function event_store($arr) {
  171. require_once('include/datetime.php');
  172. require_once('include/items.php');
  173. require_once('include/bbcode.php');
  174. $a = get_app();
  175. $arr['created'] = (($arr['created']) ? $arr['created'] : datetime_convert());
  176. $arr['edited'] = (($arr['edited']) ? $arr['edited'] : datetime_convert());
  177. $arr['type'] = (($arr['type']) ? $arr['type'] : 'event' );
  178. $arr['cid'] = ((intval($arr['cid'])) ? intval($arr['cid']) : 0);
  179. $arr['uri'] = (x($arr,'uri') ? $arr['uri'] : item_new_uri($a->get_hostname(),$arr['uid']));
  180. $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0);
  181. if($arr['cid'])
  182. $c = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  183. intval($arr['cid']),
  184. intval($arr['uid'])
  185. );
  186. else
  187. $c = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
  188. intval($arr['uid'])
  189. );
  190. if(count($c))
  191. $contact = $c[0];
  192. // Existing event being modified
  193. if($arr['id']) {
  194. // has the event actually changed?
  195. $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  196. intval($arr['id']),
  197. intval($arr['uid'])
  198. );
  199. if((! count($r)) || ($r[0]['edited'] === $arr['edited'])) {
  200. // Nothing has changed. Grab the item id to return.
  201. $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
  202. intval($arr['id']),
  203. intval($arr['uid'])
  204. );
  205. return((count($r)) ? $r[0]['id'] : 0);
  206. }
  207. // The event changed. Update it.
  208. $r = q("UPDATE `event` SET
  209. `edited` = '%s',
  210. `start` = '%s',
  211. `finish` = '%s',
  212. `summary` = '%s',
  213. `desc` = '%s',
  214. `location` = '%s',
  215. `type` = '%s',
  216. `adjust` = %d,
  217. `nofinish` = %d
  218. WHERE `id` = %d AND `uid` = %d",
  219. dbesc($arr['edited']),
  220. dbesc($arr['start']),
  221. dbesc($arr['finish']),
  222. dbesc($arr['summary']),
  223. dbesc($arr['desc']),
  224. dbesc($arr['location']),
  225. dbesc($arr['type']),
  226. intval($arr['adjust']),
  227. intval($arr['nofinish']),
  228. intval($arr['id']),
  229. intval($arr['uid'])
  230. );
  231. $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
  232. intval($arr['id']),
  233. intval($arr['uid'])
  234. );
  235. if(count($r)) {
  236. $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
  237. $object .= '<content>' . xmlify(format_event_bbcode($arr)) . '</content>';
  238. $object .= '</object>' . "\n";
  239. q("UPDATE `item` SET `body` = '%s', `object` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d",
  240. dbesc(format_event_bbcode($arr)),
  241. dbesc($object),
  242. dbesc($arr['edited']),
  243. intval($r[0]['id']),
  244. intval($arr['uid'])
  245. );
  246. $item_id = $r[0]['id'];
  247. } else
  248. $item_id = 0;
  249. call_hooks("event_updated", $arr['id']);
  250. return $item_id;
  251. }
  252. else {
  253. // New event. Store it.
  254. $r = q("INSERT INTO `event` ( `uid`,`cid`,`uri`,`created`,`edited`,`start`,`finish`,`summary`, `desc`,`location`,`type`,
  255. `adjust`,`nofinish`,`allow_cid`,`allow_gid`,`deny_cid`,`deny_gid`)
  256. VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
  257. intval($arr['uid']),
  258. intval($arr['cid']),
  259. dbesc($arr['uri']),
  260. dbesc($arr['created']),
  261. dbesc($arr['edited']),
  262. dbesc($arr['start']),
  263. dbesc($arr['finish']),
  264. dbesc($arr['summary']),
  265. dbesc($arr['desc']),
  266. dbesc($arr['location']),
  267. dbesc($arr['type']),
  268. intval($arr['adjust']),
  269. intval($arr['nofinish']),
  270. dbesc($arr['allow_cid']),
  271. dbesc($arr['allow_gid']),
  272. dbesc($arr['deny_cid']),
  273. dbesc($arr['deny_gid'])
  274. );
  275. $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  276. dbesc($arr['uri']),
  277. intval($arr['uid'])
  278. );
  279. if(count($r))
  280. $event = $r[0];
  281. $item_arr = array();
  282. $item_arr['uid'] = $arr['uid'];
  283. $item_arr['contact-id'] = $arr['cid'];
  284. $item_arr['uri'] = $arr['uri'];
  285. $item_arr['parent-uri'] = $arr['uri'];
  286. $item_arr['guid'] = $arr['guid'];
  287. $item_arr['type'] = 'activity';
  288. $item_arr['wall'] = (($arr['cid']) ? 0 : 1);
  289. $item_arr['contact-id'] = $contact['id'];
  290. $item_arr['owner-name'] = $contact['name'];
  291. $item_arr['owner-link'] = $contact['url'];
  292. $item_arr['owner-avatar'] = $contact['thumb'];
  293. $item_arr['author-name'] = $contact['name'];
  294. $item_arr['author-link'] = $contact['url'];
  295. $item_arr['author-avatar'] = $contact['thumb'];
  296. $item_arr['title'] = '';
  297. $item_arr['allow_cid'] = $arr['allow_cid'];
  298. $item_arr['allow_gid'] = $arr['allow_gid'];
  299. $item_arr['deny_cid'] = $arr['deny_cid'];
  300. $item_arr['deny_gid'] = $arr['deny_gid'];
  301. $item_arr['private'] = $arr['private'];
  302. $item_arr['last-child'] = 1;
  303. $item_arr['visible'] = 1;
  304. $item_arr['verb'] = ACTIVITY_POST;
  305. $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
  306. $item_arr['origin'] = ((intval($arr['cid']) == 0) ? 1 : 0);
  307. $item_arr['body'] = format_event_bbcode($event);
  308. $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
  309. $item_arr['object'] .= '<content>' . xmlify(format_event_bbcode($event)) . '</content>';
  310. $item_arr['object'] .= '</object>' . "\n";
  311. $item_id = item_store($item_arr);
  312. $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  313. intval($arr['uid'])
  314. );
  315. //if(count($r))
  316. // $plink = $a->get_baseurl() . '/display/' . $r[0]['nickname'] . '/' . $item_id;
  317. if($item_id) {
  318. //q("UPDATE `item` SET `plink` = '%s', `event-id` = %d WHERE `uid` = %d AND `id` = %d",
  319. // dbesc($plink),
  320. // intval($event['id']),
  321. // intval($arr['uid']),
  322. // intval($item_id)
  323. //);
  324. q("UPDATE `item` SET `event-id` = %d WHERE `uid` = %d AND `id` = %d",
  325. intval($event['id']),
  326. intval($arr['uid']),
  327. intval($item_id)
  328. );
  329. }
  330. call_hooks("event_created", $event['id']);
  331. return $item_id;
  332. }
  333. }
  334. function get_event_strings() {
  335. // First day of the week (0 = Sunday)
  336. $firstDay = get_pconfig(local_user(),'system','first_day_of_week');
  337. if ($firstDay === false) $firstDay=0;
  338. $i18n = array(
  339. "firstDay" => $firstDay,
  340. "Sun" => t("Sun"),
  341. "Mon" => t("Mon"),
  342. "Tue" => t("Tue"),
  343. "Wed" => t("Wed"),
  344. "Thu" => t("Thu"),
  345. "Fri" => t("Fri"),
  346. "Sat" => t("Sat"),
  347. "Sunday" => t("Sunday"),
  348. "Monday" => t("Monday"),
  349. "Tuesday" => t("Tuesday"),
  350. "Wednesday" => t("Wednesday"),
  351. "Thursday" => t("Thursday"),
  352. "Friday" => t("Friday"),
  353. "Saturday" => t("Saturday"),
  354. "Jan" => t("Jan"),
  355. "Feb" => t("Feb"),
  356. "Mar" => t("Mar"),
  357. "Apr" => t("Apr"),
  358. "May" => t("May"),
  359. "Jun" => t("Jun"),
  360. "Jul" => t("Jul"),
  361. "Aug" => t("Aug"),
  362. "Sep" => t("Sept"),
  363. "Oct" => t("Oct"),
  364. "Nov" => t("Nov"),
  365. "Dec" => t("Dec"),
  366. "January" => t("January"),
  367. "February" => t("February"),
  368. "March" => t("March"),
  369. "April" => t("April"),
  370. "May" => t("May"),
  371. "June" => t("June"),
  372. "July" => t("July"),
  373. "August" => t("August"),
  374. "September" => t("September"),
  375. "October" => t("October"),
  376. "November" => t("November"),
  377. "December" => t("December"),
  378. "today" => t("today"),
  379. "month" => t("month"),
  380. "week" => t("week"),
  381. "day" => t("day"),
  382. );
  383. return $i18n;
  384. }
  385. /**
  386. * @brief Get an event by its event ID
  387. *
  388. * @param type $owner_uid The User ID of the owner of the event
  389. * @param type $event_params An assoziative array with
  390. * int 'event_id' => The ID of the event in the event table
  391. * @param type $sql_extra
  392. * @return array Query result
  393. */
  394. function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
  395. // ownly allow events if there is a valid owner_id
  396. if($owner_uid == 0)
  397. return;
  398. // query for the event by event id
  399. $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
  400. `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
  401. STRAIGHT_JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
  402. WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
  403. intval($owner_uid),
  404. intval($event_params["event_id"])
  405. );
  406. if(count($r))
  407. return $r;
  408. }
  409. /**
  410. * @brief Get all events in a specific timeframe
  411. *
  412. * @param int $owner_uid The User ID of the owner of the events
  413. * @param array $event_params An assoziative array with
  414. * int 'ignored' =>
  415. * string 'start' => Start time of the timeframe
  416. * string 'finish' => Finish time of the timeframe
  417. * string 'adjust_start' =>
  418. * string 'adjust_start' =>
  419. *
  420. * @param string $sql_extra Additional sql conditions (e.g. permission request)
  421. * @return array Query results
  422. */
  423. function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
  424. // ownly allow events if there is a valid owner_id
  425. if($owner_uid == 0)
  426. return;
  427. // query for the event by date
  428. $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
  429. `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
  430. STRAIGHT_JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
  431. WHERE `event`.`uid` = %d AND event.ignore = %d
  432. AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
  433. OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
  434. $sql_extra ",
  435. intval($owner_uid),
  436. intval($event_params["ignored"]),
  437. dbesc($event_params["start"]),
  438. dbesc($event_params["start"]),
  439. dbesc($event_params["finish"]),
  440. dbesc($event_params["adjust_start"]),
  441. dbesc($event_params["adjust_start"]),
  442. dbesc($event_params["adjust_finish"])
  443. );
  444. if(count($r))
  445. return $r;
  446. }
  447. /**
  448. * @brief Convert an array query results in an arry which could be used by the events template
  449. *
  450. * @param array $arr Event query array
  451. * @return array Event array for the template
  452. */
  453. function process_events ($arr) {
  454. $events=array();
  455. $last_date = '';
  456. $fmt = t('l, F j');
  457. if (count($arr)) {
  458. foreach($arr as $rr) {
  459. $j = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], 'j') : datetime_convert('UTC','UTC',$rr['start'],'j'));
  460. $d = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], $fmt) : datetime_convert('UTC','UTC',$rr['start'],$fmt));
  461. $d = day_translate($d);
  462. $start = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], 'c') : datetime_convert('UTC','UTC',$rr['start'],'c'));
  463. if ($rr['nofinish']){
  464. $end = null;
  465. } else {
  466. $end = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['finish'], 'c') : datetime_convert('UTC','UTC',$rr['finish'],'c'));
  467. }
  468. $is_first = ($d !== $last_date);
  469. $last_date = $d;
  470. $edit = ((! $rr['cid']) ? array(App::get_baseurl().'/events/event/'.$rr['id'],t('Edit event'),'','') : null);
  471. $title = strip_tags(html_entity_decode(bbcode($rr['summary']),ENT_QUOTES,'UTF-8'));
  472. if(! $title) {
  473. list($title, $_trash) = explode("<br",bbcode($rr['desc']),2);
  474. $title = strip_tags(html_entity_decode($title,ENT_QUOTES,'UTF-8'));
  475. }
  476. $html = format_event_html($rr);
  477. $rr['desc'] = bbcode($rr['desc']);
  478. $rr['location'] = bbcode($rr['location']);
  479. $events[] = array(
  480. 'id'=>$rr['id'],
  481. 'start'=> $start,
  482. 'end' => $end,
  483. 'allDay' => false,
  484. 'title' => $title,
  485. 'j' => $j,
  486. 'd' => $d,
  487. 'is_first'=>$is_first,
  488. 'item'=>$rr,
  489. 'html'=>$html,
  490. 'plink' => array($rr['plink'],t('link to source'),'',''),
  491. );
  492. }
  493. }
  494. return $events;
  495. }
  496. /**
  497. * @brief Format event to export format (ical/csv)
  498. *
  499. * @param array $events Query result for events
  500. * @param string $format The output format (ical/csv)
  501. * @param string $timezone The timezone of the user (not implemented yet)
  502. *
  503. * @return string Content according to selected export format
  504. */
  505. function event_format_export ($events, $format = 'ical', $timezone) {
  506. if(! ((is_array($events)) && count($events)))
  507. return;
  508. switch ($format) {
  509. // format the exported data as a CSV file
  510. case "csv":
  511. header("Content-type: text/csv");
  512. $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
  513. foreach ($events as $event) {
  514. /// @todo the time / date entries don't include any information about the
  515. // timezone the event is scheduled in :-/
  516. $tmp1 = strtotime($event['start']);
  517. $tmp2 = strtotime($event['finish']);
  518. $time_format = "%H:%M:%S";
  519. $date_format = "%Y-%m-%d";
  520. $o .= '"'.$event['summary'].'", "'.strftime($date_format, $tmp1) .
  521. '", "'.strftime($time_format, $tmp1).'", "'.$event['desc'] .
  522. '", "'.strftime($date_format, $tmp2) .
  523. '", "'.strftime($time_format, $tmp2) .
  524. '", "'.$event['location'].'"' . PHP_EOL;
  525. }
  526. break;
  527. // format the exported data as a ics file
  528. case "ical":
  529. header("Content-type: text/ics");
  530. $o = 'BEGIN:VCALENDAR'. PHP_EOL
  531. . 'VERSION:2.0' . PHP_EOL
  532. . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
  533. /// @todo include timezone informations in cases were the time is not in UTC
  534. // see http://tools.ietf.org/html/rfc2445#section-4.8.3
  535. // . 'BEGIN:VTIMEZONE' . PHP_EOL
  536. // . 'TZID:' . $timezone . PHP_EOL
  537. // . 'END:VTIMEZONE' . PHP_EOL;
  538. // TODO instead of PHP_EOL CRLF should be used for long entries
  539. // but test your solution against http://icalvalid.cloudapp.net/
  540. // also long lines SHOULD be split at 75 characters length
  541. foreach ($events as $event) {
  542. if ($event['adjust'] == 1) {
  543. $UTC = 'Z';
  544. } else {
  545. $UTC = '';
  546. }
  547. $o .= 'BEGIN:VEVENT' . PHP_EOL;
  548. if ($event[start]) {
  549. $tmp = strtotime($event['start']);
  550. $dtformat = "%Y%m%dT%H%M%S".$UTC;
  551. $o .= 'DTSTART:'.strftime($dtformat, $tmp).PHP_EOL;
  552. }
  553. if (!$event['nofinish']) {
  554. $tmp = strtotime($event['finish']);
  555. $dtformat = "%Y%m%dT%H%M%S".$UTC;
  556. $o .= 'DTEND:'.strftime($dtformat, $tmp).PHP_EOL;
  557. }
  558. if ($event['summary'])
  559. $tmp = $event['summary'];
  560. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  561. $tmp = addcslashes($tmp, ',;');
  562. $o .= 'SUMMARY:' . $tmp . PHP_EOL;
  563. if ($event['desc'])
  564. $tmp = $event['desc'];
  565. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  566. $tmp = addcslashes($tmp, ',;');
  567. $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
  568. if ($event['location']) {
  569. $tmp = $event['location'];
  570. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  571. $tmp = addcslashes($tmp, ',;');
  572. $o .= 'LOCATION:' . $tmp . PHP_EOL;
  573. }
  574. $o .= 'END:VEVENT' . PHP_EOL;
  575. $o .= PHP_EOL;
  576. }
  577. $o .= 'END:VCALENDAR' . PHP_EOL;
  578. break;
  579. }
  580. return $o;
  581. }
  582. /**
  583. * @brief Get all events for a user ID
  584. *
  585. * The query for events is done permission sensitive
  586. * If the user is the owner of the calendar he/she
  587. * will get all of his/her available events.
  588. * If the user is only a visitor only the public events will
  589. * be available
  590. *
  591. * @param int $uid The user ID
  592. * @param int $sql_extra Additional sql conditions for permission
  593. *
  594. * @return array Query results
  595. */
  596. function events_by_uid($uid = 0, $sql_extra = '') {
  597. if($uid == 0)
  598. return;
  599. // The permission condition if no condition was transmitted
  600. if($sql_extra == '')
  601. $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
  602. // does the user who requests happen to be the owner of the events
  603. // requested? then show all of your events, otherwise only those that
  604. // don't have limitations set in allow_cid and allow_gid
  605. if (local_user() == $uid) {
  606. $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
  607. FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
  608. intval($uid)
  609. );
  610. } else {
  611. $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
  612. FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
  613. intval($uid)
  614. );
  615. }
  616. if(count($r))
  617. return $r;
  618. }
  619. /**
  620. *
  621. * @param int $uid The user ID
  622. * @param string $format Output format (ical/csv)
  623. * @return array With the results
  624. * bool 'success' => True if the processing was successful
  625. * string 'format' => The output format
  626. * string 'extension' => The file extension of the output format
  627. * string 'content' => The formatted output content
  628. *
  629. * @todo Respect authenticated users with events_by_uid()
  630. */
  631. function event_export($uid, $format = 'ical') {
  632. $process = false;
  633. // we are allowed to show events
  634. // get the timezone the user is in
  635. $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
  636. if (count($r))
  637. $timezone = $r[0]['timezone'];
  638. // get all events which are owned by a uid (respects permissions);
  639. $events = events_by_uid($uid);
  640. // we have the events that are available for the requestor
  641. // now format the output according to the requested format
  642. if(count($events))
  643. $res = event_format_export($events, $format, $timezone);
  644. // If there are results the precess was successfull
  645. if(x($res))
  646. $process = true;
  647. // get the file extension for the format
  648. switch ($format) {
  649. case "ical":
  650. $file_ext = "ics";
  651. break;
  652. case "csv":
  653. $file_ext = "csv";
  654. break;
  655. default:
  656. $file_ext = "";
  657. }
  658. $arr = array(
  659. 'success' => $process,
  660. 'format' => $format,
  661. 'extension' => $file_ext,
  662. 'content' => $res,
  663. );
  664. return $arr;
  665. }
  666. /**
  667. * @brief Get the events widget
  668. *
  669. * @return string Formated html of the evens widget
  670. */
  671. function widget_events() {
  672. $a = get_app();
  673. $owner_uid = $a->data['user']['uid'];
  674. // $a->data is only available if the profile page is visited. If the visited page is not part
  675. // of the profile page it should be the personal /events page. So we can use $a->user
  676. $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
  677. // The permission testing is a little bit tricky because we have to respect many cases
  678. // It's not the private events page (we don't get the $owner_uid for /events)
  679. if(! local_user() && ! $owner_uid)
  680. return;
  681. // Cal logged in user (test permission at foreign profile page)
  682. // If the $owner uid is available we know it is part of one of the profile pages (like /cal)
  683. // So we have to test if if it's the own profile page of the logged in user
  684. // or a foreign one. For foreign profile pages we need to check if the feature
  685. // for exporting the cal is enabled (otherwise the widget would appear for logged in users
  686. // on foreigen profile pages even if the widget is disabled)
  687. if(intval($owner_uid) && local_user() !== $owner_uid && ! feature_enabled($owner_uid, "export_calendar"))
  688. return;
  689. // If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
  690. // export feature isn't enabled
  691. if(intval($owner_uid) && ! local_user() && ! feature_enabled($owner_uid, "export_calendar"))
  692. return;
  693. return replace_macros(get_markup_template("events_aside.tpl"), array(
  694. '$etitle' => t("Export"),
  695. '$export_ical' => t("Export calendar as ical"),
  696. '$export_csv' => t("Export calendar as csv"),
  697. '$user' => $user
  698. ));
  699. }