3 * @file include/event.php
4 * @brief functions specific to event handling
8 use Friendica\Content\Feature;
9 use Friendica\Core\Addon;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Profile;
15 use Friendica\Util\Map;
17 require_once 'include/bbcode.php';
18 require_once 'include/datetime.php';
19 require_once 'include/conversation.php';
21 function format_event_html($ev, $simple = false) {
22 if (! ((is_array($ev)) && count($ev))) {
26 $bd_format = L10n::t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM.
28 $event_start = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
29 $ev['start'] , $bd_format ))
30 : day_translate(datetime_convert('UTC', 'UTC',
31 $ev['start'] , $bd_format)));
33 $event_end = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
34 $ev['finish'] , $bd_format ))
35 : day_translate(datetime_convert('UTC', 'UTC',
36 $ev['finish'] , $bd_format )));
39 $o = "<h3>" . bbcode($ev['summary']) . "</h3>";
41 $o .= "<div>" . bbcode($ev['desc']) . "</div>";
43 $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
45 if (! $ev['nofinish']) {
46 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end ."</p>";
49 if (strlen($ev['location'])) {
50 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . $ev['location'] . "</p>";
56 $o = '<div class="vevent">' . "\r\n";
58 $o .= '<div class="summary event-summary">' . bbcode($ev['summary']) . '</div>' . "\r\n";
60 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
61 . datetime_convert('UTC', 'UTC', $ev['start'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
63 . '</span></div>' . "\r\n";
65 if (! $ev['nofinish']) {
66 $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
67 . datetime_convert('UTC', 'UTC', $ev['finish'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
69 . '</span></div>' . "\r\n";
72 $o .= '<div class="description event-description">' . bbcode($ev['desc']) . '</div>' . "\r\n";
74 if (strlen($ev['location'])) {
75 $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span> <span class="location">'
76 . bbcode($ev['location'])
77 . '</span></div>' . "\r\n";
79 // Include a map of the location if the [map] BBCode is used.
80 if (strpos($ev['location'], "[map") !== false) {
81 $map = Map::byLocation($ev['location']);
82 if ($map !== $ev['location']) {
88 $o .= '</div>' . "\r\n";
93 * @brief Convert an array with event data to bbcode.
95 * @param array $ev Array which conains the event data.
96 * @return string The event as a bbcode formatted string.
98 function format_event_bbcode($ev) {
102 if ($ev['summary']) {
103 $o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';
107 $o .= '[event-description]' . $ev['desc'] . '[/event-description]';
111 $o .= '[event-start]' . $ev['start'] . '[/event-start]';
114 if (($ev['finish']) && (! $ev['nofinish'])) {
115 $o .= '[event-finish]' . $ev['finish'] . '[/event-finish]';
118 if ($ev['location']) {
119 $o .= '[event-location]' . $ev['location'] . '[/event-location]';
123 $o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
130 * @brief Extract bbcode formatted event data from a string
131 * and convert it to html.
133 * @params: string $s The string which should be parsed for event data.
134 * @return string The html output.
136 function bbtovcal($s) {
141 $o = format_event_html($ev);
148 * @brief Extract bbcode formatted event data from a string.
150 * @params: string $s The string which should be parsed for event data.
151 * @return array The array with the event information.
153 function bbtoevent($s) {
158 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $s, $match)) {
159 $ev['summary'] = $match[1];
163 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $s, $match)) {
164 $ev['desc'] = $match[1];
168 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $s, $match)) {
169 $ev['start'] = $match[1];
173 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $s, $match)) {
174 $ev['finish'] = $match[1];
178 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $s, $match)) {
179 $ev['location'] = $match[1];
183 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $s, $match)) {
184 $ev['adjust'] = $match[1];
187 $ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
192 function sort_by_date($a) {
194 usort($a,'ev_compare');
198 function ev_compare($a,$b) {
200 $date_a = (($a['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $a['start']) : $a['start']);
201 $date_b = (($b['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $b['start']) : $b['start']);
203 if ($date_a === $date_b) {
204 return strcasecmp($a['desc'], $b['desc']);
207 return strcmp($date_a, $date_b);
211 * @brief Delete an event from the event table.
213 * Note: This function does only delete the event from the event table not its
214 * related entry in the item table.
216 * @param int $event_id Event ID.
219 function event_delete($event_id) {
220 if ($event_id == 0) {
224 dba::delete('event', ['id' => $event_id]);
225 logger("Deleted event ".$event_id, LOGGER_DEBUG);
229 * @brief Store the event.
231 * Store the event in the event table and create an event item in the item table.
233 * @param array $arr Array with event data.
234 * @return int The event id.
236 function event_store($arr) {
238 require_once 'include/datetime.php';
239 require_once 'include/items.php';
240 require_once 'include/bbcode.php';
244 $arr['created'] = (($arr['created']) ? $arr['created'] : datetime_convert());
245 $arr['edited'] = (($arr['edited']) ? $arr['edited'] : datetime_convert());
246 $arr['type'] = (($arr['type']) ? $arr['type'] : 'event' );
247 $arr['cid'] = ((intval($arr['cid'])) ? intval($arr['cid']) : 0);
248 $arr['uri'] = (x($arr, 'uri') ? $arr['uri'] : item_new_uri($a->get_hostname(), $arr['uid']));
249 $arr['private'] = ((x($arr, 'private')) ? intval($arr['private']) : 0);
250 $arr['guid'] = get_guid(32);
253 $c = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
258 $c = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
263 if (DBM::is_result($c)) {
267 // Existing event being modified.
270 // has the event actually changed?
271 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
275 if ((! DBM::is_result($r)) || ($r[0]['edited'] === $arr['edited'])) {
277 // Nothing has changed. Grab the item id to return.
278 $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
282 return ((DBM::is_result($r)) ? $r[0]['id'] : 0);
285 // The event changed. Update it.
286 q("UPDATE `event` SET
296 WHERE `id` = %d AND `uid` = %d",
298 dbesc($arr['edited']),
299 dbesc($arr['start']),
300 dbesc($arr['finish']),
301 dbesc($arr['summary']),
303 dbesc($arr['location']),
305 intval($arr['adjust']),
306 intval($arr['nofinish']),
311 $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
315 if (DBM::is_result($r)) {
316 $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
317 $object .= '<content>' . xmlify(format_event_bbcode($arr)) . '</content>';
318 $object .= '</object>' . "\n";
320 q("UPDATE `item` SET `body` = '%s', `object` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d",
321 dbesc(format_event_bbcode($arr)),
323 dbesc($arr['edited']),
328 $item_id = $r[0]['id'];
333 Addon::callHooks("event_updated", $arr['id']);
337 // New event. Store it.
338 q("INSERT INTO `event` (`uid`,`cid`,`guid`,`uri`,`created`,`edited`,`start`,`finish`,`summary`, `desc`,`location`,`type`,
339 `adjust`,`nofinish`,`allow_cid`,`allow_gid`,`deny_cid`,`deny_gid`)
340 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
345 dbesc($arr['created']),
346 dbesc($arr['edited']),
347 dbesc($arr['start']),
348 dbesc($arr['finish']),
349 dbesc($arr['summary']),
351 dbesc($arr['location']),
353 intval($arr['adjust']),
354 intval($arr['nofinish']),
355 dbesc($arr['allow_cid']),
356 dbesc($arr['allow_gid']),
357 dbesc($arr['deny_cid']),
358 dbesc($arr['deny_gid'])
361 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
365 if (DBM::is_result($r)) {
371 $item_arr['uid'] = $arr['uid'];
372 $item_arr['contact-id'] = $arr['cid'];
373 $item_arr['uri'] = $arr['uri'];
374 $item_arr['parent-uri'] = $arr['uri'];
375 $item_arr['guid'] = $arr['guid'];
376 $item_arr['type'] = 'activity';
377 $item_arr['wall'] = (($arr['cid']) ? 0 : 1);
378 $item_arr['contact-id'] = $contact['id'];
379 $item_arr['owner-name'] = $contact['name'];
380 $item_arr['owner-link'] = $contact['url'];
381 $item_arr['owner-avatar'] = $contact['thumb'];
382 $item_arr['author-name'] = $contact['name'];
383 $item_arr['author-link'] = $contact['url'];
384 $item_arr['author-avatar'] = $contact['thumb'];
385 $item_arr['title'] = '';
386 $item_arr['allow_cid'] = $arr['allow_cid'];
387 $item_arr['allow_gid'] = $arr['allow_gid'];
388 $item_arr['deny_cid'] = $arr['deny_cid'];
389 $item_arr['deny_gid'] = $arr['deny_gid'];
390 $item_arr['private'] = $arr['private'];
391 $item_arr['visible'] = 1;
392 $item_arr['verb'] = ACTIVITY_POST;
393 $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
394 $item_arr['origin'] = ((intval($arr['cid']) == 0) ? 1 : 0);
395 $item_arr['body'] = format_event_bbcode($event);
398 $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
399 $item_arr['object'] .= '<content>' . xmlify(format_event_bbcode($event)) . '</content>';
400 $item_arr['object'] .= '</object>' . "\n";
402 $item_id = item_store($item_arr);
404 q("UPDATE `item` SET `event-id` = %d WHERE `uid` = %d AND `id` = %d",
405 intval($event['id']),
411 Addon::callHooks("event_created", $event['id']);
418 * @brief Create an array with translation strings used for events.
420 * @return array Array with translations strings.
422 function get_event_strings() {
424 // First day of the week (0 = Sunday).
425 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
428 "firstDay" => $firstDay,
429 "allday" => L10n::t("all-day"),
431 "Sun" => L10n::t("Sun"),
432 "Mon" => L10n::t("Mon"),
433 "Tue" => L10n::t("Tue"),
434 "Wed" => L10n::t("Wed"),
435 "Thu" => L10n::t("Thu"),
436 "Fri" => L10n::t("Fri"),
437 "Sat" => L10n::t("Sat"),
439 "Sunday" => L10n::t("Sunday"),
440 "Monday" => L10n::t("Monday"),
441 "Tuesday" => L10n::t("Tuesday"),
442 "Wednesday" => L10n::t("Wednesday"),
443 "Thursday" => L10n::t("Thursday"),
444 "Friday" => L10n::t("Friday"),
445 "Saturday" => L10n::t("Saturday"),
447 "Jan" => L10n::t("Jan"),
448 "Feb" => L10n::t("Feb"),
449 "Mar" => L10n::t("Mar"),
450 "Apr" => L10n::t("Apr"),
451 "May" => L10n::t("May"),
452 "Jun" => L10n::t("Jun"),
453 "Jul" => L10n::t("Jul"),
454 "Aug" => L10n::t("Aug"),
455 "Sep" => L10n::t("Sept"),
456 "Oct" => L10n::t("Oct"),
457 "Nov" => L10n::t("Nov"),
458 "Dec" => L10n::t("Dec"),
460 "January" => L10n::t("January"),
461 "February" => L10n::t("February"),
462 "March" => L10n::t("March"),
463 "April" => L10n::t("April"),
464 "May" => L10n::t("May"),
465 "June" => L10n::t("June"),
466 "July" => L10n::t("July"),
467 "August" => L10n::t("August"),
468 "September" => L10n::t("September"),
469 "October" => L10n::t("October"),
470 "November" => L10n::t("November"),
471 "December" => L10n::t("December"),
473 "today" => L10n::t("today"),
474 "month" => L10n::t("month"),
475 "week" => L10n::t("week"),
476 "day" => L10n::t("day"),
478 "noevent" => L10n::t("No events to display"),
480 "dtstart_label" => L10n::t("Starts:"),
481 "dtend_label" => L10n::t("Finishes:"),
482 "location_label" => L10n::t("Location:")
489 * @brief Removes duplicated birthday events.
491 * @param array $dates Array of possibly duplicated events.
492 * @return array Cleaned events.
494 * @todo We should replace this with a separate update function if there is some time left.
496 function event_remove_duplicates($dates) {
499 foreach ($dates as $date) {
500 if ($date['type'] == 'birthday') {
501 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
510 * @brief Get an event by its event ID.
512 * @param int $owner_uid The User ID of the owner of the event
513 * @param array $event_params An assoziative array with
514 * int 'event_id' => The ID of the event in the event table
515 * @param string $sql_extra
516 * @return array Query result
518 function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
519 // Ownly allow events if there is a valid owner_id.
520 if ($owner_uid == 0) {
524 // Query for the event by event id
525 $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
526 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
527 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
528 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
530 intval($event_params["event_id"])
533 if (DBM::is_result($r)) {
534 return event_remove_duplicates($r);
539 * @brief Get all events in a specific timeframe.
541 * @param int $owner_uid The User ID of the owner of the events.
542 * @param array $event_params An assoziative array with
543 * int 'ignored' =><br>
544 * string 'start' => Start time of the timeframe.<br>
545 * string 'finish' => Finish time of the timeframe.<br>
546 * string 'adjust_start' =><br>
547 * string 'adjust_start' =>
549 * @param string $sql_extra Additional sql conditions (e.g. permission request).
551 * @return array Query results.
553 function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
554 // Only allow events if there is a valid owner_id.
555 if ($owner_uid == 0) {
559 // Query for the event by date.
560 $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
561 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
562 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
563 WHERE `event`.`uid` = %d AND event.ignore = %d
564 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
565 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
568 intval($event_params["ignored"]),
569 dbesc($event_params["start"]),
570 dbesc($event_params["start"]),
571 dbesc($event_params["finish"]),
572 dbesc($event_params["adjust_start"]),
573 dbesc($event_params["adjust_start"]),
574 dbesc($event_params["adjust_finish"])
577 if (DBM::is_result($r)) {
578 return event_remove_duplicates($r);
583 * @brief Convert an array query results in an arry which could be used by the events template.
585 * @param array $arr Event query array.
586 * @return array Event array for the template.
588 function process_events($arr) {
592 $fmt = L10n::t('l, F j');
594 foreach ($arr as $rr) {
595 $j = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'j') : datetime_convert('UTC', 'UTC', $rr['start'], 'j'));
596 $d = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], $fmt) : datetime_convert('UTC', 'UTC', $rr['start'], $fmt));
597 $d = day_translate($d);
599 $start = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'c') : datetime_convert('UTC', 'UTC', $rr['start'], 'c'));
600 if ($rr['nofinish']) {
603 $end = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['finish'], 'c') : datetime_convert('UTC', 'UTC', $rr['finish'], 'c'));
606 $is_first = ($d !== $last_date);
610 // Show edit and drop actions only if the user is the owner of the event and the event
611 // is a real event (no bithdays).
615 if (local_user() && local_user() == $rr['uid'] && $rr['type'] == 'event') {
616 $edit = ((! $rr['cid']) ? [System::baseUrl() . '/events/event/' . $rr['id'], L10n::t('Edit event'), '', ''] : null);
617 $copy = ((! $rr['cid']) ? [System::baseUrl() . '/events/copy/' . $rr['id'], L10n::t('Duplicate event'), '', ''] : null);
618 $drop = [System::baseUrl() . '/events/drop/' . $rr['id'], L10n::t('Delete event'), '', ''];
621 $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
623 list($title, $_trash) = explode("<br", bbcode($rr['desc']), 2);
624 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
627 $html = format_event_html($rr);
628 $rr['desc'] = bbcode($rr['desc']);
629 $rr['location'] = bbcode($rr['location']);
642 'is_first' => $is_first,
645 'plink' => [$rr['plink'], L10n::t('link to source'), '', ''],
654 * @brief Format event to export format (ical/csv).
656 * @param array $events Query result for events.
657 * @param string $format The output format (ical/csv).
658 * @param string $timezone The timezone of the user (not implemented yet).
660 * @return string Content according to selected export format.
662 * @todo Implement timezone support
664 function event_format_export($events, $format = 'ical', $timezone)
666 if (!((is_array($events)) && count($events))) {
671 // Format the exported data as a CSV file.
673 header("Content-type: text/csv");
674 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
676 foreach ($events as $event) {
677 /// @todo The time / date entries don't include any information about the
678 /// timezone the event is scheduled in :-/
679 $tmp1 = strtotime($event['start']);
680 $tmp2 = strtotime($event['finish']);
681 $time_format = "%H:%M:%S";
682 $date_format = "%Y-%m-%d";
684 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
685 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
686 '", "' . strftime($date_format, $tmp2) .
687 '", "' . strftime($time_format, $tmp2) .
688 '", "' . $event['location'] . '"' . PHP_EOL;
692 // Format the exported data as a ics file.
694 header("Content-type: text/ics");
695 $o = 'BEGIN:VCALENDAR' . PHP_EOL
696 . 'VERSION:2.0' . PHP_EOL
697 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
698 /// @todo include timezone informations in cases were the time is not in UTC
699 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
700 // . 'BEGIN:VTIMEZONE' . PHP_EOL
701 // . 'TZID:' . $timezone . PHP_EOL
702 // . 'END:VTIMEZONE' . PHP_EOL;
703 // TODO instead of PHP_EOL CRLF should be used for long entries
704 // but test your solution against http://icalvalid.cloudapp.net/
705 // also long lines SHOULD be split at 75 characters length
706 foreach ($events as $event) {
707 if ($event['adjust'] == 1) {
712 $o .= 'BEGIN:VEVENT' . PHP_EOL;
714 if ($event['start']) {
715 $tmp = strtotime($event['start']);
716 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
717 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
720 if (!$event['nofinish']) {
721 $tmp = strtotime($event['finish']);
722 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
723 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
726 if ($event['summary']) {
727 $tmp = $event['summary'];
728 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
729 $tmp = addcslashes($tmp, ',;');
730 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
733 if ($event['desc']) {
734 $tmp = $event['desc'];
735 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
736 $tmp = addcslashes($tmp, ',;');
737 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
740 if ($event['location']) {
741 $tmp = $event['location'];
742 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
743 $tmp = addcslashes($tmp, ',;');
744 $o .= 'LOCATION:' . $tmp . PHP_EOL;
747 $o .= 'END:VEVENT' . PHP_EOL;
751 $o .= 'END:VCALENDAR' . PHP_EOL;
759 * @brief Get all events for a user ID.
761 * The query for events is done permission sensitive.
762 * If the user is the owner of the calendar he/she
763 * will get all of his/her available events.
764 * If the user is only a visitor only the public events will
767 * @param int $uid The user ID.
768 * @param int $sql_extra Additional sql conditions for permission.
770 * @return array Query results.
772 function events_by_uid($uid = 0, $sql_extra = '') {
777 // The permission condition if no condition was transmitted.
778 if ($sql_extra == '') {
779 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
782 // Does the user who requests happen to be the owner of the events
783 // requested? then show all of your events, otherwise only those that
784 // don't have limitations set in allow_cid and allow_gid.
785 if (local_user() == $uid) {
786 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
787 FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
791 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
792 FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
797 if (DBM::is_result($r)) {
804 * @param int $uid The user ID.
805 * @param string $format Output format (ical/csv).
806 * @return array With the results:
807 * bool 'success' => True if the processing was successful,<br>
808 * string 'format' => The output format,<br>
809 * string 'extension' => The file extension of the output format,<br>
810 * string 'content' => The formatted output content.<br>
812 * @todo Respect authenticated users with events_by_uid().
814 function event_export($uid, $format = 'ical') {
818 // We are allowed to show events.
819 // Get the timezone the user is in.
820 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
821 if (DBM::is_result($r)) {
822 $timezone = $r[0]['timezone'];
825 // Get all events which are owned by a uid (respects permissions).
826 $events = events_by_uid($uid);
828 // We have the events that are available for the requestor.
829 // Now format the output according to the requested format.
830 if (count($events)) {
831 $res = event_format_export($events, $format, $timezone);
834 // If there are results the precess was successfull.
839 // Get the file extension for the format.
854 'success' => $process,
856 'extension' => $file_ext,
864 * @brief Get the events widget.
866 * @return string Formated html of the evens widget.
868 function widget_events() {
871 $owner_uid = $a->data['user']['uid'];
872 // $a->data is only available if the profile page is visited. If the visited page is not part
873 // of the profile page it should be the personal /events page. So we can use $a->user.
874 $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
877 // The permission testing is a little bit tricky because we have to respect many cases.
879 // It's not the private events page (we don't get the $owner_uid for /events).
880 if (! local_user() && ! $owner_uid) {
885 * Cal logged in user (test permission at foreign profile page).
886 * If the $owner uid is available we know it is part of one of the profile pages (like /cal).
887 * So we have to test if if it's the own profile page of the logged in user
888 * or a foreign one. For foreign profile pages we need to check if the feature
889 * for exporting the cal is enabled (otherwise the widget would appear for logged in users
890 * on foreigen profile pages even if the widget is disabled).
892 if (intval($owner_uid) && local_user() !== $owner_uid && ! Feature::isEnabled($owner_uid, "export_calendar")) {
897 * If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
898 * export feature isn't enabled.
900 if (intval($owner_uid) && ! local_user() && ! Feature::isEnabled($owner_uid, "export_calendar")) {
904 return replace_macros(get_markup_template("events_aside.tpl"), [
905 '$etitle' => L10n::t("Export"),
906 '$export_ical' => L10n::t("Export calendar as ical"),
907 '$export_csv' => L10n::t("Export calendar as csv"),
913 * @brief Format an item array with event data to HTML.
915 * @param arr $item Array with item and event data.
916 * @return string HTML output.
918 function format_event_item($item) {
922 // Set the different time formats.
923 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
924 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
925 $tformat = L10n::t('g:i A'); // 8:01 AM.
927 // Convert the time to different formats.
928 $dtstart_dt = (($item['event-adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], $dformat)) : day_translate(datetime_convert('UTC', 'UTC', $item['event-start'], $dformat)));
929 $dtstart_title = datetime_convert('UTC', 'UTC', $item['event-start'], (($item['event-adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s'));
930 // Format: Jan till Dec.
931 $month_short = (($item['event-adjust']) ? day_short_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], 'M')) : day_short_translate(datetime_convert('UTC', 'UTC', $item['event-start'], 'M')));
932 // Format: 1 till 31.
933 $date_short = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], 'j') : datetime_convert('UTC', 'UTC', $item['event-start'], 'j'));
934 $start_time = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], $tformat) : datetime_convert('UTC', 'UTC', $item['event-start'], $tformat));
935 $start_short = (($item['event-adjust']) ? day_short_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], $dformat_short)) : day_short_translate(datetime_convert('UTC', 'UTC', $item['event-start'], $dformat_short)));
937 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
938 if (!$item['event-nofinish']) {
940 $dtend_dt = (($item['event-adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-finish'], $dformat)) : day_translate(datetime_convert('UTC', 'UTC', $item['event-finish'], $dformat)));
941 $dtend_title = datetime_convert('UTC', 'UTC', $item['event-finish'], (($item['event-adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s'));
942 $end_short = (($item['event-adjust']) ? day_short_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-finish'], $dformat_short)) : day_short_translate(datetime_convert('UTC', 'UTC', $item['event-finish'], $dformat_short)));
943 $end_time = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-finish'], $tformat) : datetime_convert('UTC', 'UTC', $item['event-finish'], $tformat));
944 // Check if start and finish time is at the same day.
945 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
950 // Format the event location.
951 $evloc = event_location2array($item['event-location']);
954 if (isset($evloc['name'])) {
955 $location['name'] = prepare_text($evloc['name']);
957 // Construct the map HTML.
958 if (isset($evloc['address'])) {
959 $location['map'] = '<div class="map">' . Map::byLocation($evloc['address']) . '</div>';
960 } elseif (isset($evloc['coordinates'])) {
961 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $evloc['coordinates'])) . '</div>';
964 // Construct the profile link (magic-auth).
966 $profile_link = best_link_url($item, $sp);
969 $profile_link = Profile::zrl($profile_link);
972 $event = replace_macros(get_markup_template('event_stream_item.tpl'), [
973 '$id' => $item['event-id'],
974 '$title' => prepare_text($item['event-summary']),
975 '$dtstart_label' => L10n::t('Starts:'),
976 '$dtstart_title' => $dtstart_title,
977 '$dtstart_dt' => $dtstart_dt,
978 '$finish' => $finish,
979 '$dtend_label' => L10n::t('Finishes:'),
980 '$dtend_title' => $dtend_title,
981 '$dtend_dt' => $dtend_dt,
982 '$month_short' => $month_short,
983 '$date_short' => $date_short,
984 '$same_date' => $same_date,
985 '$start_time' => $start_time,
986 '$start_short' => $start_short,
987 '$end_time' => $end_time,
988 '$end_short' => $end_short,
989 '$author_name' => $item['author-name'],
990 '$author_link' => $profile_link,
991 '$author_avatar' => $item['author-avatar'],
992 '$description' => prepare_text($item['event-desc']),
993 '$location_label' => L10n::t('Location:'),
994 '$show_map_label' => L10n::t('Show map'),
995 '$hide_map_label' => L10n::t('Hide map'),
996 '$map_btn_label' => L10n::t('Show map'),
997 '$location' => $location
1004 * @brief Format a string with map bbcode to an array with location data.
1006 * Note: The string must only contain location data. A string with no bbcode will be
1007 * handled as location name.
1009 * @param string $s The string with the bbcode formatted location data.
1011 * @return array The array with the location data.
1012 * 'name' => The name of the location,<br>
1013 * 'address' => The address of the location,<br>
1014 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
1016 function event_location2array($s = '') {
1021 $location = ['name' => $s];
1023 // Map tag with location name - e.g. [map]Paris[/map].
1024 if (strpos($s, '[/map]') !== false) {
1025 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
1026 if (intval($found) > 0 && array_key_exists(1, $match)) {
1027 $location['address'] = $match[1];
1028 // Remove the map bbcode from the location name.
1029 $location['name'] = str_replace($match[0], "", $s);
1031 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
1032 } elseif (strpos($s, '[map=') !== false) {
1033 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
1034 if (intval($found) > 0 && array_key_exists(1, $match)) {
1035 $location['coordinates'] = $match[1];
1036 // Remove the map bbcode from the location name.
1037 $location['name'] = str_replace($match[0], "", $s);