3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\Renderer;
29 use Friendica\Core\Session;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Protocol\Activity;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Map;
36 use Friendica\Util\Strings;
37 use Friendica\Util\XML;
40 * functions for interacting with the event database table
45 public static function getHTML(array $event, bool $simple = false, int $uriid = 0): string
51 $uriid = $event['uri-id'] ?? $uriid;
53 $bd_format = DI::l10n()->t('l F d, Y \@ g:i A \G\M\TP (e)'); // Friday October 29, 2021 @ 9:15 AM GMT-04:00 (America/New_York)
55 $event_start = DI::l10n()->getDay(DateTimeFormat::local($event['start'], $bd_format));
57 if (!empty($event['finish'])) {
58 $event_end = DI::l10n()->getDay(DateTimeFormat::local($event['finish'], $bd_format));
66 if (!empty($event['summary'])) {
67 $o .= "<h3>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['summary']), $simple) . "</h3>";
70 if (!empty($event['desc'])) {
71 $o .= "<div>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['desc']), $simple) . "</div>";
74 $o .= "<h4>" . DI::l10n()->t('Starts:') . "</h4><p>" . $event_start . "</p>";
76 if (!$event['nofinish']) {
77 $o .= "<h4>" . DI::l10n()->t('Finishes:') . "</h4><p>" . $event_end . "</p>";
80 if (!empty($event['location'])) {
81 $o .= "<h4>" . DI::l10n()->t('Location:') . "</h4><p>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['location']), $simple) . "</p>";
87 $o = '<div class="vevent">' . "\r\n";
89 $o .= '<div class="summary event-summary">' . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['summary']), $simple) . '</div>' . "\r\n";
91 $o .= '<div class="event-start"><span class="event-label">' . DI::l10n()->t('Starts:') . '</span> <span class="dtstart" title="'
92 . DateTimeFormat::local($event['start'], DateTimeFormat::ATOM)
93 . '" >' . $event_start
94 . '</span></div>' . "\r\n";
96 if (!$event['nofinish']) {
97 $o .= '<div class="event-end" ><span class="event-label">' . DI::l10n()->t('Finishes:') . '</span> <span class="dtend" title="'
98 . DateTimeFormat::local($event['finish'], DateTimeFormat::ATOM)
100 . '</span></div>' . "\r\n";
103 if (!empty($event['desc'])) {
104 $o .= '<div class="description event-description">' . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['desc']), $simple) . '</div>' . "\r\n";
107 if (!empty($event['location'])) {
108 $o .= '<div class="event-location"><span class="event-label">' . DI::l10n()->t('Location:') . '</span> <span class="location">'
109 . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['location']), $simple)
110 . '</span></div>' . "\r\n";
112 // Include a map of the location if the [map] BBCode is used.
113 if (strpos($event['location'], "[map") !== false) {
114 $map = Map::byLocation($event['location'], $simple);
115 if ($map !== $event['location']) {
121 $o .= '</div>' . "\r\n";
126 * Convert an array with event data to bbcode.
128 * @param array $event Array which contains the event data.
129 * @return string The event as a bbcode formatted string.
131 private static function getBBCode(array $event): string
135 if ($event['summary']) {
136 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
139 if ($event['desc']) {
140 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
143 if ($event['start']) {
144 $o .= '[event-start]' . $event['start'] . '[/event-start]';
147 if (($event['finish']) && (!$event['nofinish'])) {
148 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
151 if ($event['location']) {
152 $o .= '[event-location]' . $event['location'] . '[/event-location]';
159 * Extract bbcode formatted event data from a string.
161 * @param string $text The string which should be parsed for event data.
162 * @return array The array with the event information.
164 public static function fromBBCode(string $text): array
169 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
170 $ev['summary'] = $match[1];
174 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
175 $ev['desc'] = $match[1];
179 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
180 $ev['start'] = $match[1];
184 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
185 $ev['finish'] = $match[1];
189 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
190 $ev['location'] = $match[1];
193 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
198 public static function sortByDate(array $event_list): array
200 usort($event_list, ['self', 'compareDatesCallback']);
204 private static function compareDatesCallback(array $event_a, array $event_b)
206 $date_a = DateTimeFormat::local($event_a['start']);
207 $date_b = DateTimeFormat::local($event_b['start']);
209 if ($date_a === $date_b) {
210 return strcasecmp($event_a['desc'], $event_b['desc']);
213 return strcmp($date_a, $date_b);
217 * Delete an event from the event table.
219 * Note: This function does only delete the event from the event table not its
220 * related entry in the item table.
222 * @param int $event_id Event ID.
226 public static function delete(int $event_id)
228 if ($event_id == 0) {
232 DBA::delete('event', ['id' => $event_id]);
233 Logger::info("Deleted event", ['id' => $event_id]);
239 * Store the event in the event table and create an event item in the item table.
241 * @param array $arr Array with event data.
242 * @return int The new event id.
243 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
245 public static function store(array $arr): int
247 $guid = $arr['guid'] ?? '' ?: System::createUUID();
248 $uri = $arr['uri'] ?? '' ?: Item::newURI($guid);
250 'id' => intval($arr['id'] ?? 0),
251 'uid' => intval($arr['uid'] ?? 0),
252 'cid' => intval($arr['cid'] ?? 0),
255 'uri-id' => ItemURI::insert(['uri' => $uri, 'guid' => $guid]),
256 'type' => ($arr['type'] ?? '') ?: 'event',
257 'summary' => $arr['summary'] ?? '',
258 'desc' => $arr['desc'] ?? '',
259 'location' => $arr['location'] ?? '',
260 'allow_cid' => $arr['allow_cid'] ?? '',
261 'allow_gid' => $arr['allow_gid'] ?? '',
262 'deny_cid' => $arr['deny_cid'] ?? '',
263 'deny_gid' => $arr['deny_gid'] ?? '',
264 'nofinish' => intval($arr['nofinish'] ?? (!empty($arr['start']) && empty($arr['finish']))),
265 'created' => DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now'),
266 'edited' => DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now'),
267 'start' => DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME),
268 'finish' => DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME),
272 if ($event['finish'] < DBA::NULL_DATETIME) {
273 $event['finish'] = DBA::NULL_DATETIME;
276 // Existing event being modified.
278 // has the event actually changed?
279 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
280 if (!DBA::isResult($existing_event)) {
284 if ($existing_event['edited'] === $event['edited']) {
289 'edited' => $event['edited'],
290 'start' => $event['start'],
291 'finish' => $event['finish'],
292 'summary' => $event['summary'],
293 'desc' => $event['desc'],
294 'location' => $event['location'],
295 'type' => $event['type'],
296 'nofinish' => $event['nofinish'],
299 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
301 $item = Post::selectFirst(['id', 'uri-id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
302 if (DBA::isResult($item)) {
303 $object = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
304 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
305 $object .= '</object>' . "\n";
307 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
308 Item::update($fields, ['id' => $item['id']]);
311 Hook::callAll('event_updated', $event['id']);
313 // New event. Store it.
314 DBA::insert('event', $event);
316 $event['id'] = DBA::lastInsertId();
318 Hook::callAll("event_created", $event['id']);
324 public static function getItemArrayForId(int $event_id, array $item = []): array
326 if (empty($event_id)) {
330 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
331 if ($event['type'] != 'event') {
336 $conditions = ['id' => $event['cid']];
338 $conditions = ['uid' => $event['uid'], 'self' => true];
341 $contact = DBA::selectFirst('contact', [], $conditions);
343 $event['id'] = $event_id;
345 $item['uid'] = $event['uid'];
346 $item['contact-id'] = $event['cid'];
347 $item['uri'] = $event['uri'];
348 $item['uri-id'] = ItemURI::getIdByURI($event['uri']);
349 $item['guid'] = $event['guid'];
350 $item['plink'] = $arr['plink'] ?? '';
351 $item['post-type'] = Item::PT_EVENT;
352 $item['wall'] = $event['cid'] ? 0 : 1;
353 $item['contact-id'] = $contact['id'];
354 $item['owner-name'] = $contact['name'];
355 $item['owner-link'] = $contact['url'];
356 $item['owner-avatar'] = $contact['thumb'];
357 $item['author-name'] = $contact['name'];
358 $item['author-link'] = $contact['url'];
359 $item['author-avatar'] = $contact['thumb'];
361 $item['allow_cid'] = $event['allow_cid'];
362 $item['allow_gid'] = $event['allow_gid'];
363 $item['deny_cid'] = $event['deny_cid'];
364 $item['deny_gid'] = $event['deny_gid'];
365 $item['private'] = intval($event['private'] ?? 0);
366 $item['visible'] = 1;
367 $item['verb'] = Activity::POST;
368 $item['object-type'] = Activity\ObjectType::EVENT;
369 $item['post-type'] = Item::PT_EVENT;
370 $item['origin'] = $event['cid'] === 0 ? 1 : 0;
371 $item['body'] = self::getBBCode($event);
372 $item['event-id'] = $event['id'];
374 $item['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
375 $item['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
376 $item['object'] .= '</object>' . "\n";
381 public static function getItemArrayForImportedId(int $event_id, array $item = []): array
383 if (empty($event_id)) {
387 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
388 if ($event['type'] != 'event') {
392 $item['post-type'] = Item::PT_EVENT;
394 $item['object-type'] = Activity\ObjectType::EVENT;
395 $item['body'] = self::getBBCode($event);
396 $item['event-id'] = $event_id;
398 $item['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
399 $item['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
400 $item['object'] .= '</object>' . "\n";
406 * Create an array with translation strings used for events.
408 * @return array Array with translations strings.
409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
411 public static function getStrings(): array
413 // First day of the week (0 = Sunday).
414 $firstDay = DI::pConfig()->get(Session::getLocalUser(), 'system', 'first_day_of_week', 0);
417 "firstDay" => $firstDay,
418 "allday" => DI::l10n()->t("all-day"),
420 "Sun" => DI::l10n()->t("Sun"),
421 "Mon" => DI::l10n()->t("Mon"),
422 "Tue" => DI::l10n()->t("Tue"),
423 "Wed" => DI::l10n()->t("Wed"),
424 "Thu" => DI::l10n()->t("Thu"),
425 "Fri" => DI::l10n()->t("Fri"),
426 "Sat" => DI::l10n()->t("Sat"),
428 "Sunday" => DI::l10n()->t("Sunday"),
429 "Monday" => DI::l10n()->t("Monday"),
430 "Tuesday" => DI::l10n()->t("Tuesday"),
431 "Wednesday" => DI::l10n()->t("Wednesday"),
432 "Thursday" => DI::l10n()->t("Thursday"),
433 "Friday" => DI::l10n()->t("Friday"),
434 "Saturday" => DI::l10n()->t("Saturday"),
436 "Jan" => DI::l10n()->t("Jan"),
437 "Feb" => DI::l10n()->t("Feb"),
438 "Mar" => DI::l10n()->t("Mar"),
439 "Apr" => DI::l10n()->t("Apr"),
440 "May" => DI::l10n()->t("May"),
441 "Jun" => DI::l10n()->t("Jun"),
442 "Jul" => DI::l10n()->t("Jul"),
443 "Aug" => DI::l10n()->t("Aug"),
444 "Sep" => DI::l10n()->t("Sept"),
445 "Oct" => DI::l10n()->t("Oct"),
446 "Nov" => DI::l10n()->t("Nov"),
447 "Dec" => DI::l10n()->t("Dec"),
449 "January" => DI::l10n()->t("January"),
450 "February" => DI::l10n()->t("February"),
451 "March" => DI::l10n()->t("March"),
452 "April" => DI::l10n()->t("April"),
453 "June" => DI::l10n()->t("June"),
454 "July" => DI::l10n()->t("July"),
455 "August" => DI::l10n()->t("August"),
456 "September" => DI::l10n()->t("September"),
457 "October" => DI::l10n()->t("October"),
458 "November" => DI::l10n()->t("November"),
459 "December" => DI::l10n()->t("December"),
461 "today" => DI::l10n()->t("today"),
462 "month" => DI::l10n()->t("month"),
463 "week" => DI::l10n()->t("week"),
464 "day" => DI::l10n()->t("day"),
466 "noevent" => DI::l10n()->t("No events to display"),
468 "dtstart_label" => DI::l10n()->t("Starts:"),
469 "dtend_label" => DI::l10n()->t("Finishes:"),
470 "location_label" => DI::l10n()->t("Location:")
477 * Removes duplicated birthday events.
479 * @param array $dates Array of possibly duplicated events.
480 * @return array Cleaned events.
482 * @todo We should replace this with a separate update function if there is some time left.
484 private static function removeDuplicates(array $dates): array
488 foreach ($dates as $date) {
489 if ($date['type'] == 'birthday') {
490 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
495 return array_values($dates2);
499 * Get an event by its event ID.
501 * @param int $owner_uid The User ID of the owner of the event
502 * @param int $event_id The ID of the event in the event table
503 * @param string $sql_extra
504 * @return array Query result
507 public static function getListById(int $owner_uid, int $event_id, string $sql_extra = ''): array
511 // Ownly allow events if there is a valid owner_id.
512 if ($owner_uid == 0) {
516 // Query for the event by event id
517 $events = DBA::toArray(DBA::p("SELECT `event`.*, `post-user`.`id` AS `itemid` FROM `event`
518 LEFT JOIN `post-user` ON `post-user`.`event-id` = `event`.`id` AND `post-user`.`uid` = `event`.`uid`
519 WHERE `event`.`uid` = ? AND `event`.`id` = ? $sql_extra",
520 $owner_uid, $event_id));
522 if (DBA::isResult($events)) {
523 $return = self::removeDuplicates($events);
530 * Get all events in a specific time frame.
532 * @param int $owner_uid The User ID of the owner of the events.
533 * @param array $event_params An associative array with
535 * string 'start' => Start time of the timeframe.
536 * string 'finish' => Finish time of the timeframe.
538 * @param string $sql_extra Additional sql conditions (e.g. permission request).
540 * @return array Query results.
543 public static function getListByDate(int $owner_uid, array $event_params, string $sql_extra = ''): array
547 // Only allow events if there is a valid owner_id.
548 if ($owner_uid == 0) {
552 // Query for the event by date.
553 $events = DBA::toArray(DBA::p("SELECT `event`.*, `post-user`.`id` AS `itemid` FROM `event`
554 LEFT JOIN `post-user` ON `post-user`.`event-id` = `event`.`id` AND `post-user`.`uid` = `event`.`uid`
555 WHERE `event`.`uid` = ? AND `event`.`ignore` = ?
556 AND (`finish` >= ? OR (`nofinish` AND `start` >= ?)) AND `start` <= ?
558 $owner_uid, $event_params['ignore'],
559 $event_params['start'], $event_params['start'], $event_params['finish']
562 if (DBA::isResult($events)) {
563 $return = self::removeDuplicates($events);
570 * Convert an array query results in an array which could be used by the events template.
572 * @param array $event_result Event query array.
573 * @return array Event array for the template.
574 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
575 * @throws \ImagickException
577 public static function prepareListForTemplate(array $event_result): array
582 $fmt = DI::l10n()->t('l, F j');
583 foreach ($event_result as $event) {
584 $item = Post::selectFirst(['plink', 'author-name', 'author-network', 'author-id', 'author-avatar', 'author-link', 'private', 'uri-id'], ['id' => $event['itemid']]);
585 if (!DBA::isResult($item)) {
586 // Using default values when no item had been found
587 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => '', 'private' => Item::PUBLIC, 'uri-id' => ($event['uri-id'] ?? 0)];
590 $event = array_merge($event, $item);
592 $start = DateTimeFormat::local($event['start'], 'c');
593 $j = DateTimeFormat::local($event['start'], 'j');
594 $day = DateTimeFormat::local($event['start'], $fmt);
595 $day = DI::l10n()->getDay($day);
597 if ($event['nofinish']) {
600 $end = DateTimeFormat::local($event['finish'], 'c');
603 $is_first = ($day !== $last_date);
607 // Show edit and drop actions only if the user is the owner of the event and the event
608 // is a real event (no bithdays).
612 if (Session::getLocalUser() && Session::getLocalUser() == $event['uid'] && $event['type'] == 'event') {
613 $edit = !$event['cid'] ? [DI::baseUrl() . '/events/event/' . $event['id'], DI::l10n()->t('Edit event') , '', ''] : null;
614 $copy = !$event['cid'] ? [DI::baseUrl() . '/events/copy/' . $event['id'] , DI::l10n()->t('Duplicate event'), '', ''] : null;
615 $drop = [DI::baseUrl() . '/events/drop/' . $event['id'] , DI::l10n()->t('Delete event') , '', ''];
618 $title = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['summary']));
620 list($title, $_trash) = explode("<br", BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc'])), BBCode::API);
623 $author_link = $event['author-link'];
625 $event['author-link'] = Contact::magicLink($author_link);
627 $html = self::getHTML($event);
628 $event['summary'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['summary']));
629 $event['desc'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc']));
630 $event['location'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['location']));
632 'id' => $event['id'],
642 'is_first' => $is_first,
645 'plink' => Item::getPlink($event),
653 * Format event to export format (ical/csv).
655 * @param array $events Query result for events.
656 * @param string $format The output format (ical/csv).
658 * @param string $timezone Timezone (missing parameter!)
659 * @return string Content according to selected export format.
661 * @todo Implement timezone support
663 private static function formatListForExport(array $events, string $format): string
667 if (!count($events)) {
672 // Format the exported data as a CSV file.
674 header("Content-type: text/csv");
675 $o .= '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
677 foreach ($events as $event) {
678 /// @todo The time / date entries don't include any information about the
679 /// timezone the event is scheduled in :-/
680 $tmp1 = strtotime($event['start']);
681 $tmp2 = strtotime($event['finish']);
682 $time_format = "%H:%M:%S";
683 $date_format = "%Y-%m-%d";
685 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
686 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
687 '", "' . strftime($date_format, $tmp2) .
688 '", "' . strftime($time_format, $tmp2) .
689 '", "' . $event['location'] . '"' . PHP_EOL;
693 // Format the exported data as a ics file.
695 header("Content-type: text/ics");
696 $o = 'BEGIN:VCALENDAR' . PHP_EOL
697 . 'VERSION:2.0' . PHP_EOL
698 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
699 /// @todo include timezone informations in cases were the time is not in UTC
700 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
701 // . 'BEGIN:VTIMEZONE' . PHP_EOL
702 // . 'TZID:' . $timezone . PHP_EOL
703 // . 'END:VTIMEZONE' . PHP_EOL;
704 // TODO instead of PHP_EOL CRLF should be used for long entries
705 // but test your solution against http://icalvalid.cloudapp.net/
706 // also long lines SHOULD be split at 75 characters length
707 foreach ($events as $event) {
708 $o .= 'BEGIN:VEVENT' . PHP_EOL;
710 if ($event['start']) {
711 $o .= 'DTSTART:' . DateTimeFormat::utc($event['start'], 'Ymd\THis\Z') . PHP_EOL;
714 if (!$event['nofinish']) {
715 $o .= 'DTEND:' . DateTimeFormat::utc($event['finish'], 'Ymd\THis\Z') . PHP_EOL;
718 if ($event['summary']) {
719 $tmp = $event['summary'];
720 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
721 $tmp = addcslashes($tmp, ',;');
722 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
725 if ($event['desc']) {
726 $tmp = $event['desc'];
727 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
728 $tmp = addcslashes($tmp, ',;');
729 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
732 if ($event['location']) {
733 $tmp = $event['location'];
734 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
735 $tmp = addcslashes($tmp, ',;');
736 $o .= 'LOCATION:' . $tmp . PHP_EOL;
739 $o .= 'END:VEVENT' . PHP_EOL;
743 $o .= 'END:VCALENDAR' . PHP_EOL;
751 * Get all events for a user ID.
753 * The query for events is done permission sensitive.
754 * If the user is the owner of the calendar they
755 * will get all of their available events.
756 * If the user is only a visitor only the public events will
759 * @param int $uid The user ID.
761 * @return array Query results.
764 private static function getListByUserId(int $uid = 0): array
772 $fields = ['start', 'finish', 'summary', 'desc', 'location', 'nofinish'];
774 $conditions = ['uid' => $uid, 'cid' => 0];
776 // Does the user who requests happen to be the owner of the events
777 // requested? then show all of your events, otherwise only those that
778 // don't have limitations set in allow_cid and allow_gid.
779 if (Session::getLocalUser() != $uid) {
780 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
783 $events = DBA::select('event', $fields, $conditions);
784 if (DBA::isResult($events)) {
785 $return = DBA::toArray($events);
793 * @param int $uid The user ID.
794 * @param string $format Output format (ical/csv).
795 * @return array With the results:
796 * bool 'success' => True if the processing was successful,<br>
797 * string 'format' => The output format,<br>
798 * string 'extension' => The file extension of the output format,<br>
799 * string 'content' => The formatted output content.<br>
802 * @todo Respect authenticated users with events_by_uid().
804 public static function exportListByUserId(int $uid, string $format = 'ical'): array
808 // Get all events which are owned by a uid (respects permissions).
809 $events = self::getListByUserId($uid);
811 // We have the events that are available for the requestor.
812 // Now format the output according to the requested format.
813 $res = self::formatListForExport($events, $format);
815 // If there are results the precess was successful.
820 // Get the file extension for the format.
835 'success' => $process,
837 'extension' => $file_ext,
845 * Format an item array with event data to HTML.
847 * @param array $item Array with item and event data.
848 * @return string HTML output.
849 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
850 * @throws \ImagickException
852 public static function getItemHTML(array $item): string
857 // Set the different time formats.
858 $dformat = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
859 $dformat_short = DI::l10n()->t('D g:i A'); // Fri 8:01 AM.
860 $tformat = DI::l10n()->t('g:i A'); // 8:01 AM.
862 // Convert the time to different formats.
863 $dtstart_dt = DI::l10n()->getDay(DateTimeFormat::local($item['event-start'], $dformat));
864 $dtstart_title = DateTimeFormat::utc($item['event-start'], DateTimeFormat::ATOM);
865 // Format: Jan till Dec.
866 $month_short = DI::l10n()->getDayShort(DateTimeFormat::local($item['event-start'], 'M'));
867 // Format: 1 till 31.
868 $date_short = DateTimeFormat::local($item['event-start'], 'j');
869 $start_time = DateTimeFormat::local($item['event-start'], $tformat);
870 $start_short = DI::l10n()->getDayShort(DateTimeFormat::local($item['event-start'], $dformat_short));
872 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
873 if (!$item['event-nofinish']) {
875 $dtend_dt = DI::l10n()->getDay(DateTimeFormat::local($item['event-finish'], $dformat));
876 $dtend_title = DateTimeFormat::utc($item['event-finish'], DateTimeFormat::ATOM);
877 $end_short = DI::l10n()->getDayShort(DateTimeFormat::utc($item['event-finish'], $dformat_short));
878 $end_time = DateTimeFormat::local($item['event-finish'], $tformat);
879 // Check if start and finish time is at the same day.
880 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
890 // Format the event location.
891 $location = self::locationToArray($item['event-location']);
893 // Construct the profile link (magic-auth).
894 $author = ['uid' => 0, 'id' => $item['author-id'],
895 'network' => $item['author-network'], 'url' => $item['author-link']];
896 $profile_link = Contact::magicLinkByContact($author);
898 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
899 $return = Renderer::replaceMacros($tpl, [
900 '$id' => $item['event-id'],
901 '$title' => BBCode::convertForUriId($item['uri-id'], $item['event-summary']),
902 '$dtstart_label' => DI::l10n()->t('Starts:'),
903 '$dtstart_title' => $dtstart_title,
904 '$dtstart_dt' => $dtstart_dt,
905 '$finish' => $finish,
906 '$dtend_label' => DI::l10n()->t('Finishes:'),
907 '$dtend_title' => $dtend_title,
908 '$dtend_dt' => $dtend_dt,
909 '$month_short' => $month_short,
910 '$date_short' => $date_short,
911 '$same_date' => $same_date,
912 '$start_time' => $start_time,
913 '$start_short' => $start_short,
914 '$end_time' => $end_time,
915 '$end_short' => $end_short,
916 '$author_name' => $item['author-name'],
917 '$author_link' => $profile_link,
918 '$author_avatar' => $item['author-avatar'],
919 '$description' => BBCode::convertForUriId($item['uri-id'], $item['event-desc']),
920 '$location_label' => DI::l10n()->t('Location:'),
921 '$show_map_label' => DI::l10n()->t('Show map'),
922 '$hide_map_label' => DI::l10n()->t('Hide map'),
923 '$map_btn_label' => DI::l10n()->t('Show map'),
924 '$location' => $location
931 * Format a string with map bbcode to an array with location data.
933 * Note: The string must only contain location data. A string with no bbcode will be
934 * handled as location name.
936 * @param string $s The string with the bbcode formatted location data.
938 * @return array The array with the location data.
939 * 'name' => The name of the location,<br>
940 * 'address' => The address of the location,<br>
941 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
942 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
944 private static function locationToArray(string $s = ''): array
950 $location = ['name' => $s];
952 // Map tag with location name - e.g. [map]Paris[/map].
953 if (strpos($s, '[/map]') !== false) {
954 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
955 if (intval($found) > 0 && array_key_exists(1, $match)) {
956 $location['address'] = $match[1];
957 // Remove the map bbcode from the location name.
958 $location['name'] = str_replace($match[0], "", $s);
960 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
961 } elseif (strpos($s, '[map=') !== false) {
962 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
963 if (intval($found) > 0 && array_key_exists(1, $match)) {
964 $location['coordinates'] = $match[1];
965 // Remove the map bbcode from the location name.
966 $location['name'] = str_replace($match[0], "", $s);
970 $location['name'] = BBCode::convert($location['name']);
972 // Construct the map HTML.
973 if (isset($location['address'])) {
974 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
975 } elseif (isset($location['coordinates'])) {
976 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
983 * Add new birthday event for this person
985 * @param array $contact Contact array, expects: id, uid, url, name
986 * @param string $birthday Birthday of the contact
990 public static function createBirthday(array $contact, string $birthday): bool
992 // Check for duplicates
994 'uid' => $contact['uid'],
995 'cid' => $contact['id'],
996 'start' => DateTimeFormat::utc($birthday),
999 if (DBA::exists('event', $condition)) {
1004 * Add new birthday event for this person
1006 * summary is just a readable placeholder in case the event is shared
1007 * with others. We will replace it during presentation to our $importer
1008 * to contain a sparkle link and perhaps a photo.
1011 'uid' => $contact['uid'],
1012 'cid' => $contact['id'],
1013 'start' => DateTimeFormat::utc($birthday),
1014 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1015 'summary' => DI::l10n()->t('%s\'s birthday', $contact['name']),
1016 'desc' => DI::l10n()->t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1017 'type' => 'birthday',
1020 // Check if self::store() was success
1021 return (self::store($values) > 0);