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\Renderer;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Map;
21 require_once 'boot.php';
22 require_once 'include/dba.php';
23 require_once 'include/items.php';
26 * @brief functions for interacting with the event database table
28 class Event extends BaseObject
31 public static function getHTML(array $event, $simple = false)
37 $bd_format = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8 AM.
39 $event_start = day_translate(
40 !empty($event['adjust']) ?
41 DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
44 if (!empty($event['finish'])) {
45 $event_end = day_translate(
46 !empty($event['adjust']) ?
47 DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
54 if (!empty($event['summary'])) {
55 $o = "<h3>" . BBCode::convert($event['summary'], false, $simple) . "</h3>";
58 if (!empty($event['desc'])) {
59 $o .= "<div>" . BBCode::convert($event['desc'], false, $simple) . "</div>";
62 $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
64 if (!$event['nofinish']) {
65 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end . "</p>";
68 if (!empty($event['location'])) {
69 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . BBCode::convert($event['location'], false, $simple) . "</p>";
75 $o = '<div class="vevent">' . "\r\n";
77 $o .= '<div class="summary event-summary">' . BBCode::convert($event['summary'], false, $simple) . '</div>' . "\r\n";
79 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
80 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
81 . '" >' . $event_start
82 . '</span></div>' . "\r\n";
84 if (!$event['nofinish']) {
85 $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
86 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
88 . '</span></div>' . "\r\n";
91 if (!empty($event['desc'])) {
92 $o .= '<div class="description event-description">' . BBCode::convert($event['desc'], false, $simple) . '</div>' . "\r\n";
95 if (!empty($event['location'])) {
96 $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span> <span class="location">'
97 . BBCode::convert($event['location'], false, $simple)
98 . '</span></div>' . "\r\n";
100 // Include a map of the location if the [map] BBCode is used.
101 if (strpos($event['location'], "[map") !== false) {
102 $map = Map::byLocation($event['location'], $simple);
103 if ($map !== $event['location']) {
109 $o .= '</div>' . "\r\n";
114 * @brief Convert an array with event data to bbcode.
116 * @param array $event Array which contains the event data.
117 * @return string The event as a bbcode formatted string.
119 private static function getBBCode(array $event)
123 if ($event['summary']) {
124 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
127 if ($event['desc']) {
128 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
131 if ($event['start']) {
132 $o .= '[event-start]' . $event['start'] . '[/event-start]';
135 if (($event['finish']) && (!$event['nofinish'])) {
136 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
139 if ($event['location']) {
140 $o .= '[event-location]' . $event['location'] . '[/event-location]';
143 if ($event['adjust']) {
144 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
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 public static function fromBBCode($text)
161 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
162 $ev['summary'] = $match[1];
166 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
167 $ev['desc'] = $match[1];
171 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
172 $ev['start'] = $match[1];
176 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
177 $ev['finish'] = $match[1];
181 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
182 $ev['location'] = $match[1];
186 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
187 $ev['adjust'] = $match[1];
190 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
195 public static function sortByDate($event_list)
197 usort($event_list, ['self', 'compareDatesCallback']);
201 private static function compareDatesCallback($event_a, $event_b)
203 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
204 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
206 if ($date_a === $date_b) {
207 return strcasecmp($event_a['desc'], $event_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 public static function delete($event_id)
224 if ($event_id == 0) {
228 DBA::delete('event', ['id' => $event_id]);
229 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
233 * @brief Store the event.
235 * Store the event in the event table and create an event item in the item table.
237 * @param array $arr Array with event data.
238 * @return int The new event id.
240 public static function store($arr)
245 $event['id'] = intval(defaults($arr, 'id' , 0));
246 $event['uid'] = intval(defaults($arr, 'uid' , 0));
247 $event['cid'] = intval(defaults($arr, 'cid' , 0));
248 $event['uri'] = defaults($arr, 'uri' , Item::newURI($event['uid']));
249 $event['type'] = defaults($arr, 'type' , 'event');
250 $event['summary'] = defaults($arr, 'summary' , '');
251 $event['desc'] = defaults($arr, 'desc' , '');
252 $event['location'] = defaults($arr, 'location' , '');
253 $event['allow_cid'] = defaults($arr, 'allow_cid', '');
254 $event['allow_gid'] = defaults($arr, 'allow_gid', '');
255 $event['deny_cid'] = defaults($arr, 'deny_cid' , '');
256 $event['deny_gid'] = defaults($arr, 'deny_gid' , '');
257 $event['adjust'] = intval(defaults($arr, 'adjust' , 0));
258 $event['nofinish'] = intval(defaults($arr, 'nofinish' , !empty($event['start']) && empty($event['finish'])));
260 $event['created'] = DateTimeFormat::utc(defaults($arr, 'created' , 'now'));
261 $event['edited'] = DateTimeFormat::utc(defaults($arr, 'edited' , 'now'));
262 $event['start'] = DateTimeFormat::utc(defaults($arr, 'start' , DBA::NULL_DATETIME));
263 $event['finish'] = DateTimeFormat::utc(defaults($arr, 'finish' , DBA::NULL_DATETIME));
264 if ($event['finish'] < DBA::NULL_DATETIME) {
265 $event['finish'] = DBA::NULL_DATETIME;
267 $private = intval(defaults($arr, 'private', 0));
269 $conditions = ['uid' => $event['uid']];
271 $conditions['id'] = $event['cid'];
273 $conditions['self'] = true;
276 $contact = DBA::selectFirst('contact', [], $conditions);
278 // Existing event being modified.
280 // has the event actually changed?
281 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
282 if (!DBA::isResult($existing_event) || ($existing_event['edited'] === $event['edited'])) {
284 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
286 return DBA::isResult($item) ? $item['id'] : 0;
290 'edited' => $event['edited'],
291 'start' => $event['start'],
292 'finish' => $event['finish'],
293 'summary' => $event['summary'],
294 'desc' => $event['desc'],
295 'location' => $event['location'],
296 'type' => $event['type'],
297 'adjust' => $event['adjust'],
298 'nofinish' => $event['nofinish'],
301 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
303 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
304 if (DBA::isResult($item)) {
305 $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($event['uri']) . '</id>';
306 $object .= '<content>' . xmlify(self::getBBCode($event)) . '</content>';
307 $object .= '</object>' . "\n";
309 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
310 Item::update($fields, ['id' => $item['id']]);
312 $item_id = $item['id'];
317 Addon::callHooks('event_updated', $event['id']);
319 $event['guid'] = defaults($arr, 'guid', System::createUUID());
321 // New event. Store it.
322 DBA::insert('event', $event);
324 $event['id'] = DBA::lastInsertId();
328 $item_arr['uid'] = $event['uid'];
329 $item_arr['contact-id'] = $event['cid'];
330 $item_arr['uri'] = $event['uri'];
331 $item_arr['parent-uri'] = $event['uri'];
332 $item_arr['guid'] = $event['guid'];
333 $item_arr['plink'] = defaults($arr, 'plink', '');
334 $item_arr['post-type'] = Item::PT_EVENT;
335 $item_arr['wall'] = $event['cid'] ? 0 : 1;
336 $item_arr['contact-id'] = $contact['id'];
337 $item_arr['owner-name'] = $contact['name'];
338 $item_arr['owner-link'] = $contact['url'];
339 $item_arr['owner-avatar'] = $contact['thumb'];
340 $item_arr['author-name'] = $contact['name'];
341 $item_arr['author-link'] = $contact['url'];
342 $item_arr['author-avatar'] = $contact['thumb'];
343 $item_arr['title'] = '';
344 $item_arr['allow_cid'] = $event['allow_cid'];
345 $item_arr['allow_gid'] = $event['allow_gid'];
346 $item_arr['deny_cid'] = $event['deny_cid'];
347 $item_arr['deny_gid'] = $event['deny_gid'];
348 $item_arr['private'] = $private;
349 $item_arr['visible'] = 1;
350 $item_arr['verb'] = ACTIVITY_POST;
351 $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
352 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
353 $item_arr['body'] = self::getBBCode($event);
354 $item_arr['event-id'] = $event['id'];
356 $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($event['uri']) . '</id>';
357 $item_arr['object'] .= '<content>' . xmlify(self::getBBCode($event)) . '</content>';
358 $item_arr['object'] .= '</object>' . "\n";
360 $item_id = Item::insert($item_arr);
362 Addon::callHooks("event_created", $event['id']);
369 * @brief Create an array with translation strings used for events.
371 * @return array Array with translations strings.
373 public static function getStrings()
375 // First day of the week (0 = Sunday).
376 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
379 "firstDay" => $firstDay,
380 "allday" => L10n::t("all-day"),
382 "Sun" => L10n::t("Sun"),
383 "Mon" => L10n::t("Mon"),
384 "Tue" => L10n::t("Tue"),
385 "Wed" => L10n::t("Wed"),
386 "Thu" => L10n::t("Thu"),
387 "Fri" => L10n::t("Fri"),
388 "Sat" => L10n::t("Sat"),
390 "Sunday" => L10n::t("Sunday"),
391 "Monday" => L10n::t("Monday"),
392 "Tuesday" => L10n::t("Tuesday"),
393 "Wednesday" => L10n::t("Wednesday"),
394 "Thursday" => L10n::t("Thursday"),
395 "Friday" => L10n::t("Friday"),
396 "Saturday" => L10n::t("Saturday"),
398 "Jan" => L10n::t("Jan"),
399 "Feb" => L10n::t("Feb"),
400 "Mar" => L10n::t("Mar"),
401 "Apr" => L10n::t("Apr"),
402 "May" => L10n::t("May"),
403 "Jun" => L10n::t("Jun"),
404 "Jul" => L10n::t("Jul"),
405 "Aug" => L10n::t("Aug"),
406 "Sep" => L10n::t("Sept"),
407 "Oct" => L10n::t("Oct"),
408 "Nov" => L10n::t("Nov"),
409 "Dec" => L10n::t("Dec"),
411 "January" => L10n::t("January"),
412 "February" => L10n::t("February"),
413 "March" => L10n::t("March"),
414 "April" => L10n::t("April"),
415 "May" => L10n::t("May"),
416 "June" => L10n::t("June"),
417 "July" => L10n::t("July"),
418 "August" => L10n::t("August"),
419 "September" => L10n::t("September"),
420 "October" => L10n::t("October"),
421 "November" => L10n::t("November"),
422 "December" => L10n::t("December"),
424 "today" => L10n::t("today"),
425 "month" => L10n::t("month"),
426 "week" => L10n::t("week"),
427 "day" => L10n::t("day"),
429 "noevent" => L10n::t("No events to display"),
431 "dtstart_label" => L10n::t("Starts:"),
432 "dtend_label" => L10n::t("Finishes:"),
433 "location_label" => L10n::t("Location:")
440 * @brief Removes duplicated birthday events.
442 * @param array $dates Array of possibly duplicated events.
443 * @return array Cleaned events.
445 * @todo We should replace this with a separate update function if there is some time left.
447 private static function removeDuplicates(array $dates)
451 foreach ($dates as $date) {
452 if ($date['type'] == 'birthday') {
453 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
458 return array_values($dates2);
462 * @brief Get an event by its event ID.
464 * @param int $owner_uid The User ID of the owner of the event
465 * @param int $event_id The ID of the event in the event table
466 * @param string $sql_extra
467 * @return array Query result
469 public static function getListById($owner_uid, $event_id, $sql_extra = '')
473 // Ownly allow events if there is a valid owner_id.
474 if ($owner_uid == 0) {
478 // Query for the event by event id
479 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
480 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
481 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
486 if (DBA::isResult($r)) {
487 $return = self::removeDuplicates($r);
494 * @brief Get all events in a specific time frame.
496 * @param int $owner_uid The User ID of the owner of the events.
497 * @param array $event_params An associative array with
499 * string 'start' => Start time of the timeframe.
500 * string 'finish' => Finish time of the timeframe.
501 * string 'adjust_start' =>
502 * string 'adjust_finish' =>
504 * @param string $sql_extra Additional sql conditions (e.g. permission request).
506 * @return array Query results.
508 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
512 // Only allow events if there is a valid owner_id.
513 if ($owner_uid == 0) {
517 // Query for the event by date.
518 // @todo Slow query (518 seconds to run), to be optimzed
519 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
520 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
521 WHERE `event`.`uid` = %d AND event.ignore = %d
522 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
523 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
526 intval($event_params["ignore"]),
527 DBA::escape($event_params["start"]),
528 DBA::escape($event_params["start"]),
529 DBA::escape($event_params["finish"]),
530 DBA::escape($event_params["adjust_start"]),
531 DBA::escape($event_params["adjust_start"]),
532 DBA::escape($event_params["adjust_finish"])
535 if (DBA::isResult($r)) {
536 $return = self::removeDuplicates($r);
543 * @brief Convert an array query results in an array which could be used by the events template.
545 * @param array $event_result Event query array.
546 * @return array Event array for the template.
548 public static function prepareListForTemplate(array $event_result)
553 $fmt = L10n::t('l, F j');
554 foreach ($event_result as $event) {
555 $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
556 if (!DBA::isResult($item)) {
557 // Using default values when no item had been found
558 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
561 $event = array_merge($event, $item);
563 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
564 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
565 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
566 $day = day_translate($day);
568 if ($event['nofinish']) {
571 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
574 $is_first = ($day !== $last_date);
578 // Show edit and drop actions only if the user is the owner of the event and the event
579 // is a real event (no bithdays).
583 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
584 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event') , '', ''] : null;
585 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
586 $drop = [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event') , '', ''];
589 $title = strip_tags(html_entity_decode(BBCode::convert($event['summary']), ENT_QUOTES, 'UTF-8'));
591 list($title, $_trash) = explode("<br", BBCode::convert($event['desc']), 2);
592 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
595 $author_link = $event['author-link'];
596 $plink = $event['plink'];
598 $event['author-link'] = Contact::magicLink($author_link);
599 $event['plink'] = Contact::magicLink($author_link, $plink);
601 $html = self::getHTML($event);
602 $event['desc'] = BBCode::convert($event['desc']);
603 $event['location'] = BBCode::convert($event['location']);
605 'id' => $event['id'],
615 'is_first' => $is_first,
618 'plink' => [$event['plink'], L10n::t('link to source'), '', ''],
626 * @brief Format event to export format (ical/csv).
628 * @param array $events Query result for events.
629 * @param string $format The output format (ical/csv).
630 * @param string $timezone The timezone of the user (not implemented yet).
632 * @return string Content according to selected export format.
634 * @todo Implement timezone support
636 private static function formatListForExport(array $events, $format, $timezone)
638 if (!count($events)) {
643 // Format the exported data as a CSV file.
645 header("Content-type: text/csv");
646 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
648 foreach ($events as $event) {
649 /// @todo The time / date entries don't include any information about the
650 /// timezone the event is scheduled in :-/
651 $tmp1 = strtotime($event['start']);
652 $tmp2 = strtotime($event['finish']);
653 $time_format = "%H:%M:%S";
654 $date_format = "%Y-%m-%d";
656 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
657 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
658 '", "' . strftime($date_format, $tmp2) .
659 '", "' . strftime($time_format, $tmp2) .
660 '", "' . $event['location'] . '"' . PHP_EOL;
664 // Format the exported data as a ics file.
666 header("Content-type: text/ics");
667 $o = 'BEGIN:VCALENDAR' . PHP_EOL
668 . 'VERSION:2.0' . PHP_EOL
669 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
670 /// @todo include timezone informations in cases were the time is not in UTC
671 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
672 // . 'BEGIN:VTIMEZONE' . PHP_EOL
673 // . 'TZID:' . $timezone . PHP_EOL
674 // . 'END:VTIMEZONE' . PHP_EOL;
675 // TODO instead of PHP_EOL CRLF should be used for long entries
676 // but test your solution against http://icalvalid.cloudapp.net/
677 // also long lines SHOULD be split at 75 characters length
678 foreach ($events as $event) {
679 if ($event['adjust'] == 1) {
684 $o .= 'BEGIN:VEVENT' . PHP_EOL;
686 if ($event['start']) {
687 $tmp = strtotime($event['start']);
688 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
689 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
692 if (!$event['nofinish']) {
693 $tmp = strtotime($event['finish']);
694 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
695 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
698 if ($event['summary']) {
699 $tmp = $event['summary'];
700 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
701 $tmp = addcslashes($tmp, ',;');
702 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
705 if ($event['desc']) {
706 $tmp = $event['desc'];
707 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
708 $tmp = addcslashes($tmp, ',;');
709 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
712 if ($event['location']) {
713 $tmp = $event['location'];
714 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
715 $tmp = addcslashes($tmp, ',;');
716 $o .= 'LOCATION:' . $tmp . PHP_EOL;
719 $o .= 'END:VEVENT' . PHP_EOL;
723 $o .= 'END:VCALENDAR' . PHP_EOL;
731 * @brief Get all events for a user ID.
733 * The query for events is done permission sensitive.
734 * If the user is the owner of the calendar they
735 * will get all of their available events.
736 * If the user is only a visitor only the public events will
739 * @param int $uid The user ID.
741 * @return array Query results.
743 private static function getListByUserId($uid = 0)
751 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
753 $conditions = ['uid' => $uid, 'cid' => 0];
755 // Does the user who requests happen to be the owner of the events
756 // requested? then show all of your events, otherwise only those that
757 // don't have limitations set in allow_cid and allow_gid.
758 if (local_user() != $uid) {
759 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
762 $events = DBA::select('event', $fields, $conditions);
763 if (DBA::isResult($events)) {
764 $return = DBA::toArray($events);
772 * @param int $uid The user ID.
773 * @param string $format Output format (ical/csv).
774 * @return array With the results:
775 * bool 'success' => True if the processing was successful,<br>
776 * string 'format' => The output format,<br>
777 * string 'extension' => The file extension of the output format,<br>
778 * string 'content' => The formatted output content.<br>
780 * @todo Respect authenticated users with events_by_uid().
782 public static function exportListByUserId($uid, $format = 'ical')
786 $user = DBA::selectFirst('user', ['timezone'], ['uid' => $uid]);
787 if (DBA::isResult($user)) {
788 $timezone = $user['timezone'];
791 // Get all events which are owned by a uid (respects permissions).
792 $events = self::getListByUserId($uid);
794 // We have the events that are available for the requestor.
795 // Now format the output according to the requested format.
796 $res = self::formatListForExport($events, $format, $timezone);
798 // If there are results the precess was successfull.
803 // Get the file extension for the format.
818 'success' => $process,
820 'extension' => $file_ext,
828 * @brief Format an item array with event data to HTML.
830 * @param array $item Array with item and event data.
831 * @return string HTML output.
833 public static function getItemHTML(array $item) {
837 // Set the different time formats.
838 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
839 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
840 $tformat = L10n::t('g:i A'); // 8:01 AM.
842 // Convert the time to different formats.
843 $dtstart_dt = day_translate(
844 $item['event-adjust'] ?
845 DateTimeFormat::local($item['event-start'], $dformat)
846 : DateTimeFormat::utc($item['event-start'], $dformat)
848 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
849 // Format: Jan till Dec.
850 $month_short = day_short_translate(
851 $item['event-adjust'] ?
852 DateTimeFormat::local($item['event-start'], 'M')
853 : DateTimeFormat::utc($item['event-start'], 'M')
855 // Format: 1 till 31.
856 $date_short = $item['event-adjust'] ?
857 DateTimeFormat::local($item['event-start'], 'j')
858 : DateTimeFormat::utc($item['event-start'], 'j');
859 $start_time = $item['event-adjust'] ?
860 DateTimeFormat::local($item['event-start'], $tformat)
861 : DateTimeFormat::utc($item['event-start'], $tformat);
862 $start_short = day_short_translate(
863 $item['event-adjust'] ?
864 DateTimeFormat::local($item['event-start'], $dformat_short)
865 : DateTimeFormat::utc($item['event-start'], $dformat_short)
868 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
869 if (!$item['event-nofinish']) {
871 $dtend_dt = day_translate(
872 $item['event-adjust'] ?
873 DateTimeFormat::local($item['event-finish'], $dformat)
874 : DateTimeFormat::utc($item['event-finish'], $dformat)
876 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
877 $end_short = day_short_translate(
878 $item['event-adjust'] ?
879 DateTimeFormat::local($item['event-finish'], $dformat_short)
880 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
882 $end_time = $item['event-adjust'] ?
883 DateTimeFormat::local($item['event-finish'], $tformat)
884 : DateTimeFormat::utc($item['event-finish'], $tformat);
885 // Check if start and finish time is at the same day.
886 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
896 // Format the event location.
897 $location = self::locationToArray($item['event-location']);
899 // Construct the profile link (magic-auth).
900 $profile_link = Contact::magicLinkById($item['author-id']);
902 $tpl = get_markup_template('event_stream_item.tpl');
903 $return = Renderer::replaceMacros($tpl, [
904 '$id' => $item['event-id'],
905 '$title' => prepare_text($item['event-summary']),
906 '$dtstart_label' => L10n::t('Starts:'),
907 '$dtstart_title' => $dtstart_title,
908 '$dtstart_dt' => $dtstart_dt,
909 '$finish' => $finish,
910 '$dtend_label' => L10n::t('Finishes:'),
911 '$dtend_title' => $dtend_title,
912 '$dtend_dt' => $dtend_dt,
913 '$month_short' => $month_short,
914 '$date_short' => $date_short,
915 '$same_date' => $same_date,
916 '$start_time' => $start_time,
917 '$start_short' => $start_short,
918 '$end_time' => $end_time,
919 '$end_short' => $end_short,
920 '$author_name' => $item['author-name'],
921 '$author_link' => $profile_link,
922 '$author_avatar' => $item['author-avatar'],
923 '$description' => prepare_text($item['event-desc']),
924 '$location_label' => L10n::t('Location:'),
925 '$show_map_label' => L10n::t('Show map'),
926 '$hide_map_label' => L10n::t('Hide map'),
927 '$map_btn_label' => L10n::t('Show map'),
928 '$location' => $location
935 * @brief Format a string with map bbcode to an array with location data.
937 * Note: The string must only contain location data. A string with no bbcode will be
938 * handled as location name.
940 * @param string $s The string with the bbcode formatted location data.
942 * @return array The array with the location data.
943 * 'name' => The name of the location,<br>
944 * 'address' => The address of the location,<br>
945 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
947 private static function locationToArray($s = '') {
952 $location = ['name' => $s];
954 // Map tag with location name - e.g. [map]Paris[/map].
955 if (strpos($s, '[/map]') !== false) {
956 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
957 if (intval($found) > 0 && array_key_exists(1, $match)) {
958 $location['address'] = $match[1];
959 // Remove the map bbcode from the location name.
960 $location['name'] = str_replace($match[0], "", $s);
962 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
963 } elseif (strpos($s, '[map=') !== false) {
964 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
965 if (intval($found) > 0 && array_key_exists(1, $match)) {
966 $location['coordinates'] = $match[1];
967 // Remove the map bbcode from the location name.
968 $location['name'] = str_replace($match[0], "", $s);
972 $location['name'] = prepare_text($location['name']);
974 // Construct the map HTML.
975 if (isset($location['address'])) {
976 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
977 } elseif (isset($location['coordinates'])) {
978 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';