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.
 
 
 
 
 
 

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