3 * @file include/event.php
4 * @brief functions specific to event handling
7 use Friendica\Content\Feature;
8 use Friendica\Core\Addon;
9 use Friendica\Core\L10n;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Item;
14 use Friendica\Model\Profile;
15 use Friendica\Util\Map;
16 use Friendica\Util\Temporal;
18 require_once 'include/bbcode.php';
19 require_once 'include/datetime.php';
20 require_once 'include/conversation.php';
22 function format_event_html($ev, $simple = false) {
23 if (! ((is_array($ev)) && count($ev))) {
27 $bd_format = L10n::t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM.
29 $event_start = day_translate(
31 Temporal::convert($ev['start'], date_default_timezone_get(), 'UTC', $bd_format)
32 : Temporal::utc($ev['start'], $bd_format)
35 $event_end = day_translate(
37 Temporal::convert($ev['finish'], date_default_timezone_get(), 'UTC', $bd_format)
38 : Temporal::utc($ev['finish'], $bd_format)
42 $o = "<h3>" . bbcode($ev['summary']) . "</h3>";
44 $o .= "<div>" . bbcode($ev['desc']) . "</div>";
46 $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
48 if (! $ev['nofinish']) {
49 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end ."</p>";
52 if (strlen($ev['location'])) {
53 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . $ev['location'] . "</p>";
59 $o = '<div class="vevent">' . "\r\n";
61 $o .= '<div class="summary event-summary">' . bbcode($ev['summary']) . '</div>' . "\r\n";
63 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
64 . Temporal::utc($ev['start'], (($ev['adjust']) ? Temporal::ATOM : 'Y-m-d\TH:i:s' ))
66 . '</span></div>' . "\r\n";
68 if (! $ev['nofinish']) {
69 $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
70 . Temporal::utc($ev['finish'], (($ev['adjust']) ? Temporal::ATOM : 'Y-m-d\TH:i:s' ))
72 . '</span></div>' . "\r\n";
75 $o .= '<div class="description event-description">' . bbcode($ev['desc']) . '</div>' . "\r\n";
77 if (strlen($ev['location'])) {
78 $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span> <span class="location">'
79 . bbcode($ev['location'])
80 . '</span></div>' . "\r\n";
82 // Include a map of the location if the [map] BBCode is used.
83 if (strpos($ev['location'], "[map") !== false) {
84 $map = Map::byLocation($ev['location']);
85 if ($map !== $ev['location']) {
91 $o .= '</div>' . "\r\n";
96 * @brief Convert an array with event data to bbcode.
98 * @param array $ev Array which conains the event data.
99 * @return string The event as a bbcode formatted string.
101 function format_event_bbcode($ev) {
105 if ($ev['summary']) {
106 $o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';
110 $o .= '[event-description]' . $ev['desc'] . '[/event-description]';
114 $o .= '[event-start]' . $ev['start'] . '[/event-start]';
117 if (($ev['finish']) && (! $ev['nofinish'])) {
118 $o .= '[event-finish]' . $ev['finish'] . '[/event-finish]';
121 if ($ev['location']) {
122 $o .= '[event-location]' . $ev['location'] . '[/event-location]';
126 $o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
133 * @brief Extract bbcode formatted event data from a string
134 * and convert it to html.
136 * @params: string $s The string which should be parsed for event data.
137 * @return string The html output.
139 function bbtovcal($s) {
144 $o = format_event_html($ev);
151 * @brief Extract bbcode formatted event data from a string.
153 * @params: string $s The string which should be parsed for event data.
154 * @return array The array with the event information.
156 function bbtoevent($s) {
161 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $s, $match)) {
162 $ev['summary'] = $match[1];
166 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $s, $match)) {
167 $ev['desc'] = $match[1];
171 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $s, $match)) {
172 $ev['start'] = $match[1];
176 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $s, $match)) {
177 $ev['finish'] = $match[1];
181 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $s, $match)) {
182 $ev['location'] = $match[1];
186 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $s, $match)) {
187 $ev['adjust'] = $match[1];
190 $ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
195 function sort_by_date($a) {
197 usort($a,'ev_compare');
201 function ev_compare($a,$b) {
203 $date_a = (($a['adjust']) ? Temporal::convert($a['start'], date_default_timezone_get()) : $a['start']);
204 $date_b = (($b['adjust']) ? Temporal::convert($b['start'], date_default_timezone_get()) : $b['start']);
206 if ($date_a === $date_b) {
207 return strcasecmp($a['desc'], $b['desc']);
210 return strcmp($date_a, $date_b);
214 * @brief Delete an event from the event table.
216 * Note: This function does only delete the event from the event table not its
217 * related entry in the item table.
219 * @param int $event_id Event ID.
222 function event_delete($event_id) {
223 if ($event_id == 0) {
227 dba::delete('event', ['id' => $event_id]);
228 logger("Deleted event ".$event_id, LOGGER_DEBUG);
232 * @brief Store the event.
234 * Store the event in the event table and create an event item in the item table.
236 * @param array $arr Array with event data.
237 * @return int The event id.
239 function event_store($arr) {
241 require_once 'include/datetime.php';
242 require_once 'include/items.php';
243 require_once 'include/bbcode.php';
247 $arr['created'] = (($arr['created']) ? $arr['created'] : Temporal::utcNow());
248 $arr['edited'] = (($arr['edited']) ? $arr['edited'] : Temporal::utcNow());
249 $arr['type'] = (($arr['type']) ? $arr['type'] : 'event' );
250 $arr['cid'] = ((intval($arr['cid'])) ? intval($arr['cid']) : 0);
251 $arr['uri'] = (x($arr, 'uri') ? $arr['uri'] : item_new_uri($a->get_hostname(), $arr['uid']));
252 $arr['private'] = ((x($arr, 'private')) ? intval($arr['private']) : 0);
253 $arr['guid'] = get_guid(32);
256 $c = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
261 $c = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
266 if (DBM::is_result($c)) {
270 // Existing event being modified.
273 // has the event actually changed?
274 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
278 if ((! DBM::is_result($r)) || ($r[0]['edited'] === $arr['edited'])) {
280 // Nothing has changed. Grab the item id to return.
281 $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
285 return ((DBM::is_result($r)) ? $r[0]['id'] : 0);
288 // The event changed. Update it.
289 q("UPDATE `event` SET
299 WHERE `id` = %d AND `uid` = %d",
301 dbesc($arr['edited']),
302 dbesc($arr['start']),
303 dbesc($arr['finish']),
304 dbesc($arr['summary']),
306 dbesc($arr['location']),
308 intval($arr['adjust']),
309 intval($arr['nofinish']),
314 $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
318 if (DBM::is_result($r)) {
319 $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
320 $object .= '<content>' . xmlify(format_event_bbcode($arr)) . '</content>';
321 $object .= '</object>' . "\n";
323 q("UPDATE `item` SET `body` = '%s', `object` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d",
324 dbesc(format_event_bbcode($arr)),
326 dbesc($arr['edited']),
331 $item_id = $r[0]['id'];
336 Addon::callHooks("event_updated", $arr['id']);
340 // New event. Store it.
341 q("INSERT INTO `event` (`uid`,`cid`,`guid`,`uri`,`created`,`edited`,`start`,`finish`,`summary`, `desc`,`location`,`type`,
342 `adjust`,`nofinish`,`allow_cid`,`allow_gid`,`deny_cid`,`deny_gid`)
343 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
348 dbesc($arr['created']),
349 dbesc($arr['edited']),
350 dbesc($arr['start']),
351 dbesc($arr['finish']),
352 dbesc($arr['summary']),
354 dbesc($arr['location']),
356 intval($arr['adjust']),
357 intval($arr['nofinish']),
358 dbesc($arr['allow_cid']),
359 dbesc($arr['allow_gid']),
360 dbesc($arr['deny_cid']),
361 dbesc($arr['deny_gid'])
364 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
368 if (DBM::is_result($r)) {
374 $item_arr['uid'] = $arr['uid'];
375 $item_arr['contact-id'] = $arr['cid'];
376 $item_arr['uri'] = $arr['uri'];
377 $item_arr['parent-uri'] = $arr['uri'];
378 $item_arr['guid'] = $arr['guid'];
379 $item_arr['type'] = 'activity';
380 $item_arr['wall'] = (($arr['cid']) ? 0 : 1);
381 $item_arr['contact-id'] = $contact['id'];
382 $item_arr['owner-name'] = $contact['name'];
383 $item_arr['owner-link'] = $contact['url'];
384 $item_arr['owner-avatar'] = $contact['thumb'];
385 $item_arr['author-name'] = $contact['name'];
386 $item_arr['author-link'] = $contact['url'];
387 $item_arr['author-avatar'] = $contact['thumb'];
388 $item_arr['title'] = '';
389 $item_arr['allow_cid'] = $arr['allow_cid'];
390 $item_arr['allow_gid'] = $arr['allow_gid'];
391 $item_arr['deny_cid'] = $arr['deny_cid'];
392 $item_arr['deny_gid'] = $arr['deny_gid'];
393 $item_arr['private'] = $arr['private'];
394 $item_arr['visible'] = 1;
395 $item_arr['verb'] = ACTIVITY_POST;
396 $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
397 $item_arr['origin'] = ((intval($arr['cid']) == 0) ? 1 : 0);
398 $item_arr['body'] = format_event_bbcode($event);
401 $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
402 $item_arr['object'] .= '<content>' . xmlify(format_event_bbcode($event)) . '</content>';
403 $item_arr['object'] .= '</object>' . "\n";
405 $item_id = Item::insert($item_arr);
407 q("UPDATE `item` SET `event-id` = %d WHERE `uid` = %d AND `id` = %d",
408 intval($event['id']),
414 Addon::callHooks("event_created", $event['id']);
421 * @brief Create an array with translation strings used for events.
423 * @return array Array with translations strings.
425 function get_event_strings() {
427 // First day of the week (0 = Sunday).
428 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
431 "firstDay" => $firstDay,
432 "allday" => L10n::t("all-day"),
434 "Sun" => L10n::t("Sun"),
435 "Mon" => L10n::t("Mon"),
436 "Tue" => L10n::t("Tue"),
437 "Wed" => L10n::t("Wed"),
438 "Thu" => L10n::t("Thu"),
439 "Fri" => L10n::t("Fri"),
440 "Sat" => L10n::t("Sat"),
442 "Sunday" => L10n::t("Sunday"),
443 "Monday" => L10n::t("Monday"),
444 "Tuesday" => L10n::t("Tuesday"),
445 "Wednesday" => L10n::t("Wednesday"),
446 "Thursday" => L10n::t("Thursday"),
447 "Friday" => L10n::t("Friday"),
448 "Saturday" => L10n::t("Saturday"),
450 "Jan" => L10n::t("Jan"),
451 "Feb" => L10n::t("Feb"),
452 "Mar" => L10n::t("Mar"),
453 "Apr" => L10n::t("Apr"),
454 "May" => L10n::t("May"),
455 "Jun" => L10n::t("Jun"),
456 "Jul" => L10n::t("Jul"),
457 "Aug" => L10n::t("Aug"),
458 "Sep" => L10n::t("Sept"),
459 "Oct" => L10n::t("Oct"),
460 "Nov" => L10n::t("Nov"),
461 "Dec" => L10n::t("Dec"),
463 "January" => L10n::t("January"),
464 "February" => L10n::t("February"),
465 "March" => L10n::t("March"),
466 "April" => L10n::t("April"),
467 "May" => L10n::t("May"),
468 "June" => L10n::t("June"),
469 "July" => L10n::t("July"),
470 "August" => L10n::t("August"),
471 "September" => L10n::t("September"),
472 "October" => L10n::t("October"),
473 "November" => L10n::t("November"),
474 "December" => L10n::t("December"),
476 "today" => L10n::t("today"),
477 "month" => L10n::t("month"),
478 "week" => L10n::t("week"),
479 "day" => L10n::t("day"),
481 "noevent" => L10n::t("No events to display"),
483 "dtstart_label" => L10n::t("Starts:"),
484 "dtend_label" => L10n::t("Finishes:"),
485 "location_label" => L10n::t("Location:")
492 * @brief Removes duplicated birthday events.
494 * @param array $dates Array of possibly duplicated events.
495 * @return array Cleaned events.
497 * @todo We should replace this with a separate update function if there is some time left.
499 function event_remove_duplicates($dates) {
502 foreach ($dates as $date) {
503 if ($date['type'] == 'birthday') {
504 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
513 * @brief Get an event by its event ID.
515 * @param int $owner_uid The User ID of the owner of the event
516 * @param array $event_params An assoziative array with
517 * int 'event_id' => The ID of the event in the event table
518 * @param string $sql_extra
519 * @return array Query result
521 function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
522 // Ownly allow events if there is a valid owner_id.
523 if ($owner_uid == 0) {
527 // Query for the event by event id
528 $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
529 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
530 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
531 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
533 intval($event_params["event_id"])
536 if (DBM::is_result($r)) {
537 return event_remove_duplicates($r);
542 * @brief Get all events in a specific timeframe.
544 * @param int $owner_uid The User ID of the owner of the events.
545 * @param array $event_params An assoziative array with
546 * int 'ignored' =><br>
547 * string 'start' => Start time of the timeframe.<br>
548 * string 'finish' => Finish time of the timeframe.<br>
549 * string 'adjust_start' =><br>
550 * string 'adjust_start' =>
552 * @param string $sql_extra Additional sql conditions (e.g. permission request).
554 * @return array Query results.
556 function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
557 // Only allow events if there is a valid owner_id.
558 if ($owner_uid == 0) {
562 // Query for the event by date.
563 $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
564 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
565 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
566 WHERE `event`.`uid` = %d AND event.ignore = %d
567 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
568 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
571 intval($event_params["ignored"]),
572 dbesc($event_params["start"]),
573 dbesc($event_params["start"]),
574 dbesc($event_params["finish"]),
575 dbesc($event_params["adjust_start"]),
576 dbesc($event_params["adjust_start"]),
577 dbesc($event_params["adjust_finish"])
580 if (DBM::is_result($r)) {
581 return event_remove_duplicates($r);
586 * @brief Convert an array query results in an arry which could be used by the events template.
588 * @param array $arr Event query array.
589 * @return array Event array for the template.
591 function process_events($arr) {
595 $fmt = L10n::t('l, F j');
597 foreach ($arr as $rr) {
598 $j = (($rr['adjust']) ? Temporal::convert($rr['start'], date_default_timezone_get(), 'UTC', 'j') : Temporal::utc($rr['start'], 'j'));
599 $d = (($rr['adjust']) ? Temporal::convert($rr['start'], date_default_timezone_get(), 'UTC', $fmt) : Temporal::utc($rr['start'], $fmt));
600 $d = day_translate($d);
602 $start = (($rr['adjust']) ? Temporal::convert($rr['start'], date_default_timezone_get(), 'UTC', 'c') : Temporal::utc($rr['start'], 'c'));
603 if ($rr['nofinish']) {
606 $end = (($rr['adjust']) ? Temporal::convert($rr['finish'], date_default_timezone_get(), 'UTC', 'c') : Temporal::utc($rr['finish'], 'c'));
609 $is_first = ($d !== $last_date);
613 // Show edit and drop actions only if the user is the owner of the event and the event
614 // is a real event (no bithdays).
618 if (local_user() && local_user() == $rr['uid'] && $rr['type'] == 'event') {
619 $edit = ((! $rr['cid']) ? [System::baseUrl() . '/events/event/' . $rr['id'], L10n::t('Edit event'), '', ''] : null);
620 $copy = ((! $rr['cid']) ? [System::baseUrl() . '/events/copy/' . $rr['id'], L10n::t('Duplicate event'), '', ''] : null);
621 $drop = [System::baseUrl() . '/events/drop/' . $rr['id'], L10n::t('Delete event'), '', ''];
624 $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
626 list($title, $_trash) = explode("<br", bbcode($rr['desc']), 2);
627 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
630 $html = format_event_html($rr);
631 $rr['desc'] = bbcode($rr['desc']);
632 $rr['location'] = bbcode($rr['location']);
645 'is_first' => $is_first,
648 'plink' => [$rr['plink'], L10n::t('link to source'), '', ''],
657 * @brief Format event to export format (ical/csv).
659 * @param array $events Query result for events.
660 * @param string $format The output format (ical/csv).
661 * @param string $timezone The timezone of the user (not implemented yet).
663 * @return string Content according to selected export format.
665 * @todo Implement timezone support
667 function event_format_export($events, $format = 'ical', $timezone)
669 if (!((is_array($events)) && count($events))) {
674 // Format the exported data as a CSV file.
676 header("Content-type: text/csv");
677 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
679 foreach ($events as $event) {
680 /// @todo The time / date entries don't include any information about the
681 /// timezone the event is scheduled in :-/
682 $tmp1 = strtotime($event['start']);
683 $tmp2 = strtotime($event['finish']);
684 $time_format = "%H:%M:%S";
685 $date_format = "%Y-%m-%d";
687 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
688 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
689 '", "' . strftime($date_format, $tmp2) .
690 '", "' . strftime($time_format, $tmp2) .
691 '", "' . $event['location'] . '"' . PHP_EOL;
695 // Format the exported data as a ics file.
697 header("Content-type: text/ics");
698 $o = 'BEGIN:VCALENDAR' . PHP_EOL
699 . 'VERSION:2.0' . PHP_EOL
700 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
701 /// @todo include timezone informations in cases were the time is not in UTC
702 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
703 // . 'BEGIN:VTIMEZONE' . PHP_EOL
704 // . 'TZID:' . $timezone . PHP_EOL
705 // . 'END:VTIMEZONE' . PHP_EOL;
706 // TODO instead of PHP_EOL CRLF should be used for long entries
707 // but test your solution against http://icalvalid.cloudapp.net/
708 // also long lines SHOULD be split at 75 characters length
709 foreach ($events as $event) {
710 if ($event['adjust'] == 1) {
715 $o .= 'BEGIN:VEVENT' . PHP_EOL;
717 if ($event['start']) {
718 $tmp = strtotime($event['start']);
719 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
720 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
723 if (!$event['nofinish']) {
724 $tmp = strtotime($event['finish']);
725 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
726 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
729 if ($event['summary']) {
730 $tmp = $event['summary'];
731 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
732 $tmp = addcslashes($tmp, ',;');
733 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
736 if ($event['desc']) {
737 $tmp = $event['desc'];
738 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
739 $tmp = addcslashes($tmp, ',;');
740 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
743 if ($event['location']) {
744 $tmp = $event['location'];
745 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
746 $tmp = addcslashes($tmp, ',;');
747 $o .= 'LOCATION:' . $tmp . PHP_EOL;
750 $o .= 'END:VEVENT' . PHP_EOL;
754 $o .= 'END:VCALENDAR' . PHP_EOL;
762 * @brief Get all events for a user ID.
764 * The query for events is done permission sensitive.
765 * If the user is the owner of the calendar he/she
766 * will get all of his/her available events.
767 * If the user is only a visitor only the public events will
770 * @param int $uid The user ID.
771 * @param int $sql_extra Additional sql conditions for permission.
773 * @return array Query results.
775 function events_by_uid($uid = 0, $sql_extra = '') {
780 // The permission condition if no condition was transmitted.
781 if ($sql_extra == '') {
782 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
785 // Does the user who requests happen to be the owner of the events
786 // requested? then show all of your events, otherwise only those that
787 // don't have limitations set in allow_cid and allow_gid.
788 if (local_user() == $uid) {
789 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
790 FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
794 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
795 FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
800 if (DBM::is_result($r)) {
807 * @param int $uid The user ID.
808 * @param string $format Output format (ical/csv).
809 * @return array With the results:
810 * bool 'success' => True if the processing was successful,<br>
811 * string 'format' => The output format,<br>
812 * string 'extension' => The file extension of the output format,<br>
813 * string 'content' => The formatted output content.<br>
815 * @todo Respect authenticated users with events_by_uid().
817 function event_export($uid, $format = 'ical') {
821 // We are allowed to show events.
822 // Get the timezone the user is in.
823 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
824 if (DBM::is_result($r)) {
825 $timezone = $r[0]['timezone'];
828 // Get all events which are owned by a uid (respects permissions).
829 $events = events_by_uid($uid);
831 // We have the events that are available for the requestor.
832 // Now format the output according to the requested format.
833 if (count($events)) {
834 $res = event_format_export($events, $format, $timezone);
837 // If there are results the precess was successfull.
842 // Get the file extension for the format.
857 'success' => $process,
859 'extension' => $file_ext,
867 * @brief Get the events widget.
869 * @return string Formated html of the evens widget.
871 function widget_events() {
874 $owner_uid = $a->data['user']['uid'];
875 // $a->data is only available if the profile page is visited. If the visited page is not part
876 // of the profile page it should be the personal /events page. So we can use $a->user.
877 $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
880 // The permission testing is a little bit tricky because we have to respect many cases.
882 // It's not the private events page (we don't get the $owner_uid for /events).
883 if (! local_user() && ! $owner_uid) {
888 * Cal logged in user (test permission at foreign profile page).
889 * If the $owner uid is available we know it is part of one of the profile pages (like /cal).
890 * So we have to test if if it's the own profile page of the logged in user
891 * or a foreign one. For foreign profile pages we need to check if the feature
892 * for exporting the cal is enabled (otherwise the widget would appear for logged in users
893 * on foreigen profile pages even if the widget is disabled).
895 if (intval($owner_uid) && local_user() !== $owner_uid && ! Feature::isEnabled($owner_uid, "export_calendar")) {
900 * If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
901 * export feature isn't enabled.
903 if (intval($owner_uid) && ! local_user() && ! Feature::isEnabled($owner_uid, "export_calendar")) {
907 return replace_macros(get_markup_template("events_aside.tpl"), [
908 '$etitle' => L10n::t("Export"),
909 '$export_ical' => L10n::t("Export calendar as ical"),
910 '$export_csv' => L10n::t("Export calendar as csv"),
916 * @brief Format an item array with event data to HTML.
918 * @param arr $item Array with item and event data.
919 * @return string HTML output.
921 function format_event_item($item) {
925 // Set the different time formats.
926 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
927 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
928 $tformat = L10n::t('g:i A'); // 8:01 AM.
930 // Convert the time to different formats.
931 $dtstart_dt = day_translate(
932 $item['event-adjust'] ?
933 Temporal::convert($item['event-start'], date_default_timezone_get(), 'UTC', $dformat)
934 : Temporal::utc($item['event-start'], $dformat)
936 $dtstart_title = Temporal::utc($item['event-start'], $item['event-adjust'] ? Temporal::ATOM : 'Y-m-d\TH:i:s');
937 // Format: Jan till Dec.
938 $month_short = day_short_translate(
939 $item['event-adjust'] ?
940 Temporal::convert($item['event-start'], date_default_timezone_get(), 'UTC', 'M')
941 : Temporal::utc($item['event-start'], 'M')
943 // Format: 1 till 31.
944 $date_short = $item['event-adjust'] ?
945 Temporal::convert($item['event-start'], date_default_timezone_get(), 'UTC', 'j')
946 : Temporal::utc($item['event-start'], 'j');
947 $start_time = $item['event-adjust'] ?
948 Temporal::convert($item['event-start'], date_default_timezone_get(), 'UTC', $tformat)
949 : Temporal::utc($item['event-start'], $tformat);
950 $start_short = day_short_translate(
951 $item['event-adjust'] ?
952 Temporal::convert($item['event-start'], date_default_timezone_get(), 'UTC', $dformat_short)
953 : Temporal::utc($item['event-start'], $dformat_short)
956 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
957 if (!$item['event-nofinish']) {
959 $dtend_dt = day_translate(
960 $item['event-adjust'] ?
961 Temporal::convert($item['event-finish'], date_default_timezone_get(), 'UTC', $dformat)
962 : Temporal::utc($item['event-finish'], $dformat)
964 $dtend_title = Temporal::utc($item['event-finish'], $item['event-adjust'] ? Temporal::ATOM : 'Y-m-d\TH:i:s');
965 $end_short = day_short_translate(
966 $item['event-adjust'] ?
967 Temporal::convert($item['event-finish'], date_default_timezone_get(), 'UTC', $dformat_short)
968 : Temporal::utc($item['event-finish'], $dformat_short)
970 $end_time = $item['event-adjust'] ?
971 Temporal::convert($item['event-finish'], date_default_timezone_get(), 'UTC', $tformat)
972 : Temporal::utc($item['event-finish'], $tformat);
973 // Check if start and finish time is at the same day.
974 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
979 // Format the event location.
980 $evloc = event_location2array($item['event-location']);
983 if (isset($evloc['name'])) {
984 $location['name'] = prepare_text($evloc['name']);
986 // Construct the map HTML.
987 if (isset($evloc['address'])) {
988 $location['map'] = '<div class="map">' . Map::byLocation($evloc['address']) . '</div>';
989 } elseif (isset($evloc['coordinates'])) {
990 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $evloc['coordinates'])) . '</div>';
993 // Construct the profile link (magic-auth).
995 $profile_link = best_link_url($item, $sp);
998 $profile_link = Profile::zrl($profile_link);
1001 $event = replace_macros(get_markup_template('event_stream_item.tpl'), [
1002 '$id' => $item['event-id'],
1003 '$title' => prepare_text($item['event-summary']),
1004 '$dtstart_label' => L10n::t('Starts:'),
1005 '$dtstart_title' => $dtstart_title,
1006 '$dtstart_dt' => $dtstart_dt,
1007 '$finish' => $finish,
1008 '$dtend_label' => L10n::t('Finishes:'),
1009 '$dtend_title' => $dtend_title,
1010 '$dtend_dt' => $dtend_dt,
1011 '$month_short' => $month_short,
1012 '$date_short' => $date_short,
1013 '$same_date' => $same_date,
1014 '$start_time' => $start_time,
1015 '$start_short' => $start_short,
1016 '$end_time' => $end_time,
1017 '$end_short' => $end_short,
1018 '$author_name' => $item['author-name'],
1019 '$author_link' => $profile_link,
1020 '$author_avatar' => $item['author-avatar'],
1021 '$description' => prepare_text($item['event-desc']),
1022 '$location_label' => L10n::t('Location:'),
1023 '$show_map_label' => L10n::t('Show map'),
1024 '$hide_map_label' => L10n::t('Hide map'),
1025 '$map_btn_label' => L10n::t('Show map'),
1026 '$location' => $location
1033 * @brief Format a string with map bbcode to an array with location data.
1035 * Note: The string must only contain location data. A string with no bbcode will be
1036 * handled as location name.
1038 * @param string $s The string with the bbcode formatted location data.
1040 * @return array The array with the location data.
1041 * 'name' => The name of the location,<br>
1042 * 'address' => The address of the location,<br>
1043 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
1045 function event_location2array($s = '') {
1050 $location = ['name' => $s];
1052 // Map tag with location name - e.g. [map]Paris[/map].
1053 if (strpos($s, '[/map]') !== false) {
1054 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
1055 if (intval($found) > 0 && array_key_exists(1, $match)) {
1056 $location['address'] = $match[1];
1057 // Remove the map bbcode from the location name.
1058 $location['name'] = str_replace($match[0], "", $s);
1060 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
1061 } elseif (strpos($s, '[map=') !== false) {
1062 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
1063 if (intval($found) > 0 && array_key_exists(1, $match)) {
1064 $location['coordinates'] = $match[1];
1065 // Remove the map bbcode from the location name.
1066 $location['name'] = str_replace($match[0], "", $s);