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);
327 // Don't create an item for birthday events
328 if ($event['type'] == 'event') {
329 $event['id'] = DBA::lastInsertId();
333 $item_arr['uid'] = $event['uid'];
334 $item_arr['contact-id'] = $event['cid'];
335 $item_arr['uri'] = $event['uri'];
336 $item_arr['parent-uri'] = $event['uri'];
337 $item_arr['guid'] = $event['guid'];
338 $item_arr['plink'] = defaults($arr, 'plink', '');
339 $item_arr['post-type'] = Item::PT_EVENT;
340 $item_arr['wall'] = $event['cid'] ? 0 : 1;
341 $item_arr['contact-id'] = $contact['id'];
342 $item_arr['owner-name'] = $contact['name'];
343 $item_arr['owner-link'] = $contact['url'];
344 $item_arr['owner-avatar'] = $contact['thumb'];
345 $item_arr['author-name'] = $contact['name'];
346 $item_arr['author-link'] = $contact['url'];
347 $item_arr['author-avatar'] = $contact['thumb'];
348 $item_arr['title'] = '';
349 $item_arr['allow_cid'] = $event['allow_cid'];
350 $item_arr['allow_gid'] = $event['allow_gid'];
351 $item_arr['deny_cid'] = $event['deny_cid'];
352 $item_arr['deny_gid'] = $event['deny_gid'];
353 $item_arr['private'] = $private;
354 $item_arr['visible'] = 1;
355 $item_arr['verb'] = ACTIVITY_POST;
356 $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
357 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
358 $item_arr['body'] = self::getBBCode($event);
359 $item_arr['event-id'] = $event['id'];
361 $item_arr['object'] = '<object><type>' . XML::escape(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
362 $item_arr['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
363 $item_arr['object'] .= '</object>' . "\n";
365 $item_id = Item::insert($item_arr);
368 Addon::callHooks("event_created", $event['id']);
375 * @brief Create an array with translation strings used for events.
377 * @return array Array with translations strings.
379 public static function getStrings()
381 // First day of the week (0 = Sunday).
382 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
385 "firstDay" => $firstDay,
386 "allday" => L10n::t("all-day"),
388 "Sun" => L10n::t("Sun"),
389 "Mon" => L10n::t("Mon"),
390 "Tue" => L10n::t("Tue"),
391 "Wed" => L10n::t("Wed"),
392 "Thu" => L10n::t("Thu"),
393 "Fri" => L10n::t("Fri"),
394 "Sat" => L10n::t("Sat"),
396 "Sunday" => L10n::t("Sunday"),
397 "Monday" => L10n::t("Monday"),
398 "Tuesday" => L10n::t("Tuesday"),
399 "Wednesday" => L10n::t("Wednesday"),
400 "Thursday" => L10n::t("Thursday"),
401 "Friday" => L10n::t("Friday"),
402 "Saturday" => L10n::t("Saturday"),
404 "Jan" => L10n::t("Jan"),
405 "Feb" => L10n::t("Feb"),
406 "Mar" => L10n::t("Mar"),
407 "Apr" => L10n::t("Apr"),
408 "May" => L10n::t("May"),
409 "Jun" => L10n::t("Jun"),
410 "Jul" => L10n::t("Jul"),
411 "Aug" => L10n::t("Aug"),
412 "Sep" => L10n::t("Sept"),
413 "Oct" => L10n::t("Oct"),
414 "Nov" => L10n::t("Nov"),
415 "Dec" => L10n::t("Dec"),
417 "January" => L10n::t("January"),
418 "February" => L10n::t("February"),
419 "March" => L10n::t("March"),
420 "April" => L10n::t("April"),
421 "May" => L10n::t("May"),
422 "June" => L10n::t("June"),
423 "July" => L10n::t("July"),
424 "August" => L10n::t("August"),
425 "September" => L10n::t("September"),
426 "October" => L10n::t("October"),
427 "November" => L10n::t("November"),
428 "December" => L10n::t("December"),
430 "today" => L10n::t("today"),
431 "month" => L10n::t("month"),
432 "week" => L10n::t("week"),
433 "day" => L10n::t("day"),
435 "noevent" => L10n::t("No events to display"),
437 "dtstart_label" => L10n::t("Starts:"),
438 "dtend_label" => L10n::t("Finishes:"),
439 "location_label" => L10n::t("Location:")
446 * @brief Removes duplicated birthday events.
448 * @param array $dates Array of possibly duplicated events.
449 * @return array Cleaned events.
451 * @todo We should replace this with a separate update function if there is some time left.
453 private static function removeDuplicates(array $dates)
457 foreach ($dates as $date) {
458 if ($date['type'] == 'birthday') {
459 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
464 return array_values($dates2);
468 * @brief Get an event by its event ID.
470 * @param int $owner_uid The User ID of the owner of the event
471 * @param int $event_id The ID of the event in the event table
472 * @param string $sql_extra
473 * @return array Query result
475 public static function getListById($owner_uid, $event_id, $sql_extra = '')
479 // Ownly allow events if there is a valid owner_id.
480 if ($owner_uid == 0) {
484 // Query for the event by event id
485 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
486 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
487 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
492 if (DBA::isResult($r)) {
493 $return = self::removeDuplicates($r);
500 * @brief Get all events in a specific time frame.
502 * @param int $owner_uid The User ID of the owner of the events.
503 * @param array $event_params An associative array with
505 * string 'start' => Start time of the timeframe.
506 * string 'finish' => Finish time of the timeframe.
507 * string 'adjust_start' =>
508 * string 'adjust_finish' =>
510 * @param string $sql_extra Additional sql conditions (e.g. permission request).
512 * @return array Query results.
514 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
518 // Only allow events if there is a valid owner_id.
519 if ($owner_uid == 0) {
523 // Query for the event by date.
524 // @todo Slow query (518 seconds to run), to be optimzed
525 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
526 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
527 WHERE `event`.`uid` = %d AND event.ignore = %d
528 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
529 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
532 intval($event_params["ignore"]),
533 DBA::escape($event_params["start"]),
534 DBA::escape($event_params["start"]),
535 DBA::escape($event_params["finish"]),
536 DBA::escape($event_params["adjust_start"]),
537 DBA::escape($event_params["adjust_start"]),
538 DBA::escape($event_params["adjust_finish"])
541 if (DBA::isResult($r)) {
542 $return = self::removeDuplicates($r);
549 * @brief Convert an array query results in an array which could be used by the events template.
551 * @param array $event_result Event query array.
552 * @return array Event array for the template.
554 public static function prepareListForTemplate(array $event_result)
559 $fmt = L10n::t('l, F j');
560 foreach ($event_result as $event) {
561 $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
562 if (!DBA::isResult($item)) {
563 // Using default values when no item had been found
564 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
567 $event = array_merge($event, $item);
569 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
570 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
571 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
572 $day = L10n::getDay($day);
574 if ($event['nofinish']) {
577 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
580 $is_first = ($day !== $last_date);
584 // Show edit and drop actions only if the user is the owner of the event and the event
585 // is a real event (no bithdays).
589 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
590 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event') , '', ''] : null;
591 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
592 $drop = [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event') , '', ''];
595 $title = strip_tags(html_entity_decode(BBCode::convert($event['summary']), ENT_QUOTES, 'UTF-8'));
597 list($title, $_trash) = explode("<br", BBCode::convert($event['desc']), 2);
598 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
601 $author_link = $event['author-link'];
602 $plink = $event['plink'];
604 $event['author-link'] = Contact::magicLink($author_link);
605 $event['plink'] = Contact::magicLink($author_link, $plink);
607 $html = self::getHTML($event);
608 $event['desc'] = BBCode::convert($event['desc']);
609 $event['location'] = BBCode::convert($event['location']);
611 'id' => $event['id'],
621 'is_first' => $is_first,
624 'plink' => [$event['plink'], L10n::t('link to source'), '', ''],
632 * @brief Format event to export format (ical/csv).
634 * @param array $events Query result for events.
635 * @param string $format The output format (ical/csv).
636 * @param string $timezone The timezone of the user (not implemented yet).
638 * @return string Content according to selected export format.
640 * @todo Implement timezone support
642 private static function formatListForExport(array $events, $format, $timezone)
644 if (!count($events)) {
649 // Format the exported data as a CSV file.
651 header("Content-type: text/csv");
652 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
654 foreach ($events as $event) {
655 /// @todo The time / date entries don't include any information about the
656 /// timezone the event is scheduled in :-/
657 $tmp1 = strtotime($event['start']);
658 $tmp2 = strtotime($event['finish']);
659 $time_format = "%H:%M:%S";
660 $date_format = "%Y-%m-%d";
662 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
663 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
664 '", "' . strftime($date_format, $tmp2) .
665 '", "' . strftime($time_format, $tmp2) .
666 '", "' . $event['location'] . '"' . PHP_EOL;
670 // Format the exported data as a ics file.
672 header("Content-type: text/ics");
673 $o = 'BEGIN:VCALENDAR' . PHP_EOL
674 . 'VERSION:2.0' . PHP_EOL
675 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
676 /// @todo include timezone informations in cases were the time is not in UTC
677 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
678 // . 'BEGIN:VTIMEZONE' . PHP_EOL
679 // . 'TZID:' . $timezone . PHP_EOL
680 // . 'END:VTIMEZONE' . PHP_EOL;
681 // TODO instead of PHP_EOL CRLF should be used for long entries
682 // but test your solution against http://icalvalid.cloudapp.net/
683 // also long lines SHOULD be split at 75 characters length
684 foreach ($events as $event) {
685 if ($event['adjust'] == 1) {
690 $o .= 'BEGIN:VEVENT' . PHP_EOL;
692 if ($event['start']) {
693 $tmp = strtotime($event['start']);
694 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
695 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
698 if (!$event['nofinish']) {
699 $tmp = strtotime($event['finish']);
700 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
701 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
704 if ($event['summary']) {
705 $tmp = $event['summary'];
706 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
707 $tmp = addcslashes($tmp, ',;');
708 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
711 if ($event['desc']) {
712 $tmp = $event['desc'];
713 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
714 $tmp = addcslashes($tmp, ',;');
715 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
718 if ($event['location']) {
719 $tmp = $event['location'];
720 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
721 $tmp = addcslashes($tmp, ',;');
722 $o .= 'LOCATION:' . $tmp . PHP_EOL;
725 $o .= 'END:VEVENT' . PHP_EOL;
729 $o .= 'END:VCALENDAR' . PHP_EOL;
737 * @brief Get all events for a user ID.
739 * The query for events is done permission sensitive.
740 * If the user is the owner of the calendar they
741 * will get all of their available events.
742 * If the user is only a visitor only the public events will
745 * @param int $uid The user ID.
747 * @return array Query results.
749 private static function getListByUserId($uid = 0)
757 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
759 $conditions = ['uid' => $uid, 'cid' => 0];
761 // Does the user who requests happen to be the owner of the events
762 // requested? then show all of your events, otherwise only those that
763 // don't have limitations set in allow_cid and allow_gid.
764 if (local_user() != $uid) {
765 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
768 $events = DBA::select('event', $fields, $conditions);
769 if (DBA::isResult($events)) {
770 $return = DBA::toArray($events);
778 * @param int $uid The user ID.
779 * @param string $format Output format (ical/csv).
780 * @return array With the results:
781 * bool 'success' => True if the processing was successful,<br>
782 * string 'format' => The output format,<br>
783 * string 'extension' => The file extension of the output format,<br>
784 * string 'content' => The formatted output content.<br>
786 * @todo Respect authenticated users with events_by_uid().
788 public static function exportListByUserId($uid, $format = 'ical')
792 $user = DBA::selectFirst('user', ['timezone'], ['uid' => $uid]);
793 if (DBA::isResult($user)) {
794 $timezone = $user['timezone'];
797 // Get all events which are owned by a uid (respects permissions).
798 $events = self::getListByUserId($uid);
800 // We have the events that are available for the requestor.
801 // Now format the output according to the requested format.
802 $res = self::formatListForExport($events, $format, $timezone);
804 // If there are results the precess was successfull.
809 // Get the file extension for the format.
824 'success' => $process,
826 'extension' => $file_ext,
834 * @brief Format an item array with event data to HTML.
836 * @param array $item Array with item and event data.
837 * @return string HTML output.
839 public static function getItemHTML(array $item) {
843 // Set the different time formats.
844 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
845 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
846 $tformat = L10n::t('g:i A'); // 8:01 AM.
848 // Convert the time to different formats.
849 $dtstart_dt = L10n::getDay(
850 $item['event-adjust'] ?
851 DateTimeFormat::local($item['event-start'], $dformat)
852 : DateTimeFormat::utc($item['event-start'], $dformat)
854 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
855 // Format: Jan till Dec.
856 $month_short = L10n::getDayShort(
857 $item['event-adjust'] ?
858 DateTimeFormat::local($item['event-start'], 'M')
859 : DateTimeFormat::utc($item['event-start'], 'M')
861 // Format: 1 till 31.
862 $date_short = $item['event-adjust'] ?
863 DateTimeFormat::local($item['event-start'], 'j')
864 : DateTimeFormat::utc($item['event-start'], 'j');
865 $start_time = $item['event-adjust'] ?
866 DateTimeFormat::local($item['event-start'], $tformat)
867 : DateTimeFormat::utc($item['event-start'], $tformat);
868 $start_short = L10n::getDayShort(
869 $item['event-adjust'] ?
870 DateTimeFormat::local($item['event-start'], $dformat_short)
871 : DateTimeFormat::utc($item['event-start'], $dformat_short)
874 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
875 if (!$item['event-nofinish']) {
877 $dtend_dt = L10n::getDay(
878 $item['event-adjust'] ?
879 DateTimeFormat::local($item['event-finish'], $dformat)
880 : DateTimeFormat::utc($item['event-finish'], $dformat)
882 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
883 $end_short = L10n::getDayShort(
884 $item['event-adjust'] ?
885 DateTimeFormat::local($item['event-finish'], $dformat_short)
886 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
888 $end_time = $item['event-adjust'] ?
889 DateTimeFormat::local($item['event-finish'], $tformat)
890 : DateTimeFormat::utc($item['event-finish'], $tformat);
891 // Check if start and finish time is at the same day.
892 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
902 // Format the event location.
903 $location = self::locationToArray($item['event-location']);
905 // Construct the profile link (magic-auth).
906 $profile_link = Contact::magicLinkById($item['author-id']);
908 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
909 $return = Renderer::replaceMacros($tpl, [
910 '$id' => $item['event-id'],
911 '$title' => prepare_text($item['event-summary']),
912 '$dtstart_label' => L10n::t('Starts:'),
913 '$dtstart_title' => $dtstart_title,
914 '$dtstart_dt' => $dtstart_dt,
915 '$finish' => $finish,
916 '$dtend_label' => L10n::t('Finishes:'),
917 '$dtend_title' => $dtend_title,
918 '$dtend_dt' => $dtend_dt,
919 '$month_short' => $month_short,
920 '$date_short' => $date_short,
921 '$same_date' => $same_date,
922 '$start_time' => $start_time,
923 '$start_short' => $start_short,
924 '$end_time' => $end_time,
925 '$end_short' => $end_short,
926 '$author_name' => $item['author-name'],
927 '$author_link' => $profile_link,
928 '$author_avatar' => $item['author-avatar'],
929 '$description' => prepare_text($item['event-desc']),
930 '$location_label' => L10n::t('Location:'),
931 '$show_map_label' => L10n::t('Show map'),
932 '$hide_map_label' => L10n::t('Hide map'),
933 '$map_btn_label' => L10n::t('Show map'),
934 '$location' => $location
941 * @brief Format a string with map bbcode to an array with location data.
943 * Note: The string must only contain location data. A string with no bbcode will be
944 * handled as location name.
946 * @param string $s The string with the bbcode formatted location data.
948 * @return array The array with the location data.
949 * 'name' => The name of the location,<br>
950 * 'address' => The address of the location,<br>
951 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
953 private static function locationToArray($s = '') {
958 $location = ['name' => $s];
960 // Map tag with location name - e.g. [map]Paris[/map].
961 if (strpos($s, '[/map]') !== false) {
962 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
963 if (intval($found) > 0 && array_key_exists(1, $match)) {
964 $location['address'] = $match[1];
965 // Remove the map bbcode from the location name.
966 $location['name'] = str_replace($match[0], "", $s);
968 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
969 } elseif (strpos($s, '[map=') !== false) {
970 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
971 if (intval($found) > 0 && array_key_exists(1, $match)) {
972 $location['coordinates'] = $match[1];
973 // Remove the map bbcode from the location name.
974 $location['name'] = str_replace($match[0], "", $s);
978 $location['name'] = prepare_text($location['name']);
980 // Construct the map HTML.
981 if (isset($location['address'])) {
982 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
983 } elseif (isset($location['coordinates'])) {
984 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
991 * @brief Add new birthday event for this person
993 * @param array $contact Contact array, expects: id, uid, url, name
994 * @param string $birthday Birthday of the contact
997 public static function createBirthday($contact, $birthday)
999 // Check for duplicates
1001 'uid' => $contact['uid'],
1002 'cid' => $contact['id'],
1003 'start' => DateTimeFormat::utc($birthday),
1004 'type' => 'birthday'
1006 if (DBA::exists('event', $condition)) {
1011 * Add new birthday event for this person
1013 * summary is just a readable placeholder in case the event is shared
1014 * with others. We will replace it during presentation to our $importer
1015 * to contain a sparkle link and perhaps a photo.
1018 'uid' => $contact['uid'],
1019 'cid' => $contact['id'],
1020 'start' => DateTimeFormat::utc($birthday),
1021 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1022 'summary' => L10n::t('%s\'s birthday', $contact['name']),
1023 'desc' => L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1024 'type' => 'birthday',
1028 self::store($values);