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.
 
 
 
 
 
 

857 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. "allday" => t("all-day"),
  383. "noevent" => t("No events to display"),
  384. "dtstart_label" => t("Starts:"),
  385. "dtend_label" => t("Finishes:"),
  386. "location_label" => t("Location:")
  387. );
  388. return $i18n;
  389. }
  390. /**
  391. * @brief Get an event by its event ID
  392. *
  393. * @param type $owner_uid The User ID of the owner of the event
  394. * @param type $event_params An assoziative array with
  395. * int 'event_id' => The ID of the event in the event table
  396. * @param type $sql_extra
  397. * @return array Query result
  398. */
  399. function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
  400. // ownly allow events if there is a valid owner_id
  401. if($owner_uid == 0)
  402. return;
  403. // query for the event by event id
  404. $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
  405. `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
  406. LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
  407. WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
  408. intval($owner_uid),
  409. intval($event_params["event_id"])
  410. );
  411. if(count($r))
  412. return $r;
  413. }
  414. /**
  415. * @brief Get all events in a specific timeframe
  416. *
  417. * @param int $owner_uid The User ID of the owner of the events
  418. * @param array $event_params An assoziative array with
  419. * int 'ignored' =>
  420. * string 'start' => Start time of the timeframe
  421. * string 'finish' => Finish time of the timeframe
  422. * string 'adjust_start' =>
  423. * string 'adjust_start' =>
  424. *
  425. * @param string $sql_extra Additional sql conditions (e.g. permission request)
  426. * @return array Query results
  427. */
  428. function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
  429. // ownly allow events if there is a valid owner_id
  430. if($owner_uid == 0)
  431. return;
  432. // query for the event by date
  433. $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
  434. `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
  435. LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
  436. WHERE `event`.`uid` = %d AND event.ignore = %d
  437. AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
  438. OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
  439. $sql_extra ",
  440. intval($owner_uid),
  441. intval($event_params["ignored"]),
  442. dbesc($event_params["start"]),
  443. dbesc($event_params["start"]),
  444. dbesc($event_params["finish"]),
  445. dbesc($event_params["adjust_start"]),
  446. dbesc($event_params["adjust_start"]),
  447. dbesc($event_params["adjust_finish"])
  448. );
  449. if(count($r))
  450. return $r;
  451. }
  452. /**
  453. * @brief Convert an array query results in an arry which could be used by the events template
  454. *
  455. * @param array $arr Event query array
  456. * @return array Event array for the template
  457. */
  458. function process_events ($arr) {
  459. $events=array();
  460. $last_date = '';
  461. $fmt = t('l, F j');
  462. if (count($arr)) {
  463. foreach($arr as $rr) {
  464. $j = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], 'j') : datetime_convert('UTC','UTC',$rr['start'],'j'));
  465. $d = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], $fmt) : datetime_convert('UTC','UTC',$rr['start'],$fmt));
  466. $d = day_translate($d);
  467. $start = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], 'c') : datetime_convert('UTC','UTC',$rr['start'],'c'));
  468. if ($rr['nofinish']){
  469. $end = null;
  470. } else {
  471. $end = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['finish'], 'c') : datetime_convert('UTC','UTC',$rr['finish'],'c'));
  472. }
  473. $is_first = ($d !== $last_date);
  474. $last_date = $d;
  475. $edit = ((! $rr['cid']) ? array(App::get_baseurl().'/events/event/'.$rr['id'],t('Edit event'),'','') : null);
  476. $title = strip_tags(html_entity_decode(bbcode($rr['summary']),ENT_QUOTES,'UTF-8'));
  477. if(! $title) {
  478. list($title, $_trash) = explode("<br",bbcode($rr['desc']),2);
  479. $title = strip_tags(html_entity_decode($title,ENT_QUOTES,'UTF-8'));
  480. }
  481. $html = format_event_html($rr);
  482. $rr['desc'] = bbcode($rr['desc']);
  483. $rr['location'] = bbcode($rr['location']);
  484. $events[] = array(
  485. 'id'=>$rr['id'],
  486. 'start'=> $start,
  487. 'end' => $end,
  488. 'allDay' => false,
  489. 'title' => $title,
  490. 'j' => $j,
  491. 'd' => $d,
  492. 'is_first'=>$is_first,
  493. 'item'=>$rr,
  494. 'html'=>$html,
  495. 'plink' => array($rr['plink'],t('link to source'),'',''),
  496. );
  497. }
  498. }
  499. return $events;
  500. }
  501. /**
  502. * @brief Format event to export format (ical/csv)
  503. *
  504. * @param array $events Query result for events
  505. * @param string $format The output format (ical/csv)
  506. * @param string $timezone The timezone of the user (not implemented yet)
  507. *
  508. * @return string Content according to selected export format
  509. */
  510. function event_format_export ($events, $format = 'ical', $timezone) {
  511. if(! ((is_array($events)) && count($events)))
  512. return;
  513. switch ($format) {
  514. // format the exported data as a CSV file
  515. case "csv":
  516. header("Content-type: text/csv");
  517. $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
  518. foreach ($events as $event) {
  519. /// @todo the time / date entries don't include any information about the
  520. // timezone the event is scheduled in :-/
  521. $tmp1 = strtotime($event['start']);
  522. $tmp2 = strtotime($event['finish']);
  523. $time_format = "%H:%M:%S";
  524. $date_format = "%Y-%m-%d";
  525. $o .= '"'.$event['summary'].'", "'.strftime($date_format, $tmp1) .
  526. '", "'.strftime($time_format, $tmp1).'", "'.$event['desc'] .
  527. '", "'.strftime($date_format, $tmp2) .
  528. '", "'.strftime($time_format, $tmp2) .
  529. '", "'.$event['location'].'"' . PHP_EOL;
  530. }
  531. break;
  532. // format the exported data as a ics file
  533. case "ical":
  534. header("Content-type: text/ics");
  535. $o = 'BEGIN:VCALENDAR'. PHP_EOL
  536. . 'VERSION:2.0' . PHP_EOL
  537. . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
  538. /// @todo include timezone informations in cases were the time is not in UTC
  539. // see http://tools.ietf.org/html/rfc2445#section-4.8.3
  540. // . 'BEGIN:VTIMEZONE' . PHP_EOL
  541. // . 'TZID:' . $timezone . PHP_EOL
  542. // . 'END:VTIMEZONE' . PHP_EOL;
  543. // TODO instead of PHP_EOL CRLF should be used for long entries
  544. // but test your solution against http://icalvalid.cloudapp.net/
  545. // also long lines SHOULD be split at 75 characters length
  546. foreach ($events as $event) {
  547. if ($event['adjust'] == 1) {
  548. $UTC = 'Z';
  549. } else {
  550. $UTC = '';
  551. }
  552. $o .= 'BEGIN:VEVENT' . PHP_EOL;
  553. if ($event[start]) {
  554. $tmp = strtotime($event['start']);
  555. $dtformat = "%Y%m%dT%H%M%S".$UTC;
  556. $o .= 'DTSTART:'.strftime($dtformat, $tmp).PHP_EOL;
  557. }
  558. if (!$event['nofinish']) {
  559. $tmp = strtotime($event['finish']);
  560. $dtformat = "%Y%m%dT%H%M%S".$UTC;
  561. $o .= 'DTEND:'.strftime($dtformat, $tmp).PHP_EOL;
  562. }
  563. if ($event['summary'])
  564. $tmp = $event['summary'];
  565. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  566. $tmp = addcslashes($tmp, ',;');
  567. $o .= 'SUMMARY:' . $tmp . PHP_EOL;
  568. if ($event['desc'])
  569. $tmp = $event['desc'];
  570. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  571. $tmp = addcslashes($tmp, ',;');
  572. $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
  573. if ($event['location']) {
  574. $tmp = $event['location'];
  575. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  576. $tmp = addcslashes($tmp, ',;');
  577. $o .= 'LOCATION:' . $tmp . PHP_EOL;
  578. }
  579. $o .= 'END:VEVENT' . PHP_EOL;
  580. $o .= PHP_EOL;
  581. }
  582. $o .= 'END:VCALENDAR' . PHP_EOL;
  583. break;
  584. }
  585. return $o;
  586. }
  587. /**
  588. * @brief Get all events for a user ID
  589. *
  590. * The query for events is done permission sensitive
  591. * If the user is the owner of the calendar he/she
  592. * will get all of his/her available events.
  593. * If the user is only a visitor only the public events will
  594. * be available
  595. *
  596. * @param int $uid The user ID
  597. * @param int $sql_extra Additional sql conditions for permission
  598. *
  599. * @return array Query results
  600. */
  601. function events_by_uid($uid = 0, $sql_extra = '') {
  602. if($uid == 0)
  603. return;
  604. // The permission condition if no condition was transmitted
  605. if($sql_extra == '')
  606. $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
  607. // does the user who requests happen to be the owner of the events
  608. // requested? then show all of your events, otherwise only those that
  609. // don't have limitations set in allow_cid and allow_gid
  610. if (local_user() == $uid) {
  611. $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
  612. FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
  613. intval($uid)
  614. );
  615. } else {
  616. $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
  617. FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
  618. intval($uid)
  619. );
  620. }
  621. if(count($r))
  622. return $r;
  623. }
  624. /**
  625. *
  626. * @param int $uid The user ID
  627. * @param string $format Output format (ical/csv)
  628. * @return array With the results
  629. * bool 'success' => True if the processing was successful
  630. * string 'format' => The output format
  631. * string 'extension' => The file extension of the output format
  632. * string 'content' => The formatted output content
  633. *
  634. * @todo Respect authenticated users with events_by_uid()
  635. */
  636. function event_export($uid, $format = 'ical') {
  637. $process = false;
  638. // we are allowed to show events
  639. // get the timezone the user is in
  640. $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
  641. if (count($r))
  642. $timezone = $r[0]['timezone'];
  643. // get all events which are owned by a uid (respects permissions);
  644. $events = events_by_uid($uid);
  645. // we have the events that are available for the requestor
  646. // now format the output according to the requested format
  647. if(count($events))
  648. $res = event_format_export($events, $format, $timezone);
  649. // If there are results the precess was successfull
  650. if(x($res))
  651. $process = true;
  652. // get the file extension for the format
  653. switch ($format) {
  654. case "ical":
  655. $file_ext = "ics";
  656. break;
  657. case "csv":
  658. $file_ext = "csv";
  659. break;
  660. default:
  661. $file_ext = "";
  662. }
  663. $arr = array(
  664. 'success' => $process,
  665. 'format' => $format,
  666. 'extension' => $file_ext,
  667. 'content' => $res,
  668. );
  669. return $arr;
  670. }
  671. /**
  672. * @brief Get the events widget
  673. *
  674. * @return string Formated html of the evens widget
  675. */
  676. function widget_events() {
  677. $a = get_app();
  678. $owner_uid = $a->data['user']['uid'];
  679. // $a->data is only available if the profile page is visited. If the visited page is not part
  680. // of the profile page it should be the personal /events page. So we can use $a->user
  681. $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
  682. // The permission testing is a little bit tricky because we have to respect many cases
  683. // It's not the private events page (we don't get the $owner_uid for /events)
  684. if(! local_user() && ! $owner_uid)
  685. return;
  686. // Cal logged in user (test permission at foreign profile page)
  687. // If the $owner uid is available we know it is part of one of the profile pages (like /cal)
  688. // So we have to test if if it's the own profile page of the logged in user
  689. // or a foreign one. For foreign profile pages we need to check if the feature
  690. // for exporting the cal is enabled (otherwise the widget would appear for logged in users
  691. // on foreigen profile pages even if the widget is disabled)
  692. if(intval($owner_uid) && local_user() !== $owner_uid && ! feature_enabled($owner_uid, "export_calendar"))
  693. return;
  694. // If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
  695. // export feature isn't enabled
  696. if(intval($owner_uid) && ! local_user() && ! feature_enabled($owner_uid, "export_calendar"))
  697. return;
  698. return replace_macros(get_markup_template("events_aside.tpl"), array(
  699. '$etitle' => t("Export"),
  700. '$export_ical' => t("Export calendar as ical"),
  701. '$export_csv' => t("Export calendar as csv"),
  702. '$user' => $user
  703. ));
  704. }