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;
20 use Friendica\Util\XML;
22 require_once 'boot.php';
23 require_once 'include/dba.php';
24 require_once 'include/items.php';
27 * @brief functions for interacting with the event database table
29 class Event extends BaseObject
32 public static function getHTML(array $event, $simple = false)
38 $bd_format = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8 AM.
40 $event_start = L10n::getDay(
41 !empty($event['adjust']) ?
42 DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
45 if (!empty($event['finish'])) {
46 $event_end = L10n::getDay(
47 !empty($event['adjust']) ?
48 DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
55 if (!empty($event['summary'])) {
56 $o = "<h3>" . BBCode::convert($event['summary'], false, $simple) . "</h3>";
59 if (!empty($event['desc'])) {
60 $o .= "<div>" . BBCode::convert($event['desc'], false, $simple) . "</div>";
63 $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
65 if (!$event['nofinish']) {
66 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end . "</p>";
69 if (!empty($event['location'])) {
70 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . BBCode::convert($event['location'], false, $simple) . "</p>";
76 $o = '<div class="vevent">' . "\r\n";
78 $o .= '<div class="summary event-summary">' . BBCode::convert($event['summary'], false, $simple) . '</div>' . "\r\n";
80 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
81 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
82 . '" >' . $event_start
83 . '</span></div>' . "\r\n";
85 if (!$event['nofinish']) {
86 $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
87 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
89 . '</span></div>' . "\r\n";
92 if (!empty($event['desc'])) {
93 $o .= '<div class="description event-description">' . BBCode::convert($event['desc'], false, $simple) . '</div>' . "\r\n";
96 if (!empty($event['location'])) {
97 $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span> <span class="location">'
98 . BBCode::convert($event['location'], false, $simple)
99 . '</span></div>' . "\r\n";
101 // Include a map of the location if the [map] BBCode is used.
102 if (strpos($event['location'], "[map") !== false) {
103 $map = Map::byLocation($event['location'], $simple);
104 if ($map !== $event['location']) {
110 $o .= '</div>' . "\r\n";
115 * @brief Convert an array with event data to bbcode.
117 * @param array $event Array which contains the event data.
118 * @return string The event as a bbcode formatted string.
120 private static function getBBCode(array $event)
124 if ($event['summary']) {
125 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
128 if ($event['desc']) {
129 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
132 if ($event['start']) {
133 $o .= '[event-start]' . $event['start'] . '[/event-start]';
136 if (($event['finish']) && (!$event['nofinish'])) {
137 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
140 if ($event['location']) {
141 $o .= '[event-location]' . $event['location'] . '[/event-location]';
144 if ($event['adjust']) {
145 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
152 * @brief Extract bbcode formatted event data from a string.
154 * @params: string $s The string which should be parsed for event data.
155 * @return array The array with the event information.
157 public static function fromBBCode($text)
162 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
163 $ev['summary'] = $match[1];
167 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
168 $ev['desc'] = $match[1];
172 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
173 $ev['start'] = $match[1];
177 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
178 $ev['finish'] = $match[1];
182 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
183 $ev['location'] = $match[1];
187 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
188 $ev['adjust'] = $match[1];
191 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
196 public static function sortByDate($event_list)
198 usort($event_list, ['self', 'compareDatesCallback']);
202 private static function compareDatesCallback($event_a, $event_b)
204 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
205 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
207 if ($date_a === $date_b) {
208 return strcasecmp($event_a['desc'], $event_b['desc']);
211 return strcmp($date_a, $date_b);
215 * @brief Delete an event from the event table.
217 * Note: This function does only delete the event from the event table not its
218 * related entry in the item table.
220 * @param int $event_id Event ID.
223 public static function delete($event_id)
225 if ($event_id == 0) {
229 DBA::delete('event', ['id' => $event_id]);
230 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
234 * @brief Store the event.
236 * Store the event in the event table and create an event item in the item table.
238 * @param array $arr Array with event data.
239 * @return int The new event id.
241 public static function store($arr)
246 $event['id'] = intval(defaults($arr, 'id' , 0));
247 $event['uid'] = intval(defaults($arr, 'uid' , 0));
248 $event['cid'] = intval(defaults($arr, 'cid' , 0));
249 $event['uri'] = defaults($arr, 'uri' , Item::newURI($event['uid']));
250 $event['type'] = defaults($arr, 'type' , 'event');
251 $event['summary'] = defaults($arr, 'summary' , '');
252 $event['desc'] = defaults($arr, 'desc' , '');
253 $event['location'] = defaults($arr, 'location' , '');
254 $event['allow_cid'] = defaults($arr, 'allow_cid', '');
255 $event['allow_gid'] = defaults($arr, 'allow_gid', '');
256 $event['deny_cid'] = defaults($arr, 'deny_cid' , '');
257 $event['deny_gid'] = defaults($arr, 'deny_gid' , '');
258 $event['adjust'] = intval(defaults($arr, 'adjust' , 0));
259 $event['nofinish'] = intval(defaults($arr, 'nofinish' , !empty($event['start']) && empty($event['finish'])));
261 $event['created'] = DateTimeFormat::utc(defaults($arr, 'created' , 'now'));
262 $event['edited'] = DateTimeFormat::utc(defaults($arr, 'edited' , 'now'));
263 $event['start'] = DateTimeFormat::utc(defaults($arr, 'start' , DBA::NULL_DATETIME));
264 $event['finish'] = DateTimeFormat::utc(defaults($arr, 'finish' , DBA::NULL_DATETIME));
265 if ($event['finish'] < DBA::NULL_DATETIME) {
266 $event['finish'] = DBA::NULL_DATETIME;
268 $private = intval(defaults($arr, 'private', 0));
270 $conditions = ['uid' => $event['uid']];
272 $conditions['id'] = $event['cid'];
274 $conditions['self'] = true;
277 $contact = DBA::selectFirst('contact', [], $conditions);
279 // Existing event being modified.
281 // has the event actually changed?
282 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
283 if (!DBA::isResult($existing_event) || ($existing_event['edited'] === $event['edited'])) {
285 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
287 return DBA::isResult($item) ? $item['id'] : 0;
291 'edited' => $event['edited'],
292 'start' => $event['start'],
293 'finish' => $event['finish'],
294 'summary' => $event['summary'],
295 'desc' => $event['desc'],
296 'location' => $event['location'],
297 'type' => $event['type'],
298 'adjust' => $event['adjust'],
299 'nofinish' => $event['nofinish'],
302 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
304 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
305 if (DBA::isResult($item)) {
306 $object = '<object><type>' . XML::escape(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
307 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
308 $object .= '</object>' . "\n";
310 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
311 Item::update($fields, ['id' => $item['id']]);
313 $item_id = $item['id'];
318 Addon::callHooks('event_updated', $event['id']);
320 $event['guid'] = defaults($arr, 'guid', System::createUUID());
322 // New event. Store it.
323 DBA::insert('event', $event);
325 $event['id'] = DBA::lastInsertId();
329 $item_arr['uid'] = $event['uid'];
330 $item_arr['contact-id'] = $event['cid'];
331 $item_arr['uri'] = $event['uri'];
332 $item_arr['parent-uri'] = $event['uri'];
333 $item_arr['guid'] = $event['guid'];
334 $item_arr['plink'] = defaults($arr, 'plink', '');
335 $item_arr['post-type'] = Item::PT_EVENT;
336 $item_arr['wall'] = $event['cid'] ? 0 : 1;
337 $item_arr['contact-id'] = $contact['id'];
338 $item_arr['owner-name'] = $contact['name'];
339 $item_arr['owner-link'] = $contact['url'];
340 $item_arr['owner-avatar'] = $contact['thumb'];
341 $item_arr['author-name'] = $contact['name'];
342 $item_arr['author-link'] = $contact['url'];
343 $item_arr['author-avatar'] = $contact['thumb'];
344 $item_arr['title'] = '';
345 $item_arr['allow_cid'] = $event['allow_cid'];
346 $item_arr['allow_gid'] = $event['allow_gid'];
347 $item_arr['deny_cid'] = $event['deny_cid'];
348 $item_arr['deny_gid'] = $event['deny_gid'];
349 $item_arr['private'] = $private;
350 $item_arr['visible'] = 1;
351 $item_arr['verb'] = ACTIVITY_POST;
352 $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
353 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
354 $item_arr['body'] = self::getBBCode($event);
355 $item_arr['event-id'] = $event['id'];
357 $item_arr['object'] = '<object><type>' . XML::escape(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
358 $item_arr['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
359 $item_arr['object'] .= '</object>' . "\n";
361 $item_id = Item::insert($item_arr);
363 Addon::callHooks("event_created", $event['id']);
370 * @brief Create an array with translation strings used for events.
372 * @return array Array with translations strings.
374 public static function getStrings()
376 // First day of the week (0 = Sunday).
377 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
380 "firstDay" => $firstDay,
381 "allday" => L10n::t("all-day"),
383 "Sun" => L10n::t("Sun"),
384 "Mon" => L10n::t("Mon"),
385 "Tue" => L10n::t("Tue"),
386 "Wed" => L10n::t("Wed"),
387 "Thu" => L10n::t("Thu"),
388 "Fri" => L10n::t("Fri"),
389 "Sat" => L10n::t("Sat"),
391 "Sunday" => L10n::t("Sunday"),
392 "Monday" => L10n::t("Monday"),
393 "Tuesday" => L10n::t("Tuesday"),
394 "Wednesday" => L10n::t("Wednesday"),
395 "Thursday" => L10n::t("Thursday"),
396 "Friday" => L10n::t("Friday"),
397 "Saturday" => L10n::t("Saturday"),
399 "Jan" => L10n::t("Jan"),
400 "Feb" => L10n::t("Feb"),
401 "Mar" => L10n::t("Mar"),
402 "Apr" => L10n::t("Apr"),
403 "May" => L10n::t("May"),
404 "Jun" => L10n::t("Jun"),
405 "Jul" => L10n::t("Jul"),
406 "Aug" => L10n::t("Aug"),
407 "Sep" => L10n::t("Sept"),
408 "Oct" => L10n::t("Oct"),
409 "Nov" => L10n::t("Nov"),
410 "Dec" => L10n::t("Dec"),
412 "January" => L10n::t("January"),
413 "February" => L10n::t("February"),
414 "March" => L10n::t("March"),
415 "April" => L10n::t("April"),
416 "May" => L10n::t("May"),
417 "June" => L10n::t("June"),
418 "July" => L10n::t("July"),
419 "August" => L10n::t("August"),
420 "September" => L10n::t("September"),
421 "October" => L10n::t("October"),
422 "November" => L10n::t("November"),
423 "December" => L10n::t("December"),
425 "today" => L10n::t("today"),
426 "month" => L10n::t("month"),
427 "week" => L10n::t("week"),
428 "day" => L10n::t("day"),
430 "noevent" => L10n::t("No events to display"),
432 "dtstart_label" => L10n::t("Starts:"),
433 "dtend_label" => L10n::t("Finishes:"),
434 "location_label" => L10n::t("Location:")
441 * @brief Removes duplicated birthday events.
443 * @param array $dates Array of possibly duplicated events.
444 * @return array Cleaned events.
446 * @todo We should replace this with a separate update function if there is some time left.
448 private static function removeDuplicates(array $dates)
452 foreach ($dates as $date) {
453 if ($date['type'] == 'birthday') {
454 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
459 return array_values($dates2);
463 * @brief Get an event by its event ID.
465 * @param int $owner_uid The User ID of the owner of the event
466 * @param int $event_id The ID of the event in the event table
467 * @param string $sql_extra
468 * @return array Query result
470 public static function getListById($owner_uid, $event_id, $sql_extra = '')
474 // Ownly allow events if there is a valid owner_id.
475 if ($owner_uid == 0) {
479 // Query for the event by event id
480 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
481 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
482 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
487 if (DBA::isResult($r)) {
488 $return = self::removeDuplicates($r);
495 * @brief Get all events in a specific time frame.
497 * @param int $owner_uid The User ID of the owner of the events.
498 * @param array $event_params An associative array with
500 * string 'start' => Start time of the timeframe.
501 * string 'finish' => Finish time of the timeframe.
502 * string 'adjust_start' =>
503 * string 'adjust_finish' =>
505 * @param string $sql_extra Additional sql conditions (e.g. permission request).
507 * @return array Query results.
509 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
513 // Only allow events if there is a valid owner_id.
514 if ($owner_uid == 0) {
518 // Query for the event by date.
519 // @todo Slow query (518 seconds to run), to be optimzed
520 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
521 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
522 WHERE `event`.`uid` = %d AND event.ignore = %d
523 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
524 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
527 intval($event_params["ignore"]),
528 DBA::escape($event_params["start"]),
529 DBA::escape($event_params["start"]),
530 DBA::escape($event_params["finish"]),
531 DBA::escape($event_params["adjust_start"]),
532 DBA::escape($event_params["adjust_start"]),
533 DBA::escape($event_params["adjust_finish"])
536 if (DBA::isResult($r)) {
537 $return = self::removeDuplicates($r);
544 * @brief Convert an array query results in an array which could be used by the events template.
546 * @param array $event_result Event query array.
547 * @return array Event array for the template.
549 public static function prepareListForTemplate(array $event_result)
554 $fmt = L10n::t('l, F j');
555 foreach ($event_result as $event) {
556 $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
557 if (!DBA::isResult($item)) {
558 // Using default values when no item had been found
559 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
562 $event = array_merge($event, $item);
564 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
565 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
566 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
567 $day = L10n::getDay($day);
569 if ($event['nofinish']) {
572 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
575 $is_first = ($day !== $last_date);
579 // Show edit and drop actions only if the user is the owner of the event and the event
580 // is a real event (no bithdays).
584 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
585 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event') , '', ''] : null;
586 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
587 $drop = [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event') , '', ''];
590 $title = strip_tags(html_entity_decode(BBCode::convert($event['summary']), ENT_QUOTES, 'UTF-8'));
592 list($title, $_trash) = explode("<br", BBCode::convert($event['desc']), 2);
593 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
596 $author_link = $event['author-link'];
597 $plink = $event['plink'];
599 $event['author-link'] = Contact::magicLink($author_link);
600 $event['plink'] = Contact::magicLink($author_link, $plink);
602 $html = self::getHTML($event);
603 $event['desc'] = BBCode::convert($event['desc']);
604 $event['location'] = BBCode::convert($event['location']);
606 'id' => $event['id'],
616 'is_first' => $is_first,
619 'plink' => [$event['plink'], L10n::t('link to source'), '', ''],
627 * @brief Format event to export format (ical/csv).
629 * @param array $events Query result for events.
630 * @param string $format The output format (ical/csv).
631 * @param string $timezone The timezone of the user (not implemented yet).
633 * @return string Content according to selected export format.
635 * @todo Implement timezone support
637 private static function formatListForExport(array $events, $format, $timezone)
639 if (!count($events)) {
644 // Format the exported data as a CSV file.
646 header("Content-type: text/csv");
647 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
649 foreach ($events as $event) {
650 /// @todo The time / date entries don't include any information about the
651 /// timezone the event is scheduled in :-/
652 $tmp1 = strtotime($event['start']);
653 $tmp2 = strtotime($event['finish']);
654 $time_format = "%H:%M:%S";
655 $date_format = "%Y-%m-%d";
657 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
658 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
659 '", "' . strftime($date_format, $tmp2) .
660 '", "' . strftime($time_format, $tmp2) .
661 '", "' . $event['location'] . '"' . PHP_EOL;
665 // Format the exported data as a ics file.
667 header("Content-type: text/ics");
668 $o = 'BEGIN:VCALENDAR' . PHP_EOL
669 . 'VERSION:2.0' . PHP_EOL
670 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
671 /// @todo include timezone informations in cases were the time is not in UTC
672 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
673 // . 'BEGIN:VTIMEZONE' . PHP_EOL
674 // . 'TZID:' . $timezone . PHP_EOL
675 // . 'END:VTIMEZONE' . PHP_EOL;
676 // TODO instead of PHP_EOL CRLF should be used for long entries
677 // but test your solution against http://icalvalid.cloudapp.net/
678 // also long lines SHOULD be split at 75 characters length
679 foreach ($events as $event) {
680 if ($event['adjust'] == 1) {
685 $o .= 'BEGIN:VEVENT' . PHP_EOL;
687 if ($event['start']) {
688 $tmp = strtotime($event['start']);
689 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
690 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
693 if (!$event['nofinish']) {
694 $tmp = strtotime($event['finish']);
695 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
696 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
699 if ($event['summary']) {
700 $tmp = $event['summary'];
701 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
702 $tmp = addcslashes($tmp, ',;');
703 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
706 if ($event['desc']) {
707 $tmp = $event['desc'];
708 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
709 $tmp = addcslashes($tmp, ',;');
710 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
713 if ($event['location']) {
714 $tmp = $event['location'];
715 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
716 $tmp = addcslashes($tmp, ',;');
717 $o .= 'LOCATION:' . $tmp . PHP_EOL;
720 $o .= 'END:VEVENT' . PHP_EOL;
724 $o .= 'END:VCALENDAR' . PHP_EOL;
732 * @brief Get all events for a user ID.
734 * The query for events is done permission sensitive.
735 * If the user is the owner of the calendar they
736 * will get all of their available events.
737 * If the user is only a visitor only the public events will
740 * @param int $uid The user ID.
742 * @return array Query results.
744 private static function getListByUserId($uid = 0)
752 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
754 $conditions = ['uid' => $uid, 'cid' => 0];
756 // Does the user who requests happen to be the owner of the events
757 // requested? then show all of your events, otherwise only those that
758 // don't have limitations set in allow_cid and allow_gid.
759 if (local_user() != $uid) {
760 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
763 $events = DBA::select('event', $fields, $conditions);
764 if (DBA::isResult($events)) {
765 $return = DBA::toArray($events);
773 * @param int $uid The user ID.
774 * @param string $format Output format (ical/csv).
775 * @return array With the results:
776 * bool 'success' => True if the processing was successful,<br>
777 * string 'format' => The output format,<br>
778 * string 'extension' => The file extension of the output format,<br>
779 * string 'content' => The formatted output content.<br>
781 * @todo Respect authenticated users with events_by_uid().
783 public static function exportListByUserId($uid, $format = 'ical')
787 $user = DBA::selectFirst('user', ['timezone'], ['uid' => $uid]);
788 if (DBA::isResult($user)) {
789 $timezone = $user['timezone'];
792 // Get all events which are owned by a uid (respects permissions).
793 $events = self::getListByUserId($uid);
795 // We have the events that are available for the requestor.
796 // Now format the output according to the requested format.
797 $res = self::formatListForExport($events, $format, $timezone);
799 // If there are results the precess was successfull.
804 // Get the file extension for the format.
819 'success' => $process,
821 'extension' => $file_ext,
829 * @brief Format an item array with event data to HTML.
831 * @param array $item Array with item and event data.
832 * @return string HTML output.
834 public static function getItemHTML(array $item) {
838 // Set the different time formats.
839 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
840 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
841 $tformat = L10n::t('g:i A'); // 8:01 AM.
843 // Convert the time to different formats.
844 $dtstart_dt = L10n::getDay(
845 $item['event-adjust'] ?
846 DateTimeFormat::local($item['event-start'], $dformat)
847 : DateTimeFormat::utc($item['event-start'], $dformat)
849 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
850 // Format: Jan till Dec.
851 $month_short = L10n::getDayShort(
852 $item['event-adjust'] ?
853 DateTimeFormat::local($item['event-start'], 'M')
854 : DateTimeFormat::utc($item['event-start'], 'M')
856 // Format: 1 till 31.
857 $date_short = $item['event-adjust'] ?
858 DateTimeFormat::local($item['event-start'], 'j')
859 : DateTimeFormat::utc($item['event-start'], 'j');
860 $start_time = $item['event-adjust'] ?
861 DateTimeFormat::local($item['event-start'], $tformat)
862 : DateTimeFormat::utc($item['event-start'], $tformat);
863 $start_short = L10n::getDayShort(
864 $item['event-adjust'] ?
865 DateTimeFormat::local($item['event-start'], $dformat_short)
866 : DateTimeFormat::utc($item['event-start'], $dformat_short)
869 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
870 if (!$item['event-nofinish']) {
872 $dtend_dt = L10n::getDay(
873 $item['event-adjust'] ?
874 DateTimeFormat::local($item['event-finish'], $dformat)
875 : DateTimeFormat::utc($item['event-finish'], $dformat)
877 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
878 $end_short = L10n::getDayShort(
879 $item['event-adjust'] ?
880 DateTimeFormat::local($item['event-finish'], $dformat_short)
881 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
883 $end_time = $item['event-adjust'] ?
884 DateTimeFormat::local($item['event-finish'], $tformat)
885 : DateTimeFormat::utc($item['event-finish'], $tformat);
886 // Check if start and finish time is at the same day.
887 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
897 // Format the event location.
898 $location = self::locationToArray($item['event-location']);
900 // Construct the profile link (magic-auth).
901 $profile_link = Contact::magicLinkById($item['author-id']);
903 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
904 $return = Renderer::replaceMacros($tpl, [
905 '$id' => $item['event-id'],
906 '$title' => prepare_text($item['event-summary']),
907 '$dtstart_label' => L10n::t('Starts:'),
908 '$dtstart_title' => $dtstart_title,
909 '$dtstart_dt' => $dtstart_dt,
910 '$finish' => $finish,
911 '$dtend_label' => L10n::t('Finishes:'),
912 '$dtend_title' => $dtend_title,
913 '$dtend_dt' => $dtend_dt,
914 '$month_short' => $month_short,
915 '$date_short' => $date_short,
916 '$same_date' => $same_date,
917 '$start_time' => $start_time,
918 '$start_short' => $start_short,
919 '$end_time' => $end_time,
920 '$end_short' => $end_short,
921 '$author_name' => $item['author-name'],
922 '$author_link' => $profile_link,
923 '$author_avatar' => $item['author-avatar'],
924 '$description' => prepare_text($item['event-desc']),
925 '$location_label' => L10n::t('Location:'),
926 '$show_map_label' => L10n::t('Show map'),
927 '$hide_map_label' => L10n::t('Hide map'),
928 '$map_btn_label' => L10n::t('Show map'),
929 '$location' => $location
936 * @brief Format a string with map bbcode to an array with location data.
938 * Note: The string must only contain location data. A string with no bbcode will be
939 * handled as location name.
941 * @param string $s The string with the bbcode formatted location data.
943 * @return array The array with the location data.
944 * 'name' => The name of the location,<br>
945 * 'address' => The address of the location,<br>
946 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
948 private static function locationToArray($s = '') {
953 $location = ['name' => $s];
955 // Map tag with location name - e.g. [map]Paris[/map].
956 if (strpos($s, '[/map]') !== false) {
957 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
958 if (intval($found) > 0 && array_key_exists(1, $match)) {
959 $location['address'] = $match[1];
960 // Remove the map bbcode from the location name.
961 $location['name'] = str_replace($match[0], "", $s);
963 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
964 } elseif (strpos($s, '[map=') !== false) {
965 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
966 if (intval($found) > 0 && array_key_exists(1, $match)) {
967 $location['coordinates'] = $match[1];
968 // Remove the map bbcode from the location name.
969 $location['name'] = str_replace($match[0], "", $s);
973 $location['name'] = prepare_text($location['name']);
975 // Construct the map HTML.
976 if (isset($location['address'])) {
977 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
978 } elseif (isset($location['coordinates'])) {
979 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';