3 * @file src/Model/Event.php
6 namespace Friendica\Model;
8 use Friendica\BaseObject;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Addon;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Contact;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Map;
20 require_once 'boot.php';
21 require_once 'include/dba.php';
22 require_once 'include/items.php';
25 * @brief functions for interacting with the event database table
27 class Event extends BaseObject
30 public static function getHTML(array $event, $simple = false)
36 $bd_format = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8 AM.
38 $event_start = day_translate(
39 !empty($event['adjust']) ?
40 DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
43 if (!empty($event['finish'])) {
44 $event_end = day_translate(
45 !empty($event['adjust']) ?
46 DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
53 if (!empty($event['summary'])) {
54 $o = "<h3>" . BBCode::convert($event['summary'], false, $simple) . "</h3>";
57 if (!empty($event['desc'])) {
58 $o .= "<div>" . BBCode::convert($event['desc'], false, $simple) . "</div>";
61 $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
63 if (!$event['nofinish']) {
64 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end . "</p>";
67 if (!empty($event['location'])) {
68 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . BBCode::convert($event['location'], false, $simple) . "</p>";
74 $o = '<div class="vevent">' . "\r\n";
76 $o .= '<div class="summary event-summary">' . BBCode::convert($event['summary'], false, $simple) . '</div>' . "\r\n";
78 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
79 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
80 . '" >' . $event_start
81 . '</span></div>' . "\r\n";
83 if (!$event['nofinish']) {
84 $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
85 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
87 . '</span></div>' . "\r\n";
90 if (!empty($event['desc'])) {
91 $o .= '<div class="description event-description">' . BBCode::convert($event['desc'], false, $simple) . '</div>' . "\r\n";
94 if (!empty($event['location'])) {
95 $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span> <span class="location">'
96 . BBCode::convert($event['location'], false, $simple)
97 . '</span></div>' . "\r\n";
99 // Include a map of the location if the [map] BBCode is used.
100 if (strpos($event['location'], "[map") !== false) {
101 $map = Map::byLocation($event['location'], $simple);
102 if ($map !== $event['location']) {
108 $o .= '</div>' . "\r\n";
113 * @brief Convert an array with event data to bbcode.
115 * @param array $event Array which contains the event data.
116 * @return string The event as a bbcode formatted string.
118 private static function getBBCode(array $event)
122 if ($event['summary']) {
123 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
126 if ($event['desc']) {
127 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
130 if ($event['start']) {
131 $o .= '[event-start]' . $event['start'] . '[/event-start]';
134 if (($event['finish']) && (!$event['nofinish'])) {
135 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
138 if ($event['location']) {
139 $o .= '[event-location]' . $event['location'] . '[/event-location]';
142 if ($event['adjust']) {
143 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
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 public static function fromBBCode($text)
160 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
161 $ev['summary'] = $match[1];
165 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
166 $ev['desc'] = $match[1];
170 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
171 $ev['start'] = $match[1];
175 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
176 $ev['finish'] = $match[1];
180 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
181 $ev['location'] = $match[1];
185 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
186 $ev['adjust'] = $match[1];
189 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
194 public static function sortByDate($event_list)
196 usort($event_list, ['self', 'compareDatesCallback']);
200 private static function compareDatesCallback($event_a, $event_b)
202 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
203 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
205 if ($date_a === $date_b) {
206 return strcasecmp($event_a['desc'], $event_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 public static function delete($event_id)
223 if ($event_id == 0) {
227 DBA::delete('event', ['id' => $event_id]);
228 Logger::log("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 new event id.
239 public static function store($arr)
244 $event['id'] = intval(defaults($arr, 'id' , 0));
245 $event['uid'] = intval(defaults($arr, 'uid' , 0));
246 $event['cid'] = intval(defaults($arr, 'cid' , 0));
247 $event['uri'] = defaults($arr, 'uri' , Item::newURI($event['uid']));
248 $event['type'] = defaults($arr, 'type' , 'event');
249 $event['summary'] = defaults($arr, 'summary' , '');
250 $event['desc'] = defaults($arr, 'desc' , '');
251 $event['location'] = defaults($arr, 'location' , '');
252 $event['allow_cid'] = defaults($arr, 'allow_cid', '');
253 $event['allow_gid'] = defaults($arr, 'allow_gid', '');
254 $event['deny_cid'] = defaults($arr, 'deny_cid' , '');
255 $event['deny_gid'] = defaults($arr, 'deny_gid' , '');
256 $event['adjust'] = intval(defaults($arr, 'adjust' , 0));
257 $event['nofinish'] = intval(defaults($arr, 'nofinish' , !empty($event['start']) && empty($event['finish'])));
259 $event['created'] = DateTimeFormat::utc(defaults($arr, 'created' , 'now'));
260 $event['edited'] = DateTimeFormat::utc(defaults($arr, 'edited' , 'now'));
261 $event['start'] = DateTimeFormat::utc(defaults($arr, 'start' , DBA::NULL_DATETIME));
262 $event['finish'] = DateTimeFormat::utc(defaults($arr, 'finish' , DBA::NULL_DATETIME));
263 if ($event['finish'] < DBA::NULL_DATETIME) {
264 $event['finish'] = DBA::NULL_DATETIME;
266 $private = intval(defaults($arr, 'private', 0));
268 $conditions = ['uid' => $event['uid']];
270 $conditions['id'] = $event['cid'];
272 $conditions['self'] = true;
275 $contact = DBA::selectFirst('contact', [], $conditions);
277 // Existing event being modified.
279 // has the event actually changed?
280 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
281 if (!DBA::isResult($existing_event) || ($existing_event['edited'] === $event['edited'])) {
283 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
285 return DBA::isResult($item) ? $item['id'] : 0;
289 'edited' => $event['edited'],
290 'start' => $event['start'],
291 'finish' => $event['finish'],
292 'summary' => $event['summary'],
293 'desc' => $event['desc'],
294 'location' => $event['location'],
295 'type' => $event['type'],
296 'adjust' => $event['adjust'],
297 'nofinish' => $event['nofinish'],
300 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
302 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
303 if (DBA::isResult($item)) {
304 $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($event['uri']) . '</id>';
305 $object .= '<content>' . xmlify(self::getBBCode($event)) . '</content>';
306 $object .= '</object>' . "\n";
308 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
309 Item::update($fields, ['id' => $item['id']]);
311 $item_id = $item['id'];
316 Addon::callHooks('event_updated', $event['id']);
318 $event['guid'] = defaults($arr, 'guid', System::createUUID());
320 // New event. Store it.
321 DBA::insert('event', $event);
323 $event['id'] = DBA::lastInsertId();
327 $item_arr['uid'] = $event['uid'];
328 $item_arr['contact-id'] = $event['cid'];
329 $item_arr['uri'] = $event['uri'];
330 $item_arr['parent-uri'] = $event['uri'];
331 $item_arr['guid'] = $event['guid'];
332 $item_arr['plink'] = defaults($arr, 'plink', '');
333 $item_arr['post-type'] = Item::PT_EVENT;
334 $item_arr['wall'] = $event['cid'] ? 0 : 1;
335 $item_arr['contact-id'] = $contact['id'];
336 $item_arr['owner-name'] = $contact['name'];
337 $item_arr['owner-link'] = $contact['url'];
338 $item_arr['owner-avatar'] = $contact['thumb'];
339 $item_arr['author-name'] = $contact['name'];
340 $item_arr['author-link'] = $contact['url'];
341 $item_arr['author-avatar'] = $contact['thumb'];
342 $item_arr['title'] = '';
343 $item_arr['allow_cid'] = $event['allow_cid'];
344 $item_arr['allow_gid'] = $event['allow_gid'];
345 $item_arr['deny_cid'] = $event['deny_cid'];
346 $item_arr['deny_gid'] = $event['deny_gid'];
347 $item_arr['private'] = $private;
348 $item_arr['visible'] = 1;
349 $item_arr['verb'] = ACTIVITY_POST;
350 $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
351 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
352 $item_arr['body'] = self::getBBCode($event);
353 $item_arr['event-id'] = $event['id'];
355 $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($event['uri']) . '</id>';
356 $item_arr['object'] .= '<content>' . xmlify(self::getBBCode($event)) . '</content>';
357 $item_arr['object'] .= '</object>' . "\n";
359 $item_id = Item::insert($item_arr);
361 Addon::callHooks("event_created", $event['id']);
368 * @brief Create an array with translation strings used for events.
370 * @return array Array with translations strings.
372 public static function getStrings()
374 // First day of the week (0 = Sunday).
375 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
378 "firstDay" => $firstDay,
379 "allday" => L10n::t("all-day"),
381 "Sun" => L10n::t("Sun"),
382 "Mon" => L10n::t("Mon"),
383 "Tue" => L10n::t("Tue"),
384 "Wed" => L10n::t("Wed"),
385 "Thu" => L10n::t("Thu"),
386 "Fri" => L10n::t("Fri"),
387 "Sat" => L10n::t("Sat"),
389 "Sunday" => L10n::t("Sunday"),
390 "Monday" => L10n::t("Monday"),
391 "Tuesday" => L10n::t("Tuesday"),
392 "Wednesday" => L10n::t("Wednesday"),
393 "Thursday" => L10n::t("Thursday"),
394 "Friday" => L10n::t("Friday"),
395 "Saturday" => L10n::t("Saturday"),
397 "Jan" => L10n::t("Jan"),
398 "Feb" => L10n::t("Feb"),
399 "Mar" => L10n::t("Mar"),
400 "Apr" => L10n::t("Apr"),
401 "May" => L10n::t("May"),
402 "Jun" => L10n::t("Jun"),
403 "Jul" => L10n::t("Jul"),
404 "Aug" => L10n::t("Aug"),
405 "Sep" => L10n::t("Sept"),
406 "Oct" => L10n::t("Oct"),
407 "Nov" => L10n::t("Nov"),
408 "Dec" => L10n::t("Dec"),
410 "January" => L10n::t("January"),
411 "February" => L10n::t("February"),
412 "March" => L10n::t("March"),
413 "April" => L10n::t("April"),
414 "May" => L10n::t("May"),
415 "June" => L10n::t("June"),
416 "July" => L10n::t("July"),
417 "August" => L10n::t("August"),
418 "September" => L10n::t("September"),
419 "October" => L10n::t("October"),
420 "November" => L10n::t("November"),
421 "December" => L10n::t("December"),
423 "today" => L10n::t("today"),
424 "month" => L10n::t("month"),
425 "week" => L10n::t("week"),
426 "day" => L10n::t("day"),
428 "noevent" => L10n::t("No events to display"),
430 "dtstart_label" => L10n::t("Starts:"),
431 "dtend_label" => L10n::t("Finishes:"),
432 "location_label" => L10n::t("Location:")
439 * @brief Removes duplicated birthday events.
441 * @param array $dates Array of possibly duplicated events.
442 * @return array Cleaned events.
444 * @todo We should replace this with a separate update function if there is some time left.
446 private static function removeDuplicates(array $dates)
450 foreach ($dates as $date) {
451 if ($date['type'] == 'birthday') {
452 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
457 return array_values($dates2);
461 * @brief Get an event by its event ID.
463 * @param int $owner_uid The User ID of the owner of the event
464 * @param int $event_id The ID of the event in the event table
465 * @param string $sql_extra
466 * @return array Query result
468 public static function getListById($owner_uid, $event_id, $sql_extra = '')
472 // Ownly allow events if there is a valid owner_id.
473 if ($owner_uid == 0) {
477 // Query for the event by event id
478 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
479 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
480 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
485 if (DBA::isResult($r)) {
486 $return = self::removeDuplicates($r);
493 * @brief Get all events in a specific time frame.
495 * @param int $owner_uid The User ID of the owner of the events.
496 * @param array $event_params An associative array with
498 * string 'start' => Start time of the timeframe.
499 * string 'finish' => Finish time of the timeframe.
500 * string 'adjust_start' =>
501 * string 'adjust_finish' =>
503 * @param string $sql_extra Additional sql conditions (e.g. permission request).
505 * @return array Query results.
507 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
511 // Only allow events if there is a valid owner_id.
512 if ($owner_uid == 0) {
516 // Query for the event by date.
517 // @todo Slow query (518 seconds to run), to be optimzed
518 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
519 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
520 WHERE `event`.`uid` = %d AND event.ignore = %d
521 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
522 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
525 intval($event_params["ignore"]),
526 DBA::escape($event_params["start"]),
527 DBA::escape($event_params["start"]),
528 DBA::escape($event_params["finish"]),
529 DBA::escape($event_params["adjust_start"]),
530 DBA::escape($event_params["adjust_start"]),
531 DBA::escape($event_params["adjust_finish"])
534 if (DBA::isResult($r)) {
535 $return = self::removeDuplicates($r);
542 * @brief Convert an array query results in an array which could be used by the events template.
544 * @param array $event_result Event query array.
545 * @return array Event array for the template.
547 public static function prepareListForTemplate(array $event_result)
552 $fmt = L10n::t('l, F j');
553 foreach ($event_result as $event) {
554 $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
555 if (!DBA::isResult($item)) {
556 // Using default values when no item had been found
557 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
560 $event = array_merge($event, $item);
562 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
563 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
564 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
565 $day = day_translate($day);
567 if ($event['nofinish']) {
570 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
573 $is_first = ($day !== $last_date);
577 // Show edit and drop actions only if the user is the owner of the event and the event
578 // is a real event (no bithdays).
582 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
583 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event') , '', ''] : null;
584 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
585 $drop = [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event') , '', ''];
588 $title = strip_tags(html_entity_decode(BBCode::convert($event['summary']), ENT_QUOTES, 'UTF-8'));
590 list($title, $_trash) = explode("<br", BBCode::convert($event['desc']), 2);
591 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
594 $author_link = $event['author-link'];
595 $plink = $event['plink'];
597 $event['author-link'] = Contact::magicLink($author_link);
598 $event['plink'] = Contact::magicLink($author_link, $plink);
600 $html = self::getHTML($event);
601 $event['desc'] = BBCode::convert($event['desc']);
602 $event['location'] = BBCode::convert($event['location']);
604 'id' => $event['id'],
614 'is_first' => $is_first,
617 'plink' => [$event['plink'], L10n::t('link to source'), '', ''],
625 * @brief Format event to export format (ical/csv).
627 * @param array $events Query result for events.
628 * @param string $format The output format (ical/csv).
629 * @param string $timezone The timezone of the user (not implemented yet).
631 * @return string Content according to selected export format.
633 * @todo Implement timezone support
635 private static function formatListForExport(array $events, $format, $timezone)
637 if (!count($events)) {
642 // Format the exported data as a CSV file.
644 header("Content-type: text/csv");
645 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
647 foreach ($events as $event) {
648 /// @todo The time / date entries don't include any information about the
649 /// timezone the event is scheduled in :-/
650 $tmp1 = strtotime($event['start']);
651 $tmp2 = strtotime($event['finish']);
652 $time_format = "%H:%M:%S";
653 $date_format = "%Y-%m-%d";
655 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
656 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
657 '", "' . strftime($date_format, $tmp2) .
658 '", "' . strftime($time_format, $tmp2) .
659 '", "' . $event['location'] . '"' . PHP_EOL;
663 // Format the exported data as a ics file.
665 header("Content-type: text/ics");
666 $o = 'BEGIN:VCALENDAR' . PHP_EOL
667 . 'VERSION:2.0' . PHP_EOL
668 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
669 /// @todo include timezone informations in cases were the time is not in UTC
670 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
671 // . 'BEGIN:VTIMEZONE' . PHP_EOL
672 // . 'TZID:' . $timezone . PHP_EOL
673 // . 'END:VTIMEZONE' . PHP_EOL;
674 // TODO instead of PHP_EOL CRLF should be used for long entries
675 // but test your solution against http://icalvalid.cloudapp.net/
676 // also long lines SHOULD be split at 75 characters length
677 foreach ($events as $event) {
678 if ($event['adjust'] == 1) {
683 $o .= 'BEGIN:VEVENT' . PHP_EOL;
685 if ($event['start']) {
686 $tmp = strtotime($event['start']);
687 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
688 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
691 if (!$event['nofinish']) {
692 $tmp = strtotime($event['finish']);
693 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
694 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
697 if ($event['summary']) {
698 $tmp = $event['summary'];
699 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
700 $tmp = addcslashes($tmp, ',;');
701 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
704 if ($event['desc']) {
705 $tmp = $event['desc'];
706 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
707 $tmp = addcslashes($tmp, ',;');
708 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
711 if ($event['location']) {
712 $tmp = $event['location'];
713 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
714 $tmp = addcslashes($tmp, ',;');
715 $o .= 'LOCATION:' . $tmp . PHP_EOL;
718 $o .= 'END:VEVENT' . PHP_EOL;
722 $o .= 'END:VCALENDAR' . PHP_EOL;
730 * @brief Get all events for a user ID.
732 * The query for events is done permission sensitive.
733 * If the user is the owner of the calendar they
734 * will get all of their available events.
735 * If the user is only a visitor only the public events will
738 * @param int $uid The user ID.
740 * @return array Query results.
742 private static function getListByUserId($uid = 0)
750 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
752 $conditions = ['uid' => $uid, 'cid' => 0];
754 // Does the user who requests happen to be the owner of the events
755 // requested? then show all of your events, otherwise only those that
756 // don't have limitations set in allow_cid and allow_gid.
757 if (local_user() != $uid) {
758 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
761 $events = DBA::select('event', $fields, $conditions);
762 if (DBA::isResult($events)) {
763 $return = DBA::toArray($events);
771 * @param int $uid The user ID.
772 * @param string $format Output format (ical/csv).
773 * @return array With the results:
774 * bool 'success' => True if the processing was successful,<br>
775 * string 'format' => The output format,<br>
776 * string 'extension' => The file extension of the output format,<br>
777 * string 'content' => The formatted output content.<br>
779 * @todo Respect authenticated users with events_by_uid().
781 public static function exportListByUserId($uid, $format = 'ical')
785 $user = DBA::selectFirst('user', ['timezone'], ['uid' => $uid]);
786 if (DBA::isResult($user)) {
787 $timezone = $user['timezone'];
790 // Get all events which are owned by a uid (respects permissions).
791 $events = self::getListByUserId($uid);
793 // We have the events that are available for the requestor.
794 // Now format the output according to the requested format.
795 $res = self::formatListForExport($events, $format, $timezone);
797 // If there are results the precess was successfull.
802 // Get the file extension for the format.
817 'success' => $process,
819 'extension' => $file_ext,
827 * @brief Format an item array with event data to HTML.
829 * @param array $item Array with item and event data.
830 * @return string HTML output.
832 public static function getItemHTML(array $item) {
836 // Set the different time formats.
837 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
838 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
839 $tformat = L10n::t('g:i A'); // 8:01 AM.
841 // Convert the time to different formats.
842 $dtstart_dt = day_translate(
843 $item['event-adjust'] ?
844 DateTimeFormat::local($item['event-start'], $dformat)
845 : DateTimeFormat::utc($item['event-start'], $dformat)
847 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
848 // Format: Jan till Dec.
849 $month_short = day_short_translate(
850 $item['event-adjust'] ?
851 DateTimeFormat::local($item['event-start'], 'M')
852 : DateTimeFormat::utc($item['event-start'], 'M')
854 // Format: 1 till 31.
855 $date_short = $item['event-adjust'] ?
856 DateTimeFormat::local($item['event-start'], 'j')
857 : DateTimeFormat::utc($item['event-start'], 'j');
858 $start_time = $item['event-adjust'] ?
859 DateTimeFormat::local($item['event-start'], $tformat)
860 : DateTimeFormat::utc($item['event-start'], $tformat);
861 $start_short = day_short_translate(
862 $item['event-adjust'] ?
863 DateTimeFormat::local($item['event-start'], $dformat_short)
864 : DateTimeFormat::utc($item['event-start'], $dformat_short)
867 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
868 if (!$item['event-nofinish']) {
870 $dtend_dt = day_translate(
871 $item['event-adjust'] ?
872 DateTimeFormat::local($item['event-finish'], $dformat)
873 : DateTimeFormat::utc($item['event-finish'], $dformat)
875 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
876 $end_short = day_short_translate(
877 $item['event-adjust'] ?
878 DateTimeFormat::local($item['event-finish'], $dformat_short)
879 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
881 $end_time = $item['event-adjust'] ?
882 DateTimeFormat::local($item['event-finish'], $tformat)
883 : DateTimeFormat::utc($item['event-finish'], $tformat);
884 // Check if start and finish time is at the same day.
885 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
895 // Format the event location.
896 $location = self::locationToArray($item['event-location']);
898 // Construct the profile link (magic-auth).
899 $profile_link = Contact::magicLinkById($item['author-id']);
901 $tpl = get_markup_template('event_stream_item.tpl');
902 $return = replace_macros($tpl, [
903 '$id' => $item['event-id'],
904 '$title' => prepare_text($item['event-summary']),
905 '$dtstart_label' => L10n::t('Starts:'),
906 '$dtstart_title' => $dtstart_title,
907 '$dtstart_dt' => $dtstart_dt,
908 '$finish' => $finish,
909 '$dtend_label' => L10n::t('Finishes:'),
910 '$dtend_title' => $dtend_title,
911 '$dtend_dt' => $dtend_dt,
912 '$month_short' => $month_short,
913 '$date_short' => $date_short,
914 '$same_date' => $same_date,
915 '$start_time' => $start_time,
916 '$start_short' => $start_short,
917 '$end_time' => $end_time,
918 '$end_short' => $end_short,
919 '$author_name' => $item['author-name'],
920 '$author_link' => $profile_link,
921 '$author_avatar' => $item['author-avatar'],
922 '$description' => prepare_text($item['event-desc']),
923 '$location_label' => L10n::t('Location:'),
924 '$show_map_label' => L10n::t('Show map'),
925 '$hide_map_label' => L10n::t('Hide map'),
926 '$map_btn_label' => L10n::t('Show map'),
927 '$location' => $location
934 * @brief Format a string with map bbcode to an array with location data.
936 * Note: The string must only contain location data. A string with no bbcode will be
937 * handled as location name.
939 * @param string $s The string with the bbcode formatted location data.
941 * @return array The array with the location data.
942 * 'name' => The name of the location,<br>
943 * 'address' => The address of the location,<br>
944 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
946 private static function locationToArray($s = '') {
951 $location = ['name' => $s];
953 // Map tag with location name - e.g. [map]Paris[/map].
954 if (strpos($s, '[/map]') !== false) {
955 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
956 if (intval($found) > 0 && array_key_exists(1, $match)) {
957 $location['address'] = $match[1];
958 // Remove the map bbcode from the location name.
959 $location['name'] = str_replace($match[0], "", $s);
961 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
962 } elseif (strpos($s, '[map=') !== false) {
963 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
964 if (intval($found) > 0 && array_key_exists(1, $match)) {
965 $location['coordinates'] = $match[1];
966 // Remove the map bbcode from the location name.
967 $location['name'] = str_replace($match[0], "", $s);
971 $location['name'] = prepare_text($location['name']);
973 // Construct the map HTML.
974 if (isset($location['address'])) {
975 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
976 } elseif (isset($location['coordinates'])) {
977 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';