3 * @file include/event.php
4 * @brief functions specific to event handling
7 use Friendica\Content\Feature;
8 use Friendica\Content\Text\BBCode;
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\Item;
15 use Friendica\Model\Profile;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Map;
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 = day_translate(
30 DateTimeFormat::local($ev['start'], $bd_format)
31 : DateTimeFormat::utc($ev['start'], $bd_format)
34 $event_end = day_translate(
36 DateTimeFormat::local($ev['finish'], $bd_format)
37 : DateTimeFormat::utc($ev['finish'], $bd_format)
41 $o = "<h3>" . BBCode::convert($ev['summary']) . "</h3>";
43 $o .= "<p>" . BBCode::convert($ev['desc']) . "</p>";
45 $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
47 if (! $ev['nofinish']) {
48 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end ."</p>";
51 if (strlen($ev['location'])) {
52 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . BBCode::convert($ev['location']) . "</p>";
58 $o = '<div class="vevent">' . "\r\n";
60 $o .= '<div class="summary event-summary">' . BBCode::convert($ev['summary']) . '</div>' . "\r\n";
62 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
63 . DateTimeFormat::utc($ev['start'], (($ev['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s' ))
65 . '</span></div>' . "\r\n";
67 if (! $ev['nofinish']) {
68 $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
69 . DateTimeFormat::utc($ev['finish'], (($ev['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s' ))
71 . '</span></div>' . "\r\n";
74 $o .= '<div class="description event-description">' . BBCode::convert($ev['desc']) . '</div>' . "\r\n";
76 if (strlen($ev['location'])) {
77 $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span> <span class="location">'
78 . BBCode::convert($ev['location'])
79 . '</span></div>' . "\r\n";
81 // Include a map of the location if the [map] BBCode is used.
82 if (strpos($ev['location'], "[map") !== false) {
83 $map = Map::byLocation($ev['location']);
84 if ($map !== $ev['location']) {
90 $o .= '</div>' . "\r\n";
95 * @brief Convert an array with event data to bbcode.
97 * @param array $ev Array which conains the event data.
98 * @return string The event as a bbcode formatted string.
100 function format_event_bbcode($ev) {
104 if ($ev['summary']) {
105 $o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';
109 $o .= '[event-description]' . $ev['desc'] . '[/event-description]';
113 $o .= '[event-start]' . $ev['start'] . '[/event-start]';
116 if (($ev['finish']) && (! $ev['nofinish'])) {
117 $o .= '[event-finish]' . $ev['finish'] . '[/event-finish]';
120 if ($ev['location']) {
121 $o .= '[event-location]' . $ev['location'] . '[/event-location]';
125 $o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
132 * @brief Extract bbcode formatted event data from a string
133 * and convert it to html.
135 * @params: string $s The string which should be parsed for event data.
136 * @return string The html output.
138 function bbtovcal($s) {
143 $o = format_event_html($ev);
150 * @brief Extract bbcode formatted event data from a string.
152 * @params: string $s The string which should be parsed for event data.
153 * @return array The array with the event information.
155 function bbtoevent($s) {
160 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $s, $match)) {
161 $ev['summary'] = $match[1];
165 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $s, $match)) {
166 $ev['desc'] = $match[1];
170 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $s, $match)) {
171 $ev['start'] = $match[1];
175 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $s, $match)) {
176 $ev['finish'] = $match[1];
180 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $s, $match)) {
181 $ev['location'] = $match[1];
185 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $s, $match)) {
186 $ev['adjust'] = $match[1];
189 $ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
194 function sort_by_date($a) {
196 usort($a,'ev_compare');
200 function ev_compare($a,$b) {
202 $date_a = (($a['adjust']) ? DateTimeFormat::local($a['start']) : $a['start']);
203 $date_b = (($b['adjust']) ? DateTimeFormat::local($b['start']) : $b['start']);
205 if ($date_a === $date_b) {
206 return strcasecmp($a['desc'], $b['desc']);
209 return strcmp($date_a, $date_b);
213 * @brief Delete an event from the event table.
215 * Note: This function does only delete the event from the event table not its
216 * related entry in the item table.
218 * @param int $event_id Event ID.
221 function event_delete($event_id) {
222 if ($event_id == 0) {
226 dba::delete('event', ['id' => $event_id]);
227 logger("Deleted event ".$event_id, LOGGER_DEBUG);
231 * @brief Store the event.
233 * Store the event in the event table and create an event item in the item table.
235 * @param array $arr Array with event data.
236 * @return int The event id.
238 function event_store($arr) {
240 require_once 'include/items.php';
244 $arr['created'] = (($arr['created']) ? $arr['created'] : DateTimeFormat::utcNow());
245 $arr['edited'] = (($arr['edited']) ? $arr['edited'] : DateTimeFormat::utcNow());
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 $fields = ['body' => format_event_bbcode($arr), 'object' => $object, 'edited' => $arr['edited']];
321 Item::update($fields, ['id' => $r[0]['id']]);
323 $item_id = $r[0]['id'];
328 Addon::callHooks("event_updated", $arr['id']);
332 // New event. Store it.
333 q("INSERT INTO `event` (`uid`,`cid`,`guid`,`uri`,`created`,`edited`,`start`,`finish`,`summary`, `desc`,`location`,`type`,
334 `adjust`,`nofinish`,`allow_cid`,`allow_gid`,`deny_cid`,`deny_gid`)
335 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
340 dbesc($arr['created']),
341 dbesc($arr['edited']),
342 dbesc($arr['start']),
343 dbesc($arr['finish']),
344 dbesc($arr['summary']),
346 dbesc($arr['location']),
348 intval($arr['adjust']),
349 intval($arr['nofinish']),
350 dbesc($arr['allow_cid']),
351 dbesc($arr['allow_gid']),
352 dbesc($arr['deny_cid']),
353 dbesc($arr['deny_gid'])
356 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
360 if (DBM::is_result($r)) {
366 $item_arr['uid'] = $arr['uid'];
367 $item_arr['contact-id'] = $arr['cid'];
368 $item_arr['uri'] = $arr['uri'];
369 $item_arr['parent-uri'] = $arr['uri'];
370 $item_arr['guid'] = $arr['guid'];
371 $item_arr['type'] = 'activity';
372 $item_arr['wall'] = (($arr['cid']) ? 0 : 1);
373 $item_arr['contact-id'] = $contact['id'];
374 $item_arr['owner-name'] = $contact['name'];
375 $item_arr['owner-link'] = $contact['url'];
376 $item_arr['owner-avatar'] = $contact['thumb'];
377 $item_arr['author-name'] = $contact['name'];
378 $item_arr['author-link'] = $contact['url'];
379 $item_arr['author-avatar'] = $contact['thumb'];
380 $item_arr['title'] = '';
381 $item_arr['allow_cid'] = $arr['allow_cid'];
382 $item_arr['allow_gid'] = $arr['allow_gid'];
383 $item_arr['deny_cid'] = $arr['deny_cid'];
384 $item_arr['deny_gid'] = $arr['deny_gid'];
385 $item_arr['private'] = $arr['private'];
386 $item_arr['visible'] = 1;
387 $item_arr['verb'] = ACTIVITY_POST;
388 $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
389 $item_arr['origin'] = ((intval($arr['cid']) == 0) ? 1 : 0);
390 $item_arr['body'] = format_event_bbcode($event);
393 $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
394 $item_arr['object'] .= '<content>' . xmlify(format_event_bbcode($event)) . '</content>';
395 $item_arr['object'] .= '</object>' . "\n";
397 $item_id = Item::insert($item_arr);
399 Item::update(['event-id' => $event['id']], ['id' => $item_id]);
402 Addon::callHooks("event_created", $event['id']);
409 * @brief Create an array with translation strings used for events.
411 * @return array Array with translations strings.
413 function get_event_strings() {
415 // First day of the week (0 = Sunday).
416 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
419 "firstDay" => $firstDay,
420 "allday" => L10n::t("all-day"),
422 "Sun" => L10n::t("Sun"),
423 "Mon" => L10n::t("Mon"),
424 "Tue" => L10n::t("Tue"),
425 "Wed" => L10n::t("Wed"),
426 "Thu" => L10n::t("Thu"),
427 "Fri" => L10n::t("Fri"),
428 "Sat" => L10n::t("Sat"),
430 "Sunday" => L10n::t("Sunday"),
431 "Monday" => L10n::t("Monday"),
432 "Tuesday" => L10n::t("Tuesday"),
433 "Wednesday" => L10n::t("Wednesday"),
434 "Thursday" => L10n::t("Thursday"),
435 "Friday" => L10n::t("Friday"),
436 "Saturday" => L10n::t("Saturday"),
438 "Jan" => L10n::t("Jan"),
439 "Feb" => L10n::t("Feb"),
440 "Mar" => L10n::t("Mar"),
441 "Apr" => L10n::t("Apr"),
442 "May" => L10n::t("May"),
443 "Jun" => L10n::t("Jun"),
444 "Jul" => L10n::t("Jul"),
445 "Aug" => L10n::t("Aug"),
446 "Sep" => L10n::t("Sept"),
447 "Oct" => L10n::t("Oct"),
448 "Nov" => L10n::t("Nov"),
449 "Dec" => L10n::t("Dec"),
451 "January" => L10n::t("January"),
452 "February" => L10n::t("February"),
453 "March" => L10n::t("March"),
454 "April" => L10n::t("April"),
455 "May" => L10n::t("May"),
456 "June" => L10n::t("June"),
457 "July" => L10n::t("July"),
458 "August" => L10n::t("August"),
459 "September" => L10n::t("September"),
460 "October" => L10n::t("October"),
461 "November" => L10n::t("November"),
462 "December" => L10n::t("December"),
464 "today" => L10n::t("today"),
465 "month" => L10n::t("month"),
466 "week" => L10n::t("week"),
467 "day" => L10n::t("day"),
469 "noevent" => L10n::t("No events to display"),
471 "dtstart_label" => L10n::t("Starts:"),
472 "dtend_label" => L10n::t("Finishes:"),
473 "location_label" => L10n::t("Location:")
480 * @brief Removes duplicated birthday events.
482 * @param array $dates Array of possibly duplicated events.
483 * @return array Cleaned events.
485 * @todo We should replace this with a separate update function if there is some time left.
487 function event_remove_duplicates($dates) {
490 foreach ($dates as $date) {
491 if ($date['type'] == 'birthday') {
492 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
501 * @brief Get an event by its event ID.
503 * @param int $owner_uid The User ID of the owner of the event
504 * @param array $event_params An assoziative array with
505 * int 'event_id' => The ID of the event in the event table
506 * @param string $sql_extra
507 * @return array Query result
509 function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
510 // Ownly allow events if there is a valid owner_id.
511 if ($owner_uid == 0) {
515 // Query for the event by event id
516 $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
517 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
518 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
519 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
521 intval($event_params["event_id"])
524 if (DBM::is_result($r)) {
525 return event_remove_duplicates($r);
530 * @brief Get all events in a specific timeframe.
532 * @param int $owner_uid The User ID of the owner of the events.
533 * @param array $event_params An assoziative array with
534 * int 'ignored' =><br>
535 * string 'start' => Start time of the timeframe.<br>
536 * string 'finish' => Finish time of the timeframe.<br>
537 * string 'adjust_start' =><br>
538 * string 'adjust_start' =>
540 * @param string $sql_extra Additional sql conditions (e.g. permission request).
542 * @return array Query results.
544 function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
545 // Only allow events if there is a valid owner_id.
546 if ($owner_uid == 0) {
550 // Query for the event by date.
551 $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
552 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
553 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
554 WHERE `event`.`uid` = %d AND event.ignore = %d
555 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
556 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
559 intval($event_params["ignored"]),
560 dbesc($event_params["start"]),
561 dbesc($event_params["start"]),
562 dbesc($event_params["finish"]),
563 dbesc($event_params["adjust_start"]),
564 dbesc($event_params["adjust_start"]),
565 dbesc($event_params["adjust_finish"])
568 if (DBM::is_result($r)) {
569 return event_remove_duplicates($r);
574 * @brief Convert an array query results in an arry which could be used by the events template.
576 * @param array $arr Event query array.
577 * @return array Event array for the template.
579 function process_events($arr) {
583 $fmt = L10n::t('l, F j');
585 foreach ($arr as $rr) {
586 $j = (($rr['adjust']) ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j'));
587 $d = (($rr['adjust']) ? DateTimeFormat::local($rr['start'], $fmt) : DateTimeFormat::utc($rr['start'], $fmt));
588 $d = day_translate($d);
590 $start = (($rr['adjust']) ? DateTimeFormat::local($rr['start'], 'c') : DateTimeFormat::utc($rr['start'], 'c'));
591 if ($rr['nofinish']) {
594 $end = (($rr['adjust']) ? DateTimeFormat::local($rr['finish'], 'c') : DateTimeFormat::utc($rr['finish'], 'c'));
597 $is_first = ($d !== $last_date);
601 // Show edit and drop actions only if the user is the owner of the event and the event
602 // is a real event (no bithdays).
606 if (local_user() && local_user() == $rr['uid'] && $rr['type'] == 'event') {
607 $edit = ((! $rr['cid']) ? [System::baseUrl() . '/events/event/' . $rr['id'], L10n::t('Edit event'), '', ''] : null);
608 $copy = ((! $rr['cid']) ? [System::baseUrl() . '/events/copy/' . $rr['id'], L10n::t('Duplicate event'), '', ''] : null);
609 $drop = [System::baseUrl() . '/events/drop/' . $rr['id'], L10n::t('Delete event'), '', ''];
612 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
614 list($title, $_trash) = explode("<br", BBCode::convert($rr['desc']), 2);
615 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
618 $html = format_event_html($rr);
619 $rr['desc'] = BBCode::convert($rr['desc']);
620 $rr['location'] = BBCode::convert($rr['location']);
633 'is_first' => $is_first,
636 'plink' => [$rr['plink'], L10n::t('link to source'), '', ''],
645 * @brief Format event to export format (ical/csv).
647 * @param array $events Query result for events.
648 * @param string $format The output format (ical/csv).
649 * @param string $timezone The timezone of the user (not implemented yet).
651 * @return string Content according to selected export format.
653 * @todo Implement timezone support
655 function event_format_export($events, $format = 'ical', $timezone)
657 if (!((is_array($events)) && count($events))) {
662 // Format the exported data as a CSV file.
664 header("Content-type: text/csv");
665 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
667 foreach ($events as $event) {
668 /// @todo The time / date entries don't include any information about the
669 /// timezone the event is scheduled in :-/
670 $tmp1 = strtotime($event['start']);
671 $tmp2 = strtotime($event['finish']);
672 $time_format = "%H:%M:%S";
673 $date_format = "%Y-%m-%d";
675 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
676 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
677 '", "' . strftime($date_format, $tmp2) .
678 '", "' . strftime($time_format, $tmp2) .
679 '", "' . $event['location'] . '"' . PHP_EOL;
683 // Format the exported data as a ics file.
685 header("Content-type: text/ics");
686 $o = 'BEGIN:VCALENDAR' . PHP_EOL
687 . 'VERSION:2.0' . PHP_EOL
688 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
689 /// @todo include timezone informations in cases were the time is not in UTC
690 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
691 // . 'BEGIN:VTIMEZONE' . PHP_EOL
692 // . 'TZID:' . $timezone . PHP_EOL
693 // . 'END:VTIMEZONE' . PHP_EOL;
694 // TODO instead of PHP_EOL CRLF should be used for long entries
695 // but test your solution against http://icalvalid.cloudapp.net/
696 // also long lines SHOULD be split at 75 characters length
697 foreach ($events as $event) {
698 if ($event['adjust'] == 1) {
703 $o .= 'BEGIN:VEVENT' . PHP_EOL;
705 if ($event['start']) {
706 $tmp = strtotime($event['start']);
707 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
708 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
711 if (!$event['nofinish']) {
712 $tmp = strtotime($event['finish']);
713 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
714 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
717 if ($event['summary']) {
718 $tmp = $event['summary'];
719 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
720 $tmp = addcslashes($tmp, ',;');
721 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
724 if ($event['desc']) {
725 $tmp = $event['desc'];
726 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
727 $tmp = addcslashes($tmp, ',;');
728 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
731 if ($event['location']) {
732 $tmp = $event['location'];
733 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
734 $tmp = addcslashes($tmp, ',;');
735 $o .= 'LOCATION:' . $tmp . PHP_EOL;
738 $o .= 'END:VEVENT' . PHP_EOL;
742 $o .= 'END:VCALENDAR' . PHP_EOL;
750 * @brief Get all events for a user ID.
752 * The query for events is done permission sensitive.
753 * If the user is the owner of the calendar he/she
754 * will get all of his/her available events.
755 * If the user is only a visitor only the public events will
758 * @param int $uid The user ID.
759 * @param int $sql_extra Additional sql conditions for permission.
761 * @return array Query results.
763 function events_by_uid($uid = 0, $sql_extra = '') {
768 // The permission condition if no condition was transmitted.
769 if ($sql_extra == '') {
770 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
773 // Does the user who requests happen to be the owner of the events
774 // requested? then show all of your events, otherwise only those that
775 // don't have limitations set in allow_cid and allow_gid.
776 if (local_user() == $uid) {
777 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
778 FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
782 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
783 FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
788 if (DBM::is_result($r)) {
795 * @param int $uid The user ID.
796 * @param string $format Output format (ical/csv).
797 * @return array With the results:
798 * bool 'success' => True if the processing was successful,<br>
799 * string 'format' => The output format,<br>
800 * string 'extension' => The file extension of the output format,<br>
801 * string 'content' => The formatted output content.<br>
803 * @todo Respect authenticated users with events_by_uid().
805 function event_export($uid, $format = 'ical') {
809 // We are allowed to show events.
810 // Get the timezone the user is in.
811 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
812 if (DBM::is_result($r)) {
813 $timezone = $r[0]['timezone'];
816 // Get all events which are owned by a uid (respects permissions).
817 $events = events_by_uid($uid);
819 // We have the events that are available for the requestor.
820 // Now format the output according to the requested format.
821 if (count($events)) {
822 $res = event_format_export($events, $format, $timezone);
825 // If there are results the precess was successfull.
830 // Get the file extension for the format.
845 'success' => $process,
847 'extension' => $file_ext,
855 * @brief Get the events widget.
857 * @return string Formated html of the evens widget.
859 function widget_events() {
862 $owner_uid = $a->data['user']['uid'];
863 // $a->data is only available if the profile page is visited. If the visited page is not part
864 // of the profile page it should be the personal /events page. So we can use $a->user.
865 $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
868 // The permission testing is a little bit tricky because we have to respect many cases.
870 // It's not the private events page (we don't get the $owner_uid for /events).
871 if (! local_user() && ! $owner_uid) {
876 * Cal logged in user (test permission at foreign profile page).
877 * If the $owner uid is available we know it is part of one of the profile pages (like /cal).
878 * So we have to test if if it's the own profile page of the logged in user
879 * or a foreign one. For foreign profile pages we need to check if the feature
880 * for exporting the cal is enabled (otherwise the widget would appear for logged in users
881 * on foreigen profile pages even if the widget is disabled).
883 if (intval($owner_uid) && local_user() !== $owner_uid && ! Feature::isEnabled($owner_uid, "export_calendar")) {
888 * If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
889 * export feature isn't enabled.
891 if (intval($owner_uid) && ! local_user() && ! Feature::isEnabled($owner_uid, "export_calendar")) {
895 return replace_macros(get_markup_template("events_aside.tpl"), [
896 '$etitle' => L10n::t("Export"),
897 '$export_ical' => L10n::t("Export calendar as ical"),
898 '$export_csv' => L10n::t("Export calendar as csv"),
904 * @brief Format an item array with event data to HTML.
906 * @param arr $item Array with item and event data.
907 * @return string HTML output.
909 function format_event_item($item) {
913 // Set the different time formats.
914 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
915 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
916 $tformat = L10n::t('g:i A'); // 8:01 AM.
918 // Convert the time to different formats.
919 $dtstart_dt = day_translate(
920 $item['event-adjust'] ?
921 DateTimeFormat::local($item['event-start'], $dformat)
922 : DateTimeFormat::utc($item['event-start'], $dformat)
924 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
925 // Format: Jan till Dec.
926 $month_short = day_short_translate(
927 $item['event-adjust'] ?
928 DateTimeFormat::local($item['event-start'], 'M')
929 : DateTimeFormat::utc($item['event-start'], 'M')
931 // Format: 1 till 31.
932 $date_short = $item['event-adjust'] ?
933 DateTimeFormat::local($item['event-start'], 'j')
934 : DateTimeFormat::utc($item['event-start'], 'j');
935 $start_time = $item['event-adjust'] ?
936 DateTimeFormat::local($item['event-start'], $tformat)
937 : DateTimeFormat::utc($item['event-start'], $tformat);
938 $start_short = day_short_translate(
939 $item['event-adjust'] ?
940 DateTimeFormat::local($item['event-start'], $dformat_short)
941 : DateTimeFormat::utc($item['event-start'], $dformat_short)
944 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
945 if (!$item['event-nofinish']) {
947 $dtend_dt = day_translate(
948 $item['event-adjust'] ?
949 DateTimeFormat::local($item['event-finish'], $dformat)
950 : DateTimeFormat::utc($item['event-finish'], $dformat)
952 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
953 $end_short = day_short_translate(
954 $item['event-adjust'] ?
955 DateTimeFormat::local($item['event-finish'], $dformat_short)
956 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
958 $end_time = $item['event-adjust'] ?
959 DateTimeFormat::local($item['event-finish'], $tformat)
960 : DateTimeFormat::utc($item['event-finish'], $tformat);
961 // Check if start and finish time is at the same day.
962 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
967 // Format the event location.
968 $evloc = event_location2array($item['event-location']);
971 if (isset($evloc['name'])) {
972 $location['name'] = prepare_text($evloc['name']);
974 // Construct the map HTML.
975 if (isset($evloc['address'])) {
976 $location['map'] = '<div class="map">' . Map::byLocation($evloc['address']) . '</div>';
977 } elseif (isset($evloc['coordinates'])) {
978 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $evloc['coordinates'])) . '</div>';
981 // Construct the profile link (magic-auth).
983 $profile_link = best_link_url($item, $sp);
986 $profile_link = Profile::zrl($profile_link);
989 $event = replace_macros(get_markup_template('event_stream_item.tpl'), [
990 '$id' => $item['event-id'],
991 '$title' => prepare_text($item['event-summary']),
992 '$dtstart_label' => L10n::t('Starts:'),
993 '$dtstart_title' => $dtstart_title,
994 '$dtstart_dt' => $dtstart_dt,
995 '$finish' => $finish,
996 '$dtend_label' => L10n::t('Finishes:'),
997 '$dtend_title' => $dtend_title,
998 '$dtend_dt' => $dtend_dt,
999 '$month_short' => $month_short,
1000 '$date_short' => $date_short,
1001 '$same_date' => $same_date,
1002 '$start_time' => $start_time,
1003 '$start_short' => $start_short,
1004 '$end_time' => $end_time,
1005 '$end_short' => $end_short,
1006 '$author_name' => $item['author-name'],
1007 '$author_link' => $profile_link,
1008 '$author_avatar' => $item['author-avatar'],
1009 '$description' => prepare_text($item['event-desc']),
1010 '$location_label' => L10n::t('Location:'),
1011 '$show_map_label' => L10n::t('Show map'),
1012 '$hide_map_label' => L10n::t('Hide map'),
1013 '$map_btn_label' => L10n::t('Show map'),
1014 '$location' => $location
1021 * @brief Format a string with map bbcode to an array with location data.
1023 * Note: The string must only contain location data. A string with no bbcode will be
1024 * handled as location name.
1026 * @param string $s The string with the bbcode formatted location data.
1028 * @return array The array with the location data.
1029 * 'name' => The name of the location,<br>
1030 * 'address' => The address of the location,<br>
1031 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
1033 function event_location2array($s = '') {
1038 $location = ['name' => $s];
1040 // Map tag with location name - e.g. [map]Paris[/map].
1041 if (strpos($s, '[/map]') !== false) {
1042 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
1043 if (intval($found) > 0 && array_key_exists(1, $match)) {
1044 $location['address'] = $match[1];
1045 // Remove the map bbcode from the location name.
1046 $location['name'] = str_replace($match[0], "", $s);
1048 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
1049 } elseif (strpos($s, '[map=') !== false) {
1050 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
1051 if (intval($found) > 0 && array_key_exists(1, $match)) {
1052 $location['coordinates'] = $match[1];
1053 // Remove the map bbcode from the location name.
1054 $location['name'] = str_replace($match[0], "", $s);