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.
 
 
 
 
 
 

858 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. $arr['guid'] = get_guid(32);
  182. if($arr['cid'])
  183. $c = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  184. intval($arr['cid']),
  185. intval($arr['uid'])
  186. );
  187. else
  188. $c = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
  189. intval($arr['uid'])
  190. );
  191. if(count($c))
  192. $contact = $c[0];
  193. // Existing event being modified
  194. if($arr['id']) {
  195. // has the event actually changed?
  196. $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  197. intval($arr['id']),
  198. intval($arr['uid'])
  199. );
  200. if((! dbm::is_result($r)) || ($r[0]['edited'] === $arr['edited'])) {
  201. // Nothing has changed. Grab the item id to return.
  202. $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
  203. intval($arr['id']),
  204. intval($arr['uid'])
  205. );
  206. return((dbm::is_result($r)) ? $r[0]['id'] : 0);
  207. }
  208. // The event changed. Update it.
  209. $r = q("UPDATE `event` SET
  210. `edited` = '%s',
  211. `start` = '%s',
  212. `finish` = '%s',
  213. `summary` = '%s',
  214. `desc` = '%s',
  215. `location` = '%s',
  216. `type` = '%s',
  217. `adjust` = %d,
  218. `nofinish` = %d
  219. WHERE `id` = %d AND `uid` = %d",
  220. dbesc($arr['edited']),
  221. dbesc($arr['start']),
  222. dbesc($arr['finish']),
  223. dbesc($arr['summary']),
  224. dbesc($arr['desc']),
  225. dbesc($arr['location']),
  226. dbesc($arr['type']),
  227. intval($arr['adjust']),
  228. intval($arr['nofinish']),
  229. intval($arr['id']),
  230. intval($arr['uid'])
  231. );
  232. $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
  233. intval($arr['id']),
  234. intval($arr['uid'])
  235. );
  236. if (dbm::is_result($r)) {
  237. $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
  238. $object .= '<content>' . xmlify(format_event_bbcode($arr)) . '</content>';
  239. $object .= '</object>' . "\n";
  240. q("UPDATE `item` SET `body` = '%s', `object` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d",
  241. dbesc(format_event_bbcode($arr)),
  242. dbesc($object),
  243. dbesc($arr['edited']),
  244. intval($r[0]['id']),
  245. intval($arr['uid'])
  246. );
  247. $item_id = $r[0]['id'];
  248. } else
  249. $item_id = 0;
  250. call_hooks("event_updated", $arr['id']);
  251. return $item_id;
  252. } else {
  253. // New event. Store it.
  254. $r = q("INSERT INTO `event` (`uid`,`cid`,`guid`,`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', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
  257. intval($arr['uid']),
  258. intval($arr['cid']),
  259. dbesc($arr['guid']),
  260. dbesc($arr['uri']),
  261. dbesc($arr['created']),
  262. dbesc($arr['edited']),
  263. dbesc($arr['start']),
  264. dbesc($arr['finish']),
  265. dbesc($arr['summary']),
  266. dbesc($arr['desc']),
  267. dbesc($arr['location']),
  268. dbesc($arr['type']),
  269. intval($arr['adjust']),
  270. intval($arr['nofinish']),
  271. dbesc($arr['allow_cid']),
  272. dbesc($arr['allow_gid']),
  273. dbesc($arr['deny_cid']),
  274. dbesc($arr['deny_gid'])
  275. );
  276. $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  277. dbesc($arr['uri']),
  278. intval($arr['uid'])
  279. );
  280. if (dbm::is_result($r))
  281. $event = $r[0];
  282. $item_arr = array();
  283. $item_arr['uid'] = $arr['uid'];
  284. $item_arr['contact-id'] = $arr['cid'];
  285. $item_arr['uri'] = $arr['uri'];
  286. $item_arr['parent-uri'] = $arr['uri'];
  287. $item_arr['guid'] = $arr['guid'];
  288. $item_arr['type'] = 'activity';
  289. $item_arr['wall'] = (($arr['cid']) ? 0 : 1);
  290. $item_arr['contact-id'] = $contact['id'];
  291. $item_arr['owner-name'] = $contact['name'];
  292. $item_arr['owner-link'] = $contact['url'];
  293. $item_arr['owner-avatar'] = $contact['thumb'];
  294. $item_arr['author-name'] = $contact['name'];
  295. $item_arr['author-link'] = $contact['url'];
  296. $item_arr['author-avatar'] = $contact['thumb'];
  297. $item_arr['title'] = '';
  298. $item_arr['allow_cid'] = $arr['allow_cid'];
  299. $item_arr['allow_gid'] = $arr['allow_gid'];
  300. $item_arr['deny_cid'] = $arr['deny_cid'];
  301. $item_arr['deny_gid'] = $arr['deny_gid'];
  302. $item_arr['private'] = $arr['private'];
  303. $item_arr['last-child'] = 1;
  304. $item_arr['visible'] = 1;
  305. $item_arr['verb'] = ACTIVITY_POST;
  306. $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
  307. $item_arr['origin'] = ((intval($arr['cid']) == 0) ? 1 : 0);
  308. $item_arr['body'] = format_event_bbcode($event);
  309. $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
  310. $item_arr['object'] .= '<content>' . xmlify(format_event_bbcode($event)) . '</content>';
  311. $item_arr['object'] .= '</object>' . "\n";
  312. $item_id = item_store($item_arr);
  313. $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  314. intval($arr['uid'])
  315. );
  316. //if (dbm::is_result($r))
  317. // $plink = App::get_baseurl() . '/display/' . $r[0]['nickname'] . '/' . $item_id;
  318. if($item_id) {
  319. //q("UPDATE `item` SET `plink` = '%s', `event-id` = %d WHERE `uid` = %d AND `id` = %d",
  320. // dbesc($plink),
  321. // intval($event['id']),
  322. // intval($arr['uid']),
  323. // intval($item_id)
  324. //);
  325. q("UPDATE `item` SET `event-id` = %d WHERE `uid` = %d AND `id` = %d",
  326. intval($event['id']),
  327. intval($arr['uid']),
  328. intval($item_id)
  329. );
  330. }
  331. call_hooks("event_created", $event['id']);
  332. return $item_id;
  333. }
  334. }
  335. function get_event_strings() {
  336. // First day of the week (0 = Sunday)
  337. $firstDay = get_pconfig(local_user(),'system','first_day_of_week');
  338. if ($firstDay === false) $firstDay=0;
  339. $i18n = array(
  340. "firstDay" => $firstDay,
  341. "Sun" => t("Sun"),
  342. "Mon" => t("Mon"),
  343. "Tue" => t("Tue"),
  344. "Wed" => t("Wed"),
  345. "Thu" => t("Thu"),
  346. "Fri" => t("Fri"),
  347. "Sat" => t("Sat"),
  348. "Sunday" => t("Sunday"),
  349. "Monday" => t("Monday"),
  350. "Tuesday" => t("Tuesday"),
  351. "Wednesday" => t("Wednesday"),
  352. "Thursday" => t("Thursday"),
  353. "Friday" => t("Friday"),
  354. "Saturday" => t("Saturday"),
  355. "Jan" => t("Jan"),
  356. "Feb" => t("Feb"),
  357. "Mar" => t("Mar"),
  358. "Apr" => t("Apr"),
  359. "May" => t("May"),
  360. "Jun" => t("Jun"),
  361. "Jul" => t("Jul"),
  362. "Aug" => t("Aug"),
  363. "Sep" => t("Sept"),
  364. "Oct" => t("Oct"),
  365. "Nov" => t("Nov"),
  366. "Dec" => t("Dec"),
  367. "January" => t("January"),
  368. "February" => t("February"),
  369. "March" => t("March"),
  370. "April" => t("April"),
  371. "May" => t("May"),
  372. "June" => t("June"),
  373. "July" => t("July"),
  374. "August" => t("August"),
  375. "September" => t("September"),
  376. "October" => t("October"),
  377. "November" => t("November"),
  378. "December" => t("December"),
  379. "today" => t("today"),
  380. "month" => t("month"),
  381. "week" => t("week"),
  382. "day" => t("day"),
  383. "allday" => t("all-day"),
  384. "noevent" => t("No events to display"),
  385. "dtstart_label" => t("Starts:"),
  386. "dtend_label" => t("Finishes:"),
  387. "location_label" => t("Location:")
  388. );
  389. return $i18n;
  390. }
  391. /**
  392. * @brief Get an event by its event ID
  393. *
  394. * @param type $owner_uid The User ID of the owner of the event
  395. * @param type $event_params An assoziative array with
  396. * int 'event_id' => The ID of the event in the event table
  397. * @param type $sql_extra
  398. * @return array Query result
  399. */
  400. function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
  401. // ownly allow events if there is a valid owner_id
  402. if($owner_uid == 0)
  403. return;
  404. // query for the event by event id
  405. $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
  406. `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
  407. LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
  408. WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
  409. intval($owner_uid),
  410. intval($event_params["event_id"])
  411. );
  412. if (dbm::is_result($r))
  413. return $r;
  414. }
  415. /**
  416. * @brief Get all events in a specific timeframe
  417. *
  418. * @param int $owner_uid The User ID of the owner of the events
  419. * @param array $event_params An assoziative array with
  420. * int 'ignored' =>
  421. * string 'start' => Start time of the timeframe
  422. * string 'finish' => Finish time of the timeframe
  423. * string 'adjust_start' =>
  424. * string 'adjust_start' =>
  425. *
  426. * @param string $sql_extra Additional sql conditions (e.g. permission request)
  427. * @return array Query results
  428. */
  429. function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
  430. // ownly allow events if there is a valid owner_id
  431. if($owner_uid == 0)
  432. return;
  433. // query for the event by date
  434. $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
  435. `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
  436. LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
  437. WHERE `event`.`uid` = %d AND event.ignore = %d
  438. AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
  439. OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
  440. $sql_extra ",
  441. intval($owner_uid),
  442. intval($event_params["ignored"]),
  443. dbesc($event_params["start"]),
  444. dbesc($event_params["start"]),
  445. dbesc($event_params["finish"]),
  446. dbesc($event_params["adjust_start"]),
  447. dbesc($event_params["adjust_start"]),
  448. dbesc($event_params["adjust_finish"])
  449. );
  450. if (dbm::is_result($r))
  451. return $r;
  452. }
  453. /**
  454. * @brief Convert an array query results in an arry which could be used by the events template
  455. *
  456. * @param array $arr Event query array
  457. * @return array Event array for the template
  458. */
  459. function process_events ($arr) {
  460. $events=array();
  461. $last_date = '';
  462. $fmt = t('l, F j');
  463. if (count($arr)) {
  464. foreach($arr as $rr) {
  465. $j = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], 'j') : datetime_convert('UTC','UTC',$rr['start'],'j'));
  466. $d = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], $fmt) : datetime_convert('UTC','UTC',$rr['start'],$fmt));
  467. $d = day_translate($d);
  468. $start = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], 'c') : datetime_convert('UTC','UTC',$rr['start'],'c'));
  469. if ($rr['nofinish']){
  470. $end = null;
  471. } else {
  472. $end = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['finish'], 'c') : datetime_convert('UTC','UTC',$rr['finish'],'c'));
  473. }
  474. $is_first = ($d !== $last_date);
  475. $last_date = $d;
  476. $edit = ((! $rr['cid']) ? array(App::get_baseurl().'/events/event/'.$rr['id'],t('Edit event'),'','') : null);
  477. $title = strip_tags(html_entity_decode(bbcode($rr['summary']),ENT_QUOTES,'UTF-8'));
  478. if(! $title) {
  479. list($title, $_trash) = explode("<br",bbcode($rr['desc']),2);
  480. $title = strip_tags(html_entity_decode($title,ENT_QUOTES,'UTF-8'));
  481. }
  482. $html = format_event_html($rr);
  483. $rr['desc'] = bbcode($rr['desc']);
  484. $rr['location'] = bbcode($rr['location']);
  485. $events[] = array(
  486. 'id'=>$rr['id'],
  487. 'start'=> $start,
  488. 'end' => $end,
  489. 'allDay' => false,
  490. 'title' => $title,
  491. 'j' => $j,
  492. 'd' => $d,
  493. 'is_first'=>$is_first,
  494. 'item'=>$rr,
  495. 'html'=>$html,
  496. 'plink' => array($rr['plink'],t('link to source'),'',''),
  497. );
  498. }
  499. }
  500. return $events;
  501. }
  502. /**
  503. * @brief Format event to export format (ical/csv)
  504. *
  505. * @param array $events Query result for events
  506. * @param string $format The output format (ical/csv)
  507. * @param string $timezone The timezone of the user (not implemented yet)
  508. *
  509. * @return string Content according to selected export format
  510. */
  511. function event_format_export ($events, $format = 'ical', $timezone) {
  512. if(! ((is_array($events)) && count($events)))
  513. return;
  514. switch ($format) {
  515. // format the exported data as a CSV file
  516. case "csv":
  517. header("Content-type: text/csv");
  518. $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
  519. foreach ($events as $event) {
  520. /// @todo the time / date entries don't include any information about the
  521. // timezone the event is scheduled in :-/
  522. $tmp1 = strtotime($event['start']);
  523. $tmp2 = strtotime($event['finish']);
  524. $time_format = "%H:%M:%S";
  525. $date_format = "%Y-%m-%d";
  526. $o .= '"'.$event['summary'].'", "'.strftime($date_format, $tmp1) .
  527. '", "'.strftime($time_format, $tmp1).'", "'.$event['desc'] .
  528. '", "'.strftime($date_format, $tmp2) .
  529. '", "'.strftime($time_format, $tmp2) .
  530. '", "'.$event['location'].'"' . PHP_EOL;
  531. }
  532. break;
  533. // format the exported data as a ics file
  534. case "ical":
  535. header("Content-type: text/ics");
  536. $o = 'BEGIN:VCALENDAR'. PHP_EOL
  537. . 'VERSION:2.0' . PHP_EOL
  538. . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
  539. /// @todo include timezone informations in cases were the time is not in UTC
  540. // see http://tools.ietf.org/html/rfc2445#section-4.8.3
  541. // . 'BEGIN:VTIMEZONE' . PHP_EOL
  542. // . 'TZID:' . $timezone . PHP_EOL
  543. // . 'END:VTIMEZONE' . PHP_EOL;
  544. // TODO instead of PHP_EOL CRLF should be used for long entries
  545. // but test your solution against http://icalvalid.cloudapp.net/
  546. // also long lines SHOULD be split at 75 characters length
  547. foreach ($events as $event) {
  548. if ($event['adjust'] == 1) {
  549. $UTC = 'Z';
  550. } else {
  551. $UTC = '';
  552. }
  553. $o .= 'BEGIN:VEVENT' . PHP_EOL;
  554. if ($event[start]) {
  555. $tmp = strtotime($event['start']);
  556. $dtformat = "%Y%m%dT%H%M%S".$UTC;
  557. $o .= 'DTSTART:'.strftime($dtformat, $tmp).PHP_EOL;
  558. }
  559. if (!$event['nofinish']) {
  560. $tmp = strtotime($event['finish']);
  561. $dtformat = "%Y%m%dT%H%M%S".$UTC;
  562. $o .= 'DTEND:'.strftime($dtformat, $tmp).PHP_EOL;
  563. }
  564. if ($event['summary'])
  565. $tmp = $event['summary'];
  566. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  567. $tmp = addcslashes($tmp, ',;');
  568. $o .= 'SUMMARY:' . $tmp . PHP_EOL;
  569. if ($event['desc'])
  570. $tmp = $event['desc'];
  571. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  572. $tmp = addcslashes($tmp, ',;');
  573. $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
  574. if ($event['location']) {
  575. $tmp = $event['location'];
  576. $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp);
  577. $tmp = addcslashes($tmp, ',;');
  578. $o .= 'LOCATION:' . $tmp . PHP_EOL;
  579. }
  580. $o .= 'END:VEVENT' . PHP_EOL;
  581. $o .= PHP_EOL;
  582. }
  583. $o .= 'END:VCALENDAR' . PHP_EOL;
  584. break;
  585. }
  586. return $o;
  587. }
  588. /**
  589. * @brief Get all events for a user ID
  590. *
  591. * The query for events is done permission sensitive
  592. * If the user is the owner of the calendar he/she
  593. * will get all of his/her available events.
  594. * If the user is only a visitor only the public events will
  595. * be available
  596. *
  597. * @param int $uid The user ID
  598. * @param int $sql_extra Additional sql conditions for permission
  599. *
  600. * @return array Query results
  601. */
  602. function events_by_uid($uid = 0, $sql_extra = '') {
  603. if($uid == 0)
  604. return;
  605. // The permission condition if no condition was transmitted
  606. if($sql_extra == '')
  607. $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
  608. // does the user who requests happen to be the owner of the events
  609. // requested? then show all of your events, otherwise only those that
  610. // don't have limitations set in allow_cid and allow_gid
  611. if (local_user() == $uid) {
  612. $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
  613. FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
  614. intval($uid)
  615. );
  616. } else {
  617. $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
  618. FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
  619. intval($uid)
  620. );
  621. }
  622. if (dbm::is_result($r))
  623. return $r;
  624. }
  625. /**
  626. *
  627. * @param int $uid The user ID
  628. * @param string $format Output format (ical/csv)
  629. * @return array With the results
  630. * bool 'success' => True if the processing was successful
  631. * string 'format' => The output format
  632. * string 'extension' => The file extension of the output format
  633. * string 'content' => The formatted output content
  634. *
  635. * @todo Respect authenticated users with events_by_uid()
  636. */
  637. function event_export($uid, $format = 'ical') {
  638. $process = false;
  639. // we are allowed to show events
  640. // get the timezone the user is in
  641. $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
  642. if (dbm::is_result($r))
  643. $timezone = $r[0]['timezone'];
  644. // get all events which are owned by a uid (respects permissions);
  645. $events = events_by_uid($uid);
  646. // we have the events that are available for the requestor
  647. // now format the output according to the requested format
  648. if(count($events))
  649. $res = event_format_export($events, $format, $timezone);
  650. // If there are results the precess was successfull
  651. if(x($res))
  652. $process = true;
  653. // get the file extension for the format
  654. switch ($format) {
  655. case "ical":
  656. $file_ext = "ics";
  657. break;
  658. case "csv":
  659. $file_ext = "csv";
  660. break;
  661. default:
  662. $file_ext = "";
  663. }
  664. $arr = array(
  665. 'success' => $process,
  666. 'format' => $format,
  667. 'extension' => $file_ext,
  668. 'content' => $res,
  669. );
  670. return $arr;
  671. }
  672. /**
  673. * @brief Get the events widget
  674. *
  675. * @return string Formated html of the evens widget
  676. */
  677. function widget_events() {
  678. $a = get_app();
  679. $owner_uid = $a->data['user']['uid'];
  680. // $a->data is only available if the profile page is visited. If the visited page is not part
  681. // of the profile page it should be the personal /events page. So we can use $a->user
  682. $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
  683. // The permission testing is a little bit tricky because we have to respect many cases
  684. // It's not the private events page (we don't get the $owner_uid for /events)
  685. if(! local_user() && ! $owner_uid)
  686. return;
  687. // Cal logged in user (test permission at foreign profile page)
  688. // If the $owner uid is available we know it is part of one of the profile pages (like /cal)
  689. // So we have to test if if it's the own profile page of the logged in user
  690. // or a foreign one. For foreign profile pages we need to check if the feature
  691. // for exporting the cal is enabled (otherwise the widget would appear for logged in users
  692. // on foreigen profile pages even if the widget is disabled)
  693. if(intval($owner_uid) && local_user() !== $owner_uid && ! feature_enabled($owner_uid, "export_calendar"))
  694. return;
  695. // If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
  696. // export feature isn't enabled
  697. if(intval($owner_uid) && ! local_user() && ! feature_enabled($owner_uid, "export_calendar"))
  698. return;
  699. return replace_macros(get_markup_template("events_aside.tpl"), array(
  700. '$etitle' => t("Export"),
  701. '$export_ical' => t("Export calendar as ical"),
  702. '$export_csv' => t("Export calendar as csv"),
  703. '$user' => $user
  704. ));
  705. }