3 * @copyright Copyright (C) 2010-2023, 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\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Renderer;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Network\HTTPException;
33 use Friendica\Protocol\Activity;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Map;
36 use Friendica\Util\Strings;
37 use Friendica\Util\Temporal;
38 use Friendica\Util\XML;
41 * functions for interacting with the event database table
46 public static function getHTML(array $event, bool $simple = false, int $uriid = 0): string
52 $uriid = $event['uri-id'] ?? $uriid;
54 $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)
56 $event_start = DI::l10n()->getDay(DateTimeFormat::local($event['start'], $bd_format));
58 if (!empty($event['finish'])) {
59 $event_end = DI::l10n()->getDay(DateTimeFormat::local($event['finish'], $bd_format));
67 if (!empty($event['summary'])) {
68 $o .= "<h3>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['summary']), $simple) . "</h3>";
71 if (!empty($event['desc'])) {
72 $o .= "<div>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['desc']), $simple) . "</div>";
75 $o .= "<h4>" . DI::l10n()->t('Starts:') . "</h4><p>" . $event_start . "</p>";
77 if (!$event['nofinish']) {
78 $o .= "<h4>" . DI::l10n()->t('Finishes:') . "</h4><p>" . $event_end . "</p>";
81 if (!empty($event['location'])) {
82 $o .= "<h4>" . DI::l10n()->t('Location:') . "</h4><p>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['location']), $simple) . "</p>";
88 $o = '<div class="vevent">' . "\r\n";
90 $o .= '<div class="summary event-summary">' . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['summary']), $simple) . '</div>' . "\r\n";
92 $o .= '<div class="event-start"><span class="event-label">' . DI::l10n()->t('Starts:') . '</span> <span class="dtstart" title="'
93 . DateTimeFormat::local($event['start'], DateTimeFormat::ATOM)
94 . '" >' . $event_start
95 . '</span></div>' . "\r\n";
97 if (!$event['nofinish']) {
98 $o .= '<div class="event-end" ><span class="event-label">' . DI::l10n()->t('Finishes:') . '</span> <span class="dtend" title="'
99 . DateTimeFormat::local($event['finish'], DateTimeFormat::ATOM)
101 . '</span></div>' . "\r\n";
104 if (!empty($event['desc'])) {
105 $o .= '<div class="description event-description">' . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['desc']), $simple) . '</div>' . "\r\n";
108 if (!empty($event['location'])) {
109 $o .= '<div class="event-location"><span class="event-label">' . DI::l10n()->t('Location:') . '</span> <span class="location">'
110 . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['location']), $simple)
111 . '</span></div>' . "\r\n";
113 // Include a map of the location if the [map] BBCode is used.
114 if (strpos($event['location'], "[map") !== false) {
115 $map = Map::byLocation($event['location'], $simple);
116 if ($map !== $event['location']) {
122 $o .= '</div>' . "\r\n";
127 * Convert an array with event data to bbcode.
129 * @param array $event Array which contains the event data.
130 * @return string The event as a bbcode formatted string.
132 private static function getBBCode(array $event): string
136 if ($event['summary']) {
137 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
140 if ($event['desc']) {
141 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
144 if ($event['start']) {
145 $o .= '[event-start]' . $event['start'] . '[/event-start]';
148 if (($event['finish']) && (!$event['nofinish'])) {
149 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
152 if ($event['location']) {
153 $o .= '[event-location]' . $event['location'] . '[/event-location]';
160 * Extract bbcode formatted event data from a string.
162 * @param string $text The string which should be parsed for event data.
163 * @return array The array with the event information.
165 public static function fromBBCode(string $text): array
170 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
171 $ev['summary'] = $match[1];
175 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
176 $ev['desc'] = $match[1];
180 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
181 $ev['start'] = $match[1];
185 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
186 $ev['finish'] = $match[1];
190 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
191 $ev['location'] = $match[1];
194 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
199 public static function sortByDate(array $event_list): array
201 usort($event_list, [self::class, 'compareDatesCallback']);
205 private static function compareDatesCallback(array $event_a, array $event_b)
207 $date_a = DateTimeFormat::local($event_a['start']);
208 $date_b = DateTimeFormat::local($event_b['start']);
210 if ($date_a === $date_b) {
211 return strcasecmp($event_a['desc'], $event_b['desc']);
214 return strcmp($date_a, $date_b);
218 * Delete an event from the event table.
220 * Note: This function does only delete the event from the event table not its
221 * related entry in the item table.
223 * @param int $event_id Event ID.
227 public static function delete(int $event_id)
229 if ($event_id == 0) {
233 DBA::delete('event', ['id' => $event_id]);
234 Logger::info("Deleted event", ['id' => $event_id]);
240 * Store the event in the event table and create an event item in the item table.
242 * @param array $arr Array with event data.
243 * @return int The new event id.
244 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
246 public static function store(array $arr): int
248 $guid = $arr['guid'] ?? '' ?: System::createUUID();
249 $uri = $arr['uri'] ?? '' ?: Item::newURI($guid);
251 'id' => intval($arr['id'] ?? 0),
252 'uid' => intval($arr['uid'] ?? 0),
253 'cid' => intval($arr['cid'] ?? 0),
256 'uri-id' => ItemURI::insert(['uri' => $uri, 'guid' => $guid]),
257 'type' => ($arr['type'] ?? '') ?: 'event',
258 'summary' => $arr['summary'] ?? '',
259 'desc' => $arr['desc'] ?? '',
260 'location' => $arr['location'] ?? '',
261 'allow_cid' => $arr['allow_cid'] ?? '',
262 'allow_gid' => $arr['allow_gid'] ?? '',
263 'deny_cid' => $arr['deny_cid'] ?? '',
264 'deny_gid' => $arr['deny_gid'] ?? '',
265 'nofinish' => intval($arr['nofinish'] ?? (!empty($arr['start']) && empty($arr['finish']))),
266 'created' => DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now'),
267 'edited' => DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now'),
268 'start' => DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME),
269 'finish' => DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME),
273 if ($event['finish'] < DBA::NULL_DATETIME) {
274 $event['finish'] = DBA::NULL_DATETIME;
277 // Existing event being modified.
279 // has the event actually changed?
280 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
281 if (!DBA::isResult($existing_event)) {
285 if ($existing_event['edited'] === $event['edited']) {
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 'nofinish' => $event['nofinish'],
300 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
302 $item = Post::selectFirst(['id', 'uri-id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
303 if (DBA::isResult($item)) {
304 $object = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
305 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
306 $object .= '</object>' . "\n";
308 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
309 Item::update($fields, ['id' => $item['id']]);
312 Hook::callAll('event_updated', $event['id']);
314 // New event. Store it.
315 DBA::insert('event', $event);
317 $event['id'] = DBA::lastInsertId();
319 Hook::callAll("event_created", $event['id']);
325 public static function getItemArrayForId(int $event_id, array $item = []): array
327 if (empty($event_id)) {
331 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
332 if ($event['type'] != 'event') {
337 $conditions = ['id' => $event['cid']];
339 $conditions = ['uid' => $event['uid'], 'self' => true];
342 $contact = DBA::selectFirst('contact', [], $conditions);
344 $event['id'] = $event_id;
346 $item['uid'] = $event['uid'];
347 $item['contact-id'] = $event['cid'];
348 $item['uri'] = $event['uri'];
349 $item['uri-id'] = ItemURI::getIdByURI($event['uri']);
350 $item['guid'] = $event['guid'];
351 $item['plink'] = $arr['plink'] ?? '';
352 $item['post-type'] = Item::PT_EVENT;
353 $item['wall'] = $event['cid'] ? 0 : 1;
354 $item['contact-id'] = $contact['id'];
355 $item['owner-name'] = $contact['name'];
356 $item['owner-link'] = $contact['url'];
357 $item['owner-avatar'] = $contact['thumb'];
358 $item['author-name'] = $contact['name'];
359 $item['author-link'] = $contact['url'];
360 $item['author-avatar'] = $contact['thumb'];
362 $item['allow_cid'] = $event['allow_cid'];
363 $item['allow_gid'] = $event['allow_gid'];
364 $item['deny_cid'] = $event['deny_cid'];
365 $item['deny_gid'] = $event['deny_gid'];
366 $item['private'] = intval($event['private'] ?? 0);
367 $item['visible'] = 1;
368 $item['verb'] = Activity::POST;
369 $item['object-type'] = Activity\ObjectType::EVENT;
370 $item['post-type'] = Item::PT_EVENT;
371 $item['origin'] = $event['cid'] === 0 ? 1 : 0;
372 $item['body'] = self::getBBCode($event);
373 $item['event-id'] = $event['id'];
375 $item['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
376 $item['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
377 $item['object'] .= '</object>' . "\n";
382 public static function getItemArrayForImportedId(int $event_id, array $item = []): array
384 if (empty($event_id)) {
388 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
389 if ($event['type'] != 'event') {
393 $item['post-type'] = Item::PT_EVENT;
395 $item['object-type'] = Activity\ObjectType::EVENT;
396 $item['body'] = self::getBBCode($event);
397 $item['event-id'] = $event_id;
399 $item['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
400 $item['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
401 $item['object'] .= '</object>' . "\n";
407 * Create an array with translation strings used for events.
409 * @return array Array with translations strings.
410 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
412 public static function getStrings(): array
414 // First day of the week (0 = Sunday).
415 $firstDay = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'calendar', 'first_day_of_week') ?? 0;
416 $defaultView = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'calendar', 'defaultView') ?? 'month';
419 'firstDay' => $firstDay,
420 'defaultView' => $defaultView,
421 'allday' => DI::l10n()->t('all-day'),
423 'Sun' => DI::l10n()->t('Sun'),
424 'Mon' => DI::l10n()->t('Mon'),
425 'Tue' => DI::l10n()->t('Tue'),
426 'Wed' => DI::l10n()->t('Wed'),
427 'Thu' => DI::l10n()->t('Thu'),
428 'Fri' => DI::l10n()->t('Fri'),
429 'Sat' => DI::l10n()->t('Sat'),
431 'Sunday' => DI::l10n()->t('Sunday'),
432 'Monday' => DI::l10n()->t('Monday'),
433 'Tuesday' => DI::l10n()->t('Tuesday'),
434 'Wednesday' => DI::l10n()->t('Wednesday'),
435 'Thursday' => DI::l10n()->t('Thursday'),
436 'Friday' => DI::l10n()->t('Friday'),
437 'Saturday' => DI::l10n()->t('Saturday'),
439 'Jan' => DI::l10n()->t('Jan'),
440 'Feb' => DI::l10n()->t('Feb'),
441 'Mar' => DI::l10n()->t('Mar'),
442 'Apr' => DI::l10n()->t('Apr'),
443 'May' => DI::l10n()->t('May'),
444 'Jun' => DI::l10n()->t('Jun'),
445 'Jul' => DI::l10n()->t('Jul'),
446 'Aug' => DI::l10n()->t('Aug'),
447 'Sep' => DI::l10n()->t('Sept'),
448 'Oct' => DI::l10n()->t('Oct'),
449 'Nov' => DI::l10n()->t('Nov'),
450 'Dec' => DI::l10n()->t('Dec'),
452 'January' => DI::l10n()->t('January'),
453 'February' => DI::l10n()->t('February'),
454 'March' => DI::l10n()->t('March'),
455 'April' => DI::l10n()->t('April'),
456 'June' => DI::l10n()->t('June'),
457 'July' => DI::l10n()->t('July'),
458 'August' => DI::l10n()->t('August'),
459 'September' => DI::l10n()->t('September'),
460 'October' => DI::l10n()->t('October'),
461 'November' => DI::l10n()->t('November'),
462 'December' => DI::l10n()->t('December'),
464 'today' => DI::l10n()->t('today'),
465 'month' => DI::l10n()->t('month'),
466 'week' => DI::l10n()->t('week'),
467 'day' => DI::l10n()->t('day'),
469 'noevent' => DI::l10n()->t('No events to display'),
471 'dtstart_label' => DI::l10n()->t('Starts:'),
472 'dtend_label' => DI::l10n()->t('Finishes:'),
473 'location_label' => DI::l10n()->t('Location:')
478 * Removes duplicated birthday events.
480 * @param array $dates Array of possibly duplicated events.
481 * @return array Cleaned events.
483 * @todo We should replace this with a separate update function if there is some time left.
485 private static function removeDuplicates(array $dates): array
489 foreach ($dates as $date) {
490 if ($date['type'] == 'birthday') {
491 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
496 return array_values($dates2);
500 * Returns the owner array of a given nickname
501 * Additionally, it can check if the owner array is selectable
503 * @param string $nickname
505 * @return array the owner array
506 * @throws HTTPException\InternalServerErrorException
507 * @throws HTTPException\NotFoundException The given nickname does not exist
508 * @throws HTTPException\UnauthorizedException The access for the given nickname is restricted
510 public static function getOwnerForNickname(string $nickname): array
512 $owner = User::getOwnerDataByNick($nickname);
513 if (empty($owner) || $owner['account_removed'] || $owner['account_expired']) {
514 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
517 if (!DI::userSession()->isAuthenticated() && $owner['hidewall']) {
518 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Access to this profile has been restricted.'));
521 if (!DI::userSession()->isAuthenticated() && !Feature::isEnabled($owner['uid'], 'public_calendar')) {
522 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
529 * Get an event by its event ID. Checks permissions.
531 * @param int $owner_uid The User ID of the owner of the event
532 * @param int $event_id The ID of the event in the event table
533 * @param string|null $nickname a possible nickname to search for instead of the owner uid
534 * @return array Query result
537 public static function getByIdAndUid(int $owner_uid, int $event_id): array
539 // Only allow events if there is a valid owner_id.
540 if ($owner_uid == 0) {
544 // get the permissions
545 $sql_perms = Item::getPermissionsSQLByUserId($owner_uid);
547 // Query for the event by event id
548 $events = DBA::toArray(DBA::p(
549 "SELECT `event`.*, `post-user`.`id` AS `itemid` FROM `event`
550 LEFT JOIN `post-user`
551 ON `post-user`.`event-id` = `event`.`id`
552 AND `post-user`.`uid` = `event`.`uid`
553 WHERE `event`.`id` = ?
554 AND `event`.`uid` = ?
559 if (empty($events)) {
560 throw new HTTPException\NotFoundException(DI::l10n()->t('Event not found.'));
567 * Get all events in a specific time frame.
569 * @param int $owner_uid The User ID of the owner of the events.
570 * @param string|null $start Start time of the timeframe.
571 * @param string|null $finish Finish time of the timeframe.
572 * @param bool|null $ignore Filters ignored events (false: unignored events, true: ignored events, null: all events)
574 * @return array Query results.
575 * @throws HTTPException\NotFoundException
576 * @throws HTTPException\UnauthorizedException
578 public static function getListByDate(int $owner_uid, string $start = null, string $finish = null, ?bool $ignore = false): array
580 // Only allow events if there is a valid owner_id.
581 if ($owner_uid == 0) {
585 // get the permissions
586 $sql_perms = Item::getPermissionsSQLByUserId($owner_uid);
588 if (empty($start) || empty($finish)) {
589 $y = intval(DateTimeFormat::localNow('Y'));
590 $m = intval(DateTimeFormat::localNow('m'));
593 $start = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
595 $dim = Temporal::getDaysInMonth($y, $m);
596 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
600 if ($ignore === true) {
601 $sql_ignore = " AND `event`.`ignore` = 1";
602 } elseif ($ignore === false) {
603 $sql_ignore = " AND `event`.`ignore` = 0";
608 // Query for the event by date.
609 $events = DBA::toArray(DBA::p(
610 "SELECT `event`.*, `post-user`.`id` AS `itemid` FROM `event`
611 LEFT JOIN `post-user`
612 ON `post-user`.`event-id` = `event`.`id`
613 AND `post-user`.`uid` = `event`.`uid`
614 WHERE `event`.`uid` = ?
616 AND (`finish` >= ? OR (`nofinish` AND `start` >= ?))
625 $events = self::removeDuplicates($events);
626 return self::sortByDate($events);
630 * Convert an event in an array which could be used by the event template.
632 * @param array $event Event query array.
633 * @return array Event array for the template.
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
635 * @throws \ImagickException
637 public static function prepareForItem(array $event): array
639 $fmt = DI::l10n()->t('l, F j');
641 $item = Post::selectFirst(['plink', 'author-name', 'author-network', 'author-id', 'author-avatar', 'author-link', 'private', 'uri-id'], ['id' => $event['itemid']]);
643 // Using default values when no item had been found
644 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => '', 'private' => Item::PUBLIC, 'uri-id' => ($event['uri-id'] ?? 0)];
647 $event = array_merge($event, $item);
649 $start = DateTimeFormat::local($event['start'], 'c');
650 $j = DateTimeFormat::local($event['start'], 'j');
651 $day = DateTimeFormat::local($event['start'], $fmt);
652 $day = DI::l10n()->getDay($day);
654 if ($event['nofinish']) {
657 $end = DateTimeFormat::local($event['finish'], 'c');
660 // Show edit and drop actions only if the user is the owner of the event and the event
661 // is a real event (no birthdays).
665 if (DI::userSession()->getLocalUserId() && DI::userSession()->getLocalUserId() == $event['uid'] && $event['type'] == 'event') {
666 $edit = !$event['cid'] ? ['calendar/event/edit/' . $event['id'], DI::l10n()->t('Edit event'), '', ''] : null;
667 $copy = !$event['cid'] ? ['calendar/event/copy/' . $event['id'], DI::l10n()->t('Duplicate event'), '', ''] : null;
668 $drop = ['calendar/api/delete/' . $event['id'], DI::l10n()->t('Delete event'), '', ''];
671 $title = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['summary']));
673 [$title, $_trash] = explode("<br", BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc'])), BBCode::TWITTER_API);
676 $event['author-link'] = Contact::magicLink($event['author-link']);
679 'id' => $event['id'],
690 'html' => self::getHTML($event),
691 'plink' => Item::getPlink($event),
696 * Format event to export format (ical/csv).
698 * @param array $events Query result for events.
699 * @param string $format The output format (ical/csv).
700 * @return string Content according to selected export format.
702 * @todo Implement timezone support
704 private static function formatListForExport(array $events, string $format): string
708 if (!count($events)) {
713 // Format the exported data as a CSV file.
715 $o .= '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
717 foreach ($events as $event) {
718 /// @todo The time / date entries don't include any information about the
719 /// timezone the event is scheduled in :-/
720 $tmp1 = strtotime($event['start']);
721 $tmp2 = strtotime($event['finish']);
722 $time_format = "%H:%M:%S";
723 $date_format = "%Y-%m-%d";
725 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
726 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
727 '", "' . strftime($date_format, $tmp2) .
728 '", "' . strftime($time_format, $tmp2) .
729 '", "' . $event['location'] . '"' . PHP_EOL;
733 // Format the exported data as a ics file.
735 $o = 'BEGIN:VCALENDAR' . PHP_EOL
736 . 'VERSION:2.0' . PHP_EOL
737 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
738 /// @todo include timezone informations in cases were the time is not in UTC
739 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
740 // . 'BEGIN:VTIMEZONE' . PHP_EOL
741 // . 'TZID:' . $timezone . PHP_EOL
742 // . 'END:VTIMEZONE' . PHP_EOL;
743 // TODO instead of PHP_EOL CRLF should be used for long entries
744 // but test your solution against http://icalvalid.cloudapp.net/
745 // also long lines SHOULD be split at 75 characters length
746 foreach ($events as $event) {
747 $o .= 'BEGIN:VEVENT' . PHP_EOL;
748 $o .= 'UID:' . $event['id'] . PHP_EOL;
749 $o .= 'DTSTAMP:' . DateTimeFormat::utc($event['created'], 'Ymd\THis\Z') . PHP_EOL;
751 if ($event['start']) {
752 $o .= 'DTSTART:' . DateTimeFormat::utc($event['start'], 'Ymd\THis\Z') . PHP_EOL;
755 if (!$event['nofinish']) {
756 $o .= 'DTEND:' . DateTimeFormat::utc($event['finish'], 'Ymd\THis\Z') . PHP_EOL;
759 if ($event['summary']) {
760 $tmp = $event['summary'];
761 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
762 $tmp = addcslashes($tmp, ',;');
763 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
766 if ($event['desc']) {
767 $tmp = $event['desc'];
768 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
769 $tmp = addcslashes($tmp, ',;');
770 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
773 if ($event['location']) {
774 $tmp = $event['location'];
775 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
776 $tmp = addcslashes($tmp, ',;');
777 $o .= 'LOCATION:' . $tmp . PHP_EOL;
780 $o .= 'END:VEVENT' . PHP_EOL;
783 $o .= 'END:VCALENDAR' . PHP_EOL;
791 * Get all events for a user ID.
793 * The query for events is done permission sensitive.
794 * If the user is the owner of the calendar they
795 * will get all of their available events.
796 * If the user is only a visitor only the public events will
799 * @param int $uid The user ID.
801 * @return array Query results.
804 private static function getListByUserId(int $uid = 0): array
812 $fields = ['id', 'created', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'];
814 $conditions = ['uid' => $uid, 'cid' => 0];
816 // Does the user who requests happen to be the owner of the events
817 // requested? then show all of your events, otherwise only those that
818 // don't have limitations set in allow_cid and allow_gid.
819 if (DI::userSession()->getLocalUserId() != $uid) {
820 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
823 $events = DBA::select('event', $fields, $conditions);
824 if (DBA::isResult($events)) {
825 $return = DBA::toArray($events);
833 * @param int $uid The user ID.
834 * @param string $format Output format (ical/csv).
835 * @return array With the results:
836 * bool 'success' => True if the processing was successful,<br>
837 * string 'format' => The output format,<br>
838 * string 'extension' => The file extension of the output format,<br>
839 * string 'content' => The formatted output content.<br>
842 * @todo Respect authenticated users with events_by_uid().
844 public static function exportListByUserId(int $uid, string $format = 'ical'): array
848 // Get all events which are owned by a uid (respects permissions).
849 $events = self::getListByUserId($uid);
851 // We have the events that are available for the requestor.
852 // Now format the output according to the requested format.
853 $res = self::formatListForExport($events, $format);
855 // If there are results the precess was successful.
860 // Get the file extension for the format.
875 'success' => $process,
877 'extension' => $file_ext,
885 * Format an item array with event data to HTML.
887 * @param array $item Array with item and event data.
888 * @return string HTML output.
889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
890 * @throws \ImagickException
892 public static function getItemHTML(array $item): string
897 // Set the different time formats.
898 $dformat = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
899 $dformat_short = DI::l10n()->t('D g:i A'); // Fri 8:01 AM.
900 $tformat = DI::l10n()->t('g:i A'); // 8:01 AM.
902 // Convert the time to different formats.
903 $dtstart_dt = DI::l10n()->getDay(DateTimeFormat::local($item['event-start'], $dformat));
904 $dtstart_title = DateTimeFormat::utc($item['event-start'], DateTimeFormat::ATOM);
905 // Format: Jan till Dec.
906 $month_short = DI::l10n()->getDayShort(DateTimeFormat::local($item['event-start'], 'M'));
907 // Format: 1 till 31.
908 $date_short = DateTimeFormat::local($item['event-start'], 'j');
909 $start_time = DateTimeFormat::local($item['event-start'], $tformat);
910 $start_short = DI::l10n()->getDayShort(DateTimeFormat::local($item['event-start'], $dformat_short));
912 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
913 if (!$item['event-nofinish']) {
915 $dtend_dt = DI::l10n()->getDay(DateTimeFormat::local($item['event-finish'], $dformat));
916 $dtend_title = DateTimeFormat::utc($item['event-finish'], DateTimeFormat::ATOM);
917 $end_short = DI::l10n()->getDayShort(DateTimeFormat::utc($item['event-finish'], $dformat_short));
918 $end_time = DateTimeFormat::local($item['event-finish'], $tformat);
919 // Check if start and finish time is at the same day.
920 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
930 // Format the event location.
931 $location = self::locationToArray($item['event-location']);
933 // Construct the profile link (magic-auth).
936 'id' => $item['author-id'],
937 'network' => $item['author-network'],
938 'url' => $item['author-link'],
939 'alias' => $item['author-alias']
941 $profile_link = Contact::magicLinkByContact($author);
943 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
944 $return = Renderer::replaceMacros($tpl, [
945 '$id' => $item['event-id'],
946 '$title' => BBCode::convertForUriId($item['uri-id'], $item['event-summary']),
947 '$dtstart_label' => DI::l10n()->t('Starts:'),
948 '$dtstart_title' => $dtstart_title,
949 '$dtstart_dt' => $dtstart_dt,
950 '$finish' => $finish,
951 '$dtend_label' => DI::l10n()->t('Finishes:'),
952 '$dtend_title' => $dtend_title,
953 '$dtend_dt' => $dtend_dt,
954 '$month_short' => $month_short,
955 '$date_short' => $date_short,
956 '$same_date' => $same_date,
957 '$start_time' => $start_time,
958 '$start_short' => $start_short,
959 '$end_time' => $end_time,
960 '$end_short' => $end_short,
961 '$author_name' => $item['author-name'],
962 '$author_link' => $profile_link,
963 '$author_avatar' => $item['author-avatar'],
964 '$description' => BBCode::convertForUriId($item['uri-id'], $item['event-desc']),
965 '$location_label' => DI::l10n()->t('Location:'),
966 '$show_map_label' => DI::l10n()->t('Show map'),
967 '$hide_map_label' => DI::l10n()->t('Hide map'),
968 '$map_btn_label' => DI::l10n()->t('Show map'),
969 '$location' => $location
976 * Format a string with map bbcode to an array with location data.
978 * Note: The string must only contain location data. A string with no bbcode will be
979 * handled as location name.
981 * @param string $s The string with the bbcode formatted location data.
983 * @return array The array with the location data.
984 * 'name' => The name of the location,<br>
985 * 'address' => The address of the location,<br>
986 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
987 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989 private static function locationToArray(string $s = ''): array
995 $location = ['name' => $s];
997 // Map tag with location name - e.g. [map]Paris[/map].
998 if (strpos($s, '[/map]') !== false) {
999 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
1000 if (intval($found) > 0 && array_key_exists(1, $match)) {
1001 $location['address'] = $match[1];
1002 // Remove the map bbcode from the location name.
1003 $location['name'] = str_replace($match[0], "", $s);
1005 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
1006 } elseif (strpos($s, '[map=') !== false) {
1007 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
1008 if (intval($found) > 0 && array_key_exists(1, $match)) {
1009 $location['coordinates'] = $match[1];
1010 // Remove the map bbcode from the location name.
1011 $location['name'] = str_replace($match[0], "", $s);
1015 $location['name'] = BBCode::toPlaintext($location['name'], false);
1017 // Construct the map HTML.
1018 if (isset($location['address'])) {
1019 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
1020 } elseif (isset($location['coordinates'])) {
1021 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
1028 * Add new birthday event for this person
1030 * @param array $contact Contact array, expects: id, uid, url, name
1031 * @param string $birthday Birthday of the contact
1033 * @throws \Exception
1035 public static function createBirthday(array $contact, string $birthday): bool
1037 // Check for duplicates
1039 'uid' => $contact['uid'],
1040 'cid' => $contact['id'],
1041 'start' => DateTimeFormat::utc($birthday),
1042 'type' => 'birthday'
1044 if (DBA::exists('event', $condition)) {
1049 * Add new birthday event for this person
1051 * summary is just a readable placeholder in case the event is shared
1052 * with others. We will replace it during presentation to our $importer
1053 * to contain a sparkle link and perhaps a photo.
1056 'uid' => $contact['uid'],
1057 'cid' => $contact['id'],
1058 'start' => DateTimeFormat::utc($birthday),
1059 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1060 'summary' => DI::l10n()->t('%s\'s birthday', $contact['name']),
1061 'desc' => DI::l10n()->t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1062 'type' => 'birthday',
1065 // Check if self::store() was success
1066 return (self::store($values) > 0);
1069 public static function setIgnore(int $uid, int $eventId, bool $ignore = true)
1071 DBA::update('event', ['ignore' => $ignore], ['id' => $eventId, 'uid' => $uid]);