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.
 
 
 
 
 
 

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