3 * @file src/Model/Event.php
6 namespace Friendica\Model;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Hook;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Renderer;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
15 use Friendica\Protocol\Activity;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Map;
18 use Friendica\Util\Strings;
19 use Friendica\Util\XML;
22 * functions for interacting with the event database table
27 public static function getHTML(array $event, $simple = false)
33 $bd_format = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8 AM.
35 $event_start = DI::l10n()->getDay(
36 !empty($event['adjust']) ?
37 DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
40 if (!empty($event['finish'])) {
41 $event_end = DI::l10n()->getDay(
42 !empty($event['adjust']) ?
43 DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
52 if (!empty($event['summary'])) {
53 $o .= "<h3>" . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . "</h3>";
56 if (!empty($event['desc'])) {
57 $o .= "<div>" . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . "</div>";
60 $o .= "<h4>" . DI::l10n()->t('Starts:') . "</h4><p>" . $event_start . "</p>";
62 if (!$event['nofinish']) {
63 $o .= "<h4>" . DI::l10n()->t('Finishes:') . "</h4><p>" . $event_end . "</p>";
66 if (!empty($event['location'])) {
67 $o .= "<h4>" . DI::l10n()->t('Location:') . "</h4><p>" . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple) . "</p>";
73 $o = '<div class="vevent">' . "\r\n";
75 $o .= '<div class="summary event-summary">' . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . '</div>' . "\r\n";
77 $o .= '<div class="event-start"><span class="event-label">' . DI::l10n()->t('Starts:') . '</span> <span class="dtstart" title="'
78 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
79 . '" >' . $event_start
80 . '</span></div>' . "\r\n";
82 if (!$event['nofinish']) {
83 $o .= '<div class="event-end" ><span class="event-label">' . DI::l10n()->t('Finishes:') . '</span> <span class="dtend" title="'
84 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
86 . '</span></div>' . "\r\n";
89 if (!empty($event['desc'])) {
90 $o .= '<div class="description event-description">' . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . '</div>' . "\r\n";
93 if (!empty($event['location'])) {
94 $o .= '<div class="event-location"><span class="event-label">' . DI::l10n()->t('Location:') . '</span> <span class="location">'
95 . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple)
96 . '</span></div>' . "\r\n";
98 // Include a map of the location if the [map] BBCode is used.
99 if (strpos($event['location'], "[map") !== false) {
100 $map = Map::byLocation($event['location'], $simple);
101 if ($map !== $event['location']) {
107 $o .= '</div>' . "\r\n";
112 * Convert an array with event data to bbcode.
114 * @param array $event Array which contains the event data.
115 * @return string The event as a bbcode formatted string.
117 private static function getBBCode(array $event)
121 if ($event['summary']) {
122 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
125 if ($event['desc']) {
126 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
129 if ($event['start']) {
130 $o .= '[event-start]' . $event['start'] . '[/event-start]';
133 if (($event['finish']) && (!$event['nofinish'])) {
134 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
137 if ($event['location']) {
138 $o .= '[event-location]' . $event['location'] . '[/event-location]';
141 if ($event['adjust']) {
142 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
149 * Extract bbcode formatted event data from a string.
151 * @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 * 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.
222 public static function delete($event_id)
224 if ($event_id == 0) {
228 DBA::delete('event', ['id' => $event_id], ['cascade' => false]);
229 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
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.
239 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
241 public static function store($arr)
244 $event['id'] = intval($arr['id'] ?? 0);
245 $event['uid'] = intval($arr['uid'] ?? 0);
246 $event['cid'] = intval($arr['cid'] ?? 0);
247 $event['guid'] = ($arr['guid'] ?? '') ?: System::createUUID();
248 $event['uri'] = ($arr['uri'] ?? '') ?: Item::newURI($event['uid'], $event['guid']);
249 $event['type'] = ($arr['type'] ?? '') ?: 'event';
250 $event['summary'] = $arr['summary'] ?? '';
251 $event['desc'] = $arr['desc'] ?? '';
252 $event['location'] = $arr['location'] ?? '';
253 $event['allow_cid'] = $arr['allow_cid'] ?? '';
254 $event['allow_gid'] = $arr['allow_gid'] ?? '';
255 $event['deny_cid'] = $arr['deny_cid'] ?? '';
256 $event['deny_gid'] = $arr['deny_gid'] ?? '';
257 $event['adjust'] = intval($arr['adjust'] ?? 0);
258 $event['nofinish'] = intval($arr['nofinish'] ?? (!empty($event['start']) && empty($event['finish'])));
260 $event['created'] = DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now');
261 $event['edited'] = DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now');
262 $event['start'] = DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME);
263 $event['finish'] = DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME);
264 if ($event['finish'] < DBA::NULL_DATETIME) {
265 $event['finish'] = DBA::NULL_DATETIME;
267 $private = intval($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>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
306 $object .= '<content>' . XML::escape(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 Hook::callAll('event_updated', $event['id']);
319 // New event. Store it.
320 DBA::insert('event', $event);
324 // Don't create an item for birthday events
325 if ($event['type'] == 'event') {
326 $event['id'] = DBA::lastInsertId();
330 $item_arr['uid'] = $event['uid'];
331 $item_arr['contact-id'] = $event['cid'];
332 $item_arr['uri'] = $event['uri'];
333 $item_arr['parent-uri'] = $event['uri'];
334 $item_arr['guid'] = $event['guid'];
335 $item_arr['plink'] = $arr['plink'] ?? '';
336 $item_arr['post-type'] = Item::PT_EVENT;
337 $item_arr['wall'] = $event['cid'] ? 0 : 1;
338 $item_arr['contact-id'] = $contact['id'];
339 $item_arr['owner-name'] = $contact['name'];
340 $item_arr['owner-link'] = $contact['url'];
341 $item_arr['owner-avatar'] = $contact['thumb'];
342 $item_arr['author-name'] = $contact['name'];
343 $item_arr['author-link'] = $contact['url'];
344 $item_arr['author-avatar'] = $contact['thumb'];
345 $item_arr['title'] = '';
346 $item_arr['allow_cid'] = $event['allow_cid'];
347 $item_arr['allow_gid'] = $event['allow_gid'];
348 $item_arr['deny_cid'] = $event['deny_cid'];
349 $item_arr['deny_gid'] = $event['deny_gid'];
350 $item_arr['private'] = $private;
351 $item_arr['visible'] = 1;
352 $item_arr['verb'] = Activity::POST;
353 $item_arr['object-type'] = Activity\ObjectType::EVENT;
354 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
355 $item_arr['body'] = self::getBBCode($event);
356 $item_arr['event-id'] = $event['id'];
358 $item_arr['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
359 $item_arr['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
360 $item_arr['object'] .= '</object>' . "\n";
362 $item_id = Item::insert($item_arr);
365 Hook::callAll("event_created", $event['id']);
372 * Create an array with translation strings used for events.
374 * @return array Array with translations strings.
375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
377 public static function getStrings()
379 // First day of the week (0 = Sunday).
380 $firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0);
383 "firstDay" => $firstDay,
384 "allday" => DI::l10n()->t("all-day"),
386 "Sun" => DI::l10n()->t("Sun"),
387 "Mon" => DI::l10n()->t("Mon"),
388 "Tue" => DI::l10n()->t("Tue"),
389 "Wed" => DI::l10n()->t("Wed"),
390 "Thu" => DI::l10n()->t("Thu"),
391 "Fri" => DI::l10n()->t("Fri"),
392 "Sat" => DI::l10n()->t("Sat"),
394 "Sunday" => DI::l10n()->t("Sunday"),
395 "Monday" => DI::l10n()->t("Monday"),
396 "Tuesday" => DI::l10n()->t("Tuesday"),
397 "Wednesday" => DI::l10n()->t("Wednesday"),
398 "Thursday" => DI::l10n()->t("Thursday"),
399 "Friday" => DI::l10n()->t("Friday"),
400 "Saturday" => DI::l10n()->t("Saturday"),
402 "Jan" => DI::l10n()->t("Jan"),
403 "Feb" => DI::l10n()->t("Feb"),
404 "Mar" => DI::l10n()->t("Mar"),
405 "Apr" => DI::l10n()->t("Apr"),
406 "May" => DI::l10n()->t("May"),
407 "Jun" => DI::l10n()->t("Jun"),
408 "Jul" => DI::l10n()->t("Jul"),
409 "Aug" => DI::l10n()->t("Aug"),
410 "Sep" => DI::l10n()->t("Sept"),
411 "Oct" => DI::l10n()->t("Oct"),
412 "Nov" => DI::l10n()->t("Nov"),
413 "Dec" => DI::l10n()->t("Dec"),
415 "January" => DI::l10n()->t("January"),
416 "February" => DI::l10n()->t("February"),
417 "March" => DI::l10n()->t("March"),
418 "April" => DI::l10n()->t("April"),
419 "June" => DI::l10n()->t("June"),
420 "July" => DI::l10n()->t("July"),
421 "August" => DI::l10n()->t("August"),
422 "September" => DI::l10n()->t("September"),
423 "October" => DI::l10n()->t("October"),
424 "November" => DI::l10n()->t("November"),
425 "December" => DI::l10n()->t("December"),
427 "today" => DI::l10n()->t("today"),
428 "month" => DI::l10n()->t("month"),
429 "week" => DI::l10n()->t("week"),
430 "day" => DI::l10n()->t("day"),
432 "noevent" => DI::l10n()->t("No events to display"),
434 "dtstart_label" => DI::l10n()->t("Starts:"),
435 "dtend_label" => DI::l10n()->t("Finishes:"),
436 "location_label" => DI::l10n()->t("Location:")
443 * Removes duplicated birthday events.
445 * @param array $dates Array of possibly duplicated events.
446 * @return array Cleaned events.
448 * @todo We should replace this with a separate update function if there is some time left.
450 private static function removeDuplicates(array $dates)
454 foreach ($dates as $date) {
455 if ($date['type'] == 'birthday') {
456 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
461 return array_values($dates2);
465 * Get an event by its event ID.
467 * @param int $owner_uid The User ID of the owner of the event
468 * @param int $event_id The ID of the event in the event table
469 * @param string $sql_extra
470 * @return array Query result
473 public static function getListById($owner_uid, $event_id, $sql_extra = '')
477 // Ownly allow events if there is a valid owner_id.
478 if ($owner_uid == 0) {
482 // Query for the event by event id
483 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
484 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
485 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
490 if (DBA::isResult($r)) {
491 $return = self::removeDuplicates($r);
498 * Get all events in a specific time frame.
500 * @param int $owner_uid The User ID of the owner of the events.
501 * @param array $event_params An associative array with
503 * string 'start' => Start time of the timeframe.
504 * string 'finish' => Finish time of the timeframe.
505 * string 'adjust_start' =>
506 * string 'adjust_finish' =>
508 * @param string $sql_extra Additional sql conditions (e.g. permission request).
510 * @return array Query results.
513 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
517 // Only allow events if there is a valid owner_id.
518 if ($owner_uid == 0) {
522 // Query for the event by date.
523 // @todo Slow query (518 seconds to run), to be optimzed
524 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
525 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
526 WHERE `event`.`uid` = %d AND event.ignore = %d
527 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
528 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
531 intval($event_params["ignore"]),
532 DBA::escape($event_params["start"]),
533 DBA::escape($event_params["start"]),
534 DBA::escape($event_params["finish"]),
535 DBA::escape($event_params["adjust_start"]),
536 DBA::escape($event_params["adjust_start"]),
537 DBA::escape($event_params["adjust_finish"])
540 if (DBA::isResult($r)) {
541 $return = self::removeDuplicates($r);
548 * Convert an array query results in an array which could be used by the events template.
550 * @param array $event_result Event query array.
551 * @return array Event array for the template.
552 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
553 * @throws \ImagickException
555 public static function prepareListForTemplate(array $event_result)
560 $fmt = DI::l10n()->t('l, F j');
561 foreach ($event_result as $event) {
562 $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
563 if (!DBA::isResult($item)) {
564 // Using default values when no item had been found
565 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
568 $event = array_merge($event, $item);
570 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
571 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
572 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
573 $day = DI::l10n()->getDay($day);
575 if ($event['nofinish']) {
578 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
581 $is_first = ($day !== $last_date);
585 // Show edit and drop actions only if the user is the owner of the event and the event
586 // is a real event (no bithdays).
590 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
591 $edit = !$event['cid'] ? [DI::baseUrl() . '/events/event/' . $event['id'], DI::l10n()->t('Edit event') , '', ''] : null;
592 $copy = !$event['cid'] ? [DI::baseUrl() . '/events/copy/' . $event['id'] , DI::l10n()->t('Duplicate event'), '', ''] : null;
593 $drop = [DI::baseUrl() . '/events/drop/' . $event['id'] , DI::l10n()->t('Delete event') , '', ''];
596 $title = BBCode::convert(Strings::escapeHtml($event['summary']));
598 list($title, $_trash) = explode("<br", BBCode::convert(Strings::escapeHtml($event['desc'])), 2);
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['summary'] = BBCode::convert(Strings::escapeHtml($event['summary']));
609 $event['desc'] = BBCode::convert(Strings::escapeHtml($event['desc']));
610 $event['location'] = BBCode::convert(Strings::escapeHtml($event['location']));
612 'id' => $event['id'],
622 'is_first' => $is_first,
625 'plink' => [$event['plink'], DI::l10n()->t('link to source'), '', ''],
633 * Format event to export format (ical/csv).
635 * @param array $events Query result for events.
636 * @param string $format The output format (ical/csv).
639 * @return string Content according to selected export format.
641 * @todo Implement timezone support
643 private static function formatListForExport(array $events, $format)
647 if (!count($events)) {
652 // Format the exported data as a CSV file.
654 header("Content-type: text/csv");
655 $o .= '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
657 foreach ($events as $event) {
658 /// @todo The time / date entries don't include any information about the
659 /// timezone the event is scheduled in :-/
660 $tmp1 = strtotime($event['start']);
661 $tmp2 = strtotime($event['finish']);
662 $time_format = "%H:%M:%S";
663 $date_format = "%Y-%m-%d";
665 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
666 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
667 '", "' . strftime($date_format, $tmp2) .
668 '", "' . strftime($time_format, $tmp2) .
669 '", "' . $event['location'] . '"' . PHP_EOL;
673 // Format the exported data as a ics file.
675 header("Content-type: text/ics");
676 $o = 'BEGIN:VCALENDAR' . PHP_EOL
677 . 'VERSION:2.0' . PHP_EOL
678 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
679 /// @todo include timezone informations in cases were the time is not in UTC
680 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
681 // . 'BEGIN:VTIMEZONE' . PHP_EOL
682 // . 'TZID:' . $timezone . PHP_EOL
683 // . 'END:VTIMEZONE' . PHP_EOL;
684 // TODO instead of PHP_EOL CRLF should be used for long entries
685 // but test your solution against http://icalvalid.cloudapp.net/
686 // also long lines SHOULD be split at 75 characters length
687 foreach ($events as $event) {
688 if ($event['adjust'] == 1) {
693 $o .= 'BEGIN:VEVENT' . PHP_EOL;
695 if ($event['start']) {
696 $tmp = strtotime($event['start']);
697 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
698 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
701 if (!$event['nofinish']) {
702 $tmp = strtotime($event['finish']);
703 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
704 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
707 if ($event['summary']) {
708 $tmp = $event['summary'];
709 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
710 $tmp = addcslashes($tmp, ',;');
711 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
714 if ($event['desc']) {
715 $tmp = $event['desc'];
716 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
717 $tmp = addcslashes($tmp, ',;');
718 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
721 if ($event['location']) {
722 $tmp = $event['location'];
723 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
724 $tmp = addcslashes($tmp, ',;');
725 $o .= 'LOCATION:' . $tmp . PHP_EOL;
728 $o .= 'END:VEVENT' . PHP_EOL;
732 $o .= 'END:VCALENDAR' . PHP_EOL;
740 * Get all events for a user ID.
742 * The query for events is done permission sensitive.
743 * If the user is the owner of the calendar they
744 * will get all of their available events.
745 * If the user is only a visitor only the public events will
748 * @param int $uid The user ID.
750 * @return array Query results.
753 private static function getListByUserId($uid = 0)
761 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
763 $conditions = ['uid' => $uid, 'cid' => 0];
765 // Does the user who requests happen to be the owner of the events
766 // requested? then show all of your events, otherwise only those that
767 // don't have limitations set in allow_cid and allow_gid.
768 if (local_user() != $uid) {
769 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
772 $events = DBA::select('event', $fields, $conditions);
773 if (DBA::isResult($events)) {
774 $return = DBA::toArray($events);
782 * @param int $uid The user ID.
783 * @param string $format Output format (ical/csv).
784 * @return array With the results:
785 * bool 'success' => True if the processing was successful,<br>
786 * string 'format' => The output format,<br>
787 * string 'extension' => The file extension of the output format,<br>
788 * string 'content' => The formatted output content.<br>
791 * @todo Respect authenticated users with events_by_uid().
793 public static function exportListByUserId($uid, $format = 'ical')
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);
804 // If there are results the precess was successful.
809 // Get the file extension for the format.
824 'success' => $process,
826 'extension' => $file_ext,
834 * Format an item array with event data to HTML.
836 * @param array $item Array with item and event data.
837 * @return string HTML output.
838 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
839 * @throws \ImagickException
841 public static function getItemHTML(array $item) {
845 // Set the different time formats.
846 $dformat = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
847 $dformat_short = DI::l10n()->t('D g:i A'); // Fri 8:01 AM.
848 $tformat = DI::l10n()->t('g:i A'); // 8:01 AM.
850 // Convert the time to different formats.
851 $dtstart_dt = DI::l10n()->getDay(
852 $item['event-adjust'] ?
853 DateTimeFormat::local($item['event-start'], $dformat)
854 : DateTimeFormat::utc($item['event-start'], $dformat)
856 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
857 // Format: Jan till Dec.
858 $month_short = DI::l10n()->getDayShort(
859 $item['event-adjust'] ?
860 DateTimeFormat::local($item['event-start'], 'M')
861 : DateTimeFormat::utc($item['event-start'], 'M')
863 // Format: 1 till 31.
864 $date_short = $item['event-adjust'] ?
865 DateTimeFormat::local($item['event-start'], 'j')
866 : DateTimeFormat::utc($item['event-start'], 'j');
867 $start_time = $item['event-adjust'] ?
868 DateTimeFormat::local($item['event-start'], $tformat)
869 : DateTimeFormat::utc($item['event-start'], $tformat);
870 $start_short = DI::l10n()->getDayShort(
871 $item['event-adjust'] ?
872 DateTimeFormat::local($item['event-start'], $dformat_short)
873 : DateTimeFormat::utc($item['event-start'], $dformat_short)
876 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
877 if (!$item['event-nofinish']) {
879 $dtend_dt = DI::l10n()->getDay(
880 $item['event-adjust'] ?
881 DateTimeFormat::local($item['event-finish'], $dformat)
882 : DateTimeFormat::utc($item['event-finish'], $dformat)
884 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
885 $end_short = DI::l10n()->getDayShort(
886 $item['event-adjust'] ?
887 DateTimeFormat::local($item['event-finish'], $dformat_short)
888 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
890 $end_time = $item['event-adjust'] ?
891 DateTimeFormat::local($item['event-finish'], $tformat)
892 : DateTimeFormat::utc($item['event-finish'], $tformat);
893 // Check if start and finish time is at the same day.
894 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
904 // Format the event location.
905 $location = self::locationToArray($item['event-location']);
907 // Construct the profile link (magic-auth).
908 $profile_link = Contact::magicLinkById($item['author-id']);
910 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
911 $return = Renderer::replaceMacros($tpl, [
912 '$id' => $item['event-id'],
913 '$title' => BBCode::convert($item['event-summary']),
914 '$dtstart_label' => DI::l10n()->t('Starts:'),
915 '$dtstart_title' => $dtstart_title,
916 '$dtstart_dt' => $dtstart_dt,
917 '$finish' => $finish,
918 '$dtend_label' => DI::l10n()->t('Finishes:'),
919 '$dtend_title' => $dtend_title,
920 '$dtend_dt' => $dtend_dt,
921 '$month_short' => $month_short,
922 '$date_short' => $date_short,
923 '$same_date' => $same_date,
924 '$start_time' => $start_time,
925 '$start_short' => $start_short,
926 '$end_time' => $end_time,
927 '$end_short' => $end_short,
928 '$author_name' => $item['author-name'],
929 '$author_link' => $profile_link,
930 '$author_avatar' => $item['author-avatar'],
931 '$description' => BBCode::convert($item['event-desc']),
932 '$location_label' => DI::l10n()->t('Location:'),
933 '$show_map_label' => DI::l10n()->t('Show map'),
934 '$hide_map_label' => DI::l10n()->t('Hide map'),
935 '$map_btn_label' => DI::l10n()->t('Show map'),
936 '$location' => $location
943 * Format a string with map bbcode to an array with location data.
945 * Note: The string must only contain location data. A string with no bbcode will be
946 * handled as location name.
948 * @param string $s The string with the bbcode formatted location data.
950 * @return array The array with the location data.
951 * 'name' => The name of the location,<br>
952 * 'address' => The address of the location,<br>
953 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
954 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
956 private static function locationToArray($s = '') {
961 $location = ['name' => $s];
963 // Map tag with location name - e.g. [map]Paris[/map].
964 if (strpos($s, '[/map]') !== false) {
965 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
966 if (intval($found) > 0 && array_key_exists(1, $match)) {
967 $location['address'] = $match[1];
968 // Remove the map bbcode from the location name.
969 $location['name'] = str_replace($match[0], "", $s);
971 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
972 } elseif (strpos($s, '[map=') !== false) {
973 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
974 if (intval($found) > 0 && array_key_exists(1, $match)) {
975 $location['coordinates'] = $match[1];
976 // Remove the map bbcode from the location name.
977 $location['name'] = str_replace($match[0], "", $s);
981 $location['name'] = BBCode::convert($location['name']);
983 // Construct the map HTML.
984 if (isset($location['address'])) {
985 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
986 } elseif (isset($location['coordinates'])) {
987 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
994 * Add new birthday event for this person
996 * @param array $contact Contact array, expects: id, uid, url, name
997 * @param string $birthday Birthday of the contact
1001 public static function createBirthday($contact, $birthday)
1003 // Check for duplicates
1005 'uid' => $contact['uid'],
1006 'cid' => $contact['id'],
1007 'start' => DateTimeFormat::utc($birthday),
1008 'type' => 'birthday'
1010 if (DBA::exists('event', $condition)) {
1015 * Add new birthday event for this person
1017 * summary is just a readable placeholder in case the event is shared
1018 * with others. We will replace it during presentation to our $importer
1019 * to contain a sparkle link and perhaps a photo.
1022 'uid' => $contact['uid'],
1023 'cid' => $contact['id'],
1024 'start' => DateTimeFormat::utc($birthday),
1025 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1026 'summary' => DI::l10n()->t('%s\'s birthday', $contact['name']),
1027 'desc' => DI::l10n()->t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1028 'type' => 'birthday',
1032 self::store($values);