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\System;
30 use Friendica\Database\DBA;
32 use Friendica\Protocol\Activity;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Map;
35 use Friendica\Util\Strings;
36 use Friendica\Util\XML;
39 * functions for interacting with the event database table
44 public static function getHTML(array $event, $simple = false, $uriid = 0)
50 $uriid = $event['uri-id'] ?? $uriid;
52 $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)
54 $event_start = DI::l10n()->getDay(DateTimeFormat::local($event['start'], $bd_format));
56 if (!empty($event['finish'])) {
57 $event_end = DI::l10n()->getDay(DateTimeFormat::local($event['finish'], $bd_format));
65 if (!empty($event['summary'])) {
66 $o .= "<h3>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['summary']), $simple) . "</h3>";
69 if (!empty($event['desc'])) {
70 $o .= "<div>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['desc']), $simple) . "</div>";
73 $o .= "<h4>" . DI::l10n()->t('Starts:') . "</h4><p>" . $event_start . "</p>";
75 if (!$event['nofinish']) {
76 $o .= "<h4>" . DI::l10n()->t('Finishes:') . "</h4><p>" . $event_end . "</p>";
79 if (!empty($event['location'])) {
80 $o .= "<h4>" . DI::l10n()->t('Location:') . "</h4><p>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['location']), $simple) . "</p>";
86 $o = '<div class="vevent">' . "\r\n";
88 $o .= '<div class="summary event-summary">' . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['summary']), $simple) . '</div>' . "\r\n";
90 $o .= '<div class="event-start"><span class="event-label">' . DI::l10n()->t('Starts:') . '</span> <span class="dtstart" title="'
91 . DateTimeFormat::local($event['start'], DateTimeFormat::ATOM)
92 . '" >' . $event_start
93 . '</span></div>' . "\r\n";
95 if (!$event['nofinish']) {
96 $o .= '<div class="event-end" ><span class="event-label">' . DI::l10n()->t('Finishes:') . '</span> <span class="dtend" title="'
97 . DateTimeFormat::local($event['finish'], DateTimeFormat::ATOM)
99 . '</span></div>' . "\r\n";
102 if (!empty($event['desc'])) {
103 $o .= '<div class="description event-description">' . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['desc']), $simple) . '</div>' . "\r\n";
106 if (!empty($event['location'])) {
107 $o .= '<div class="event-location"><span class="event-label">' . DI::l10n()->t('Location:') . '</span> <span class="location">'
108 . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['location']), $simple)
109 . '</span></div>' . "\r\n";
111 // Include a map of the location if the [map] BBCode is used.
112 if (strpos($event['location'], "[map") !== false) {
113 $map = Map::byLocation($event['location'], $simple);
114 if ($map !== $event['location']) {
120 $o .= '</div>' . "\r\n";
125 * Convert an array with event data to bbcode.
127 * @param array $event Array which contains the event data.
128 * @return string The event as a bbcode formatted string.
130 private static function getBBCode(array $event)
134 if ($event['summary']) {
135 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
138 if ($event['desc']) {
139 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
142 if ($event['start']) {
143 $o .= '[event-start]' . $event['start'] . '[/event-start]';
146 if (($event['finish']) && (!$event['nofinish'])) {
147 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
150 if ($event['location']) {
151 $o .= '[event-location]' . $event['location'] . '[/event-location]';
158 * Extract bbcode formatted event data from a string.
160 * @params: string $s The string which should be parsed for event data.
162 * @return array The array with the event information.
164 public static function fromBBCode($text)
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($event_list)
200 usort($event_list, ['self', 'compareDatesCallback']);
204 private static function compareDatesCallback($event_a, $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($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($arr)
248 $event['id'] = intval($arr['id'] ?? 0);
249 $event['uid'] = intval($arr['uid'] ?? 0);
250 $event['cid'] = intval($arr['cid'] ?? 0);
251 $event['guid'] = ($arr['guid'] ?? '') ?: System::createUUID();
252 $event['uri'] = ($arr['uri'] ?? '') ?: Item::newURI($event['uid'], $event['guid']);
253 $event['uri-id'] = ItemURI::insert(['uri' => $event['uri'], 'guid' => $event['guid']]);
254 $event['type'] = ($arr['type'] ?? '') ?: 'event';
255 $event['summary'] = $arr['summary'] ?? '';
256 $event['desc'] = $arr['desc'] ?? '';
257 $event['location'] = $arr['location'] ?? '';
258 $event['allow_cid'] = $arr['allow_cid'] ?? '';
259 $event['allow_gid'] = $arr['allow_gid'] ?? '';
260 $event['deny_cid'] = $arr['deny_cid'] ?? '';
261 $event['deny_gid'] = $arr['deny_gid'] ?? '';
262 $event['nofinish'] = intval($arr['nofinish'] ?? (!empty($event['start']) && empty($event['finish'])));
264 $event['created'] = DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now');
265 $event['edited'] = DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now');
266 $event['start'] = DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME);
267 $event['finish'] = DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME);
268 if ($event['finish'] < DBA::NULL_DATETIME) {
269 $event['finish'] = DBA::NULL_DATETIME;
272 // Existing event being modified.
274 // has the event actually changed?
275 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
276 if (!DBA::isResult($existing_event)) {
280 if ($existing_event['edited'] === $event['edited']) {
285 'edited' => $event['edited'],
286 'start' => $event['start'],
287 'finish' => $event['finish'],
288 'summary' => $event['summary'],
289 'desc' => $event['desc'],
290 'location' => $event['location'],
291 'type' => $event['type'],
292 'nofinish' => $event['nofinish'],
295 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
297 $item = Post::selectFirst(['id', 'uri-id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
298 if (DBA::isResult($item)) {
299 $object = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
300 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
301 $object .= '</object>' . "\n";
303 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
304 Item::update($fields, ['id' => $item['id']]);
307 Hook::callAll('event_updated', $event['id']);
309 // New event. Store it.
310 DBA::insert('event', $event);
312 $event['id'] = DBA::lastInsertId();
314 Hook::callAll("event_created", $event['id']);
320 public static function getItemArrayForId(int $event_id, array $item = []):array
322 if (empty($event_id)) {
326 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
327 if ($event['type'] != 'event') {
332 $conditions = ['id' => $event['cid']];
334 $conditions = ['uid' => $event['uid'], 'self' => true];
337 $contact = DBA::selectFirst('contact', [], $conditions);
339 $event['id'] = $event_id;
341 $item['uid'] = $event['uid'];
342 $item['contact-id'] = $event['cid'];
343 $item['uri'] = $event['uri'];
344 $item['uri-id'] = ItemURI::getIdByURI($event['uri']);
345 $item['guid'] = $event['guid'];
346 $item['plink'] = $arr['plink'] ?? '';
347 $item['post-type'] = Item::PT_EVENT;
348 $item['wall'] = $event['cid'] ? 0 : 1;
349 $item['contact-id'] = $contact['id'];
350 $item['owner-name'] = $contact['name'];
351 $item['owner-link'] = $contact['url'];
352 $item['owner-avatar'] = $contact['thumb'];
353 $item['author-name'] = $contact['name'];
354 $item['author-link'] = $contact['url'];
355 $item['author-avatar'] = $contact['thumb'];
357 $item['allow_cid'] = $event['allow_cid'];
358 $item['allow_gid'] = $event['allow_gid'];
359 $item['deny_cid'] = $event['deny_cid'];
360 $item['deny_gid'] = $event['deny_gid'];
361 $item['private'] = intval($event['private'] ?? 0);
362 $item['visible'] = 1;
363 $item['verb'] = Activity::POST;
364 $item['object-type'] = Activity\ObjectType::EVENT;
365 $item['post-type'] = Item::PT_EVENT;
366 $item['origin'] = $event['cid'] === 0 ? 1 : 0;
367 $item['body'] = self::getBBCode($event);
368 $item['event-id'] = $event['id'];
370 $item['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
371 $item['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
372 $item['object'] .= '</object>' . "\n";
377 public static function getItemArrayForImportedId(int $event_id, array $item = []):array
379 if (empty($event_id)) {
383 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
384 if ($event['type'] != 'event') {
388 $item['post-type'] = Item::PT_EVENT;
390 $item['object-type'] = Activity\ObjectType::EVENT;
391 $item['body'] = self::getBBCode($event);
392 $item['event-id'] = $event_id;
394 $item['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
395 $item['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
396 $item['object'] .= '</object>' . "\n";
402 * Create an array with translation strings used for events.
404 * @return array Array with translations strings.
405 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
407 public static function getStrings()
409 // First day of the week (0 = Sunday).
410 $firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0);
413 "firstDay" => $firstDay,
414 "allday" => DI::l10n()->t("all-day"),
416 "Sun" => DI::l10n()->t("Sun"),
417 "Mon" => DI::l10n()->t("Mon"),
418 "Tue" => DI::l10n()->t("Tue"),
419 "Wed" => DI::l10n()->t("Wed"),
420 "Thu" => DI::l10n()->t("Thu"),
421 "Fri" => DI::l10n()->t("Fri"),
422 "Sat" => DI::l10n()->t("Sat"),
424 "Sunday" => DI::l10n()->t("Sunday"),
425 "Monday" => DI::l10n()->t("Monday"),
426 "Tuesday" => DI::l10n()->t("Tuesday"),
427 "Wednesday" => DI::l10n()->t("Wednesday"),
428 "Thursday" => DI::l10n()->t("Thursday"),
429 "Friday" => DI::l10n()->t("Friday"),
430 "Saturday" => DI::l10n()->t("Saturday"),
432 "Jan" => DI::l10n()->t("Jan"),
433 "Feb" => DI::l10n()->t("Feb"),
434 "Mar" => DI::l10n()->t("Mar"),
435 "Apr" => DI::l10n()->t("Apr"),
436 "May" => DI::l10n()->t("May"),
437 "Jun" => DI::l10n()->t("Jun"),
438 "Jul" => DI::l10n()->t("Jul"),
439 "Aug" => DI::l10n()->t("Aug"),
440 "Sep" => DI::l10n()->t("Sept"),
441 "Oct" => DI::l10n()->t("Oct"),
442 "Nov" => DI::l10n()->t("Nov"),
443 "Dec" => DI::l10n()->t("Dec"),
445 "January" => DI::l10n()->t("January"),
446 "February" => DI::l10n()->t("February"),
447 "March" => DI::l10n()->t("March"),
448 "April" => DI::l10n()->t("April"),
449 "June" => DI::l10n()->t("June"),
450 "July" => DI::l10n()->t("July"),
451 "August" => DI::l10n()->t("August"),
452 "September" => DI::l10n()->t("September"),
453 "October" => DI::l10n()->t("October"),
454 "November" => DI::l10n()->t("November"),
455 "December" => DI::l10n()->t("December"),
457 "today" => DI::l10n()->t("today"),
458 "month" => DI::l10n()->t("month"),
459 "week" => DI::l10n()->t("week"),
460 "day" => DI::l10n()->t("day"),
462 "noevent" => DI::l10n()->t("No events to display"),
464 "dtstart_label" => DI::l10n()->t("Starts:"),
465 "dtend_label" => DI::l10n()->t("Finishes:"),
466 "location_label" => DI::l10n()->t("Location:")
473 * Removes duplicated birthday events.
475 * @param array $dates Array of possibly duplicated events.
476 * @return array Cleaned events.
478 * @todo We should replace this with a separate update function if there is some time left.
480 private static function removeDuplicates(array $dates)
484 foreach ($dates as $date) {
485 if ($date['type'] == 'birthday') {
486 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
491 return array_values($dates2);
495 * Get an event by its event ID.
497 * @param int $owner_uid The User ID of the owner of the event
498 * @param int $event_id The ID of the event in the event table
499 * @param string $sql_extra
500 * @return array Query result
503 public static function getListById($owner_uid, $event_id, $sql_extra = '')
507 // Ownly allow events if there is a valid owner_id.
508 if ($owner_uid == 0) {
512 // Query for the event by event id
513 $events = DBA::toArray(DBA::p("SELECT `event`.*, `post-user`.`id` AS `itemid` FROM `event`
514 LEFT JOIN `post-user` ON `post-user`.`event-id` = `event`.`id` AND `post-user`.`uid` = `event`.`uid`
515 WHERE `event`.`uid` = ? AND `event`.`id` = ? $sql_extra",
516 $owner_uid, $event_id));
518 if (DBA::isResult($events)) {
519 $return = self::removeDuplicates($events);
526 * Get all events in a specific time frame.
528 * @param int $owner_uid The User ID of the owner of the events.
529 * @param array $event_params An associative array with
531 * string 'start' => Start time of the timeframe.
532 * string 'finish' => Finish time of the timeframe.
534 * @param string $sql_extra Additional sql conditions (e.g. permission request).
536 * @return array Query results.
539 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
543 // Only allow events if there is a valid owner_id.
544 if ($owner_uid == 0) {
548 // Query for the event by date.
549 $events = DBA::toArray(DBA::p("SELECT `event`.*, `post-user`.`id` AS `itemid` FROM `event`
550 LEFT JOIN `post-user` ON `post-user`.`event-id` = `event`.`id` AND `post-user`.`uid` = `event`.`uid`
551 WHERE `event`.`uid` = ? AND `event`.`ignore` = ?
552 AND (`finish` >= ? OR (`nofinish` AND `start` >= ?)) AND `start` <= ?
554 $owner_uid, $event_params['ignore'],
555 $event_params['start'], $event_params['start'], $event_params['finish']
558 if (DBA::isResult($events)) {
559 $return = self::removeDuplicates($events);
566 * Convert an array query results in an array which could be used by the events template.
568 * @param array $event_result Event query array.
569 * @return array Event array for the template.
570 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
571 * @throws \ImagickException
573 public static function prepareListForTemplate(array $event_result)
578 $fmt = DI::l10n()->t('l, F j');
579 foreach ($event_result as $event) {
580 $item = Post::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link', 'private', 'uri-id'], ['id' => $event['itemid']]);
581 if (!DBA::isResult($item)) {
582 // Using default values when no item had been found
583 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => '', 'private' => Item::PUBLIC, 'uri-id' => ($event['uri-id'] ?? 0)];
586 $event = array_merge($event, $item);
588 $start = DateTimeFormat::local($event['start'], 'c');
589 $j = DateTimeFormat::local($event['start'], 'j');
590 $day = DateTimeFormat::local($event['start'], $fmt);
591 $day = DI::l10n()->getDay($day);
593 if ($event['nofinish']) {
596 $end = DateTimeFormat::local($event['finish'], 'c');
599 $is_first = ($day !== $last_date);
603 // Show edit and drop actions only if the user is the owner of the event and the event
604 // is a real event (no bithdays).
608 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
609 $edit = !$event['cid'] ? [DI::baseUrl() . '/events/event/' . $event['id'], DI::l10n()->t('Edit event') , '', ''] : null;
610 $copy = !$event['cid'] ? [DI::baseUrl() . '/events/copy/' . $event['id'] , DI::l10n()->t('Duplicate event'), '', ''] : null;
611 $drop = [DI::baseUrl() . '/events/drop/' . $event['id'] , DI::l10n()->t('Delete event') , '', ''];
614 $title = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['summary']));
616 list($title, $_trash) = explode("<br", BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc'])), BBCode::API);
619 $author_link = $event['author-link'];
621 $event['author-link'] = Contact::magicLink($author_link);
623 $html = self::getHTML($event);
624 $event['summary'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['summary']));
625 $event['desc'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc']));
626 $event['location'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['location']));
628 'id' => $event['id'],
638 'is_first' => $is_first,
641 'plink' => Item::getPlink($event),
649 * Format event to export format (ical/csv).
651 * @param array $events Query result for events.
652 * @param string $format The output format (ical/csv).
655 * @return string Content according to selected export format.
657 * @todo Implement timezone support
659 private static function formatListForExport(array $events, $format)
663 if (!count($events)) {
668 // Format the exported data as a CSV file.
670 header("Content-type: text/csv");
671 $o .= '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
673 foreach ($events as $event) {
674 /// @todo The time / date entries don't include any information about the
675 /// timezone the event is scheduled in :-/
676 $tmp1 = strtotime($event['start']);
677 $tmp2 = strtotime($event['finish']);
678 $time_format = "%H:%M:%S";
679 $date_format = "%Y-%m-%d";
681 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
682 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
683 '", "' . strftime($date_format, $tmp2) .
684 '", "' . strftime($time_format, $tmp2) .
685 '", "' . $event['location'] . '"' . PHP_EOL;
689 // Format the exported data as a ics file.
691 header("Content-type: text/ics");
692 $o = 'BEGIN:VCALENDAR' . PHP_EOL
693 . 'VERSION:2.0' . PHP_EOL
694 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
695 /// @todo include timezone informations in cases were the time is not in UTC
696 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
697 // . 'BEGIN:VTIMEZONE' . PHP_EOL
698 // . 'TZID:' . $timezone . PHP_EOL
699 // . 'END:VTIMEZONE' . PHP_EOL;
700 // TODO instead of PHP_EOL CRLF should be used for long entries
701 // but test your solution against http://icalvalid.cloudapp.net/
702 // also long lines SHOULD be split at 75 characters length
703 foreach ($events as $event) {
704 $o .= 'BEGIN:VEVENT' . PHP_EOL;
706 if ($event['start']) {
707 $o .= 'DTSTART:' . DateTimeFormat::utc($event['start'], 'Ymd\THis\Z') . PHP_EOL;
710 if (!$event['nofinish']) {
711 $o .= 'DTEND:' . DateTimeFormat::utc($event['finish'], 'Ymd\THis\Z') . PHP_EOL;
714 if ($event['summary']) {
715 $tmp = $event['summary'];
716 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
717 $tmp = addcslashes($tmp, ',;');
718 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
721 if ($event['desc']) {
722 $tmp = $event['desc'];
723 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
724 $tmp = addcslashes($tmp, ',;');
725 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
728 if ($event['location']) {
729 $tmp = $event['location'];
730 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
731 $tmp = addcslashes($tmp, ',;');
732 $o .= 'LOCATION:' . $tmp . PHP_EOL;
735 $o .= 'END:VEVENT' . PHP_EOL;
739 $o .= 'END:VCALENDAR' . PHP_EOL;
747 * Get all events for a user ID.
749 * The query for events is done permission sensitive.
750 * If the user is the owner of the calendar they
751 * will get all of their available events.
752 * If the user is only a visitor only the public events will
755 * @param int $uid The user ID.
757 * @return array Query results.
760 private static function getListByUserId($uid = 0)
768 $fields = ['start', 'finish', 'summary', 'desc', 'location', 'nofinish'];
770 $conditions = ['uid' => $uid, 'cid' => 0];
772 // Does the user who requests happen to be the owner of the events
773 // requested? then show all of your events, otherwise only those that
774 // don't have limitations set in allow_cid and allow_gid.
775 if (local_user() != $uid) {
776 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
779 $events = DBA::select('event', $fields, $conditions);
780 if (DBA::isResult($events)) {
781 $return = DBA::toArray($events);
789 * @param int $uid The user ID.
790 * @param string $format Output format (ical/csv).
791 * @return array With the results:
792 * bool 'success' => True if the processing was successful,<br>
793 * string 'format' => The output format,<br>
794 * string 'extension' => The file extension of the output format,<br>
795 * string 'content' => The formatted output content.<br>
798 * @todo Respect authenticated users with events_by_uid().
800 public static function exportListByUserId($uid, $format = 'ical')
804 // Get all events which are owned by a uid (respects permissions).
805 $events = self::getListByUserId($uid);
807 // We have the events that are available for the requestor.
808 // Now format the output according to the requested format.
809 $res = self::formatListForExport($events, $format);
811 // If there are results the precess was successful.
816 // Get the file extension for the format.
831 'success' => $process,
833 'extension' => $file_ext,
841 * Format an item array with event data to HTML.
843 * @param array $item Array with item and event data.
844 * @return string HTML output.
845 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
846 * @throws \ImagickException
848 public static function getItemHTML(array $item) {
852 // Set the different time formats.
853 $dformat = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
854 $dformat_short = DI::l10n()->t('D g:i A'); // Fri 8:01 AM.
855 $tformat = DI::l10n()->t('g:i A'); // 8:01 AM.
857 // Convert the time to different formats.
858 $dtstart_dt = DI::l10n()->getDay(DateTimeFormat::local($item['event-start'], $dformat));
859 $dtstart_title = DateTimeFormat::utc($item['event-start'], DateTimeFormat::ATOM);
860 // Format: Jan till Dec.
861 $month_short = DI::l10n()->getDayShort(DateTimeFormat::local($item['event-start'], 'M'));
862 // Format: 1 till 31.
863 $date_short = DateTimeFormat::local($item['event-start'], 'j');
864 $start_time = DateTimeFormat::local($item['event-start'], $tformat);
865 $start_short = DI::l10n()->getDayShort(DateTimeFormat::local($item['event-start'], $dformat_short));
867 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
868 if (!$item['event-nofinish']) {
870 $dtend_dt = DI::l10n()->getDay(DateTimeFormat::local($item['event-finish'], $dformat));
871 $dtend_title = DateTimeFormat::utc($item['event-finish'], DateTimeFormat::ATOM);
872 $end_short = DI::l10n()->getDayShort(DateTimeFormat::utc($item['event-finish'], $dformat_short));
873 $end_time = DateTimeFormat::local($item['event-finish'], $tformat);
874 // Check if start and finish time is at the same day.
875 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
885 // Format the event location.
886 $location = self::locationToArray($item['event-location']);
888 // Construct the profile link (magic-auth).
889 $author = ['uid' => 0, 'id' => $item['author-id'],
890 'network' => $item['author-network'], 'url' => $item['author-link']];
891 $profile_link = Contact::magicLinkByContact($author);
893 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
894 $return = Renderer::replaceMacros($tpl, [
895 '$id' => $item['event-id'],
896 '$title' => BBCode::convertForUriId($item['uri-id'], $item['event-summary']),
897 '$dtstart_label' => DI::l10n()->t('Starts:'),
898 '$dtstart_title' => $dtstart_title,
899 '$dtstart_dt' => $dtstart_dt,
900 '$finish' => $finish,
901 '$dtend_label' => DI::l10n()->t('Finishes:'),
902 '$dtend_title' => $dtend_title,
903 '$dtend_dt' => $dtend_dt,
904 '$month_short' => $month_short,
905 '$date_short' => $date_short,
906 '$same_date' => $same_date,
907 '$start_time' => $start_time,
908 '$start_short' => $start_short,
909 '$end_time' => $end_time,
910 '$end_short' => $end_short,
911 '$author_name' => $item['author-name'],
912 '$author_link' => $profile_link,
913 '$author_avatar' => $item['author-avatar'],
914 '$description' => BBCode::convertForUriId($item['uri-id'], $item['event-desc']),
915 '$location_label' => DI::l10n()->t('Location:'),
916 '$show_map_label' => DI::l10n()->t('Show map'),
917 '$hide_map_label' => DI::l10n()->t('Hide map'),
918 '$map_btn_label' => DI::l10n()->t('Show map'),
919 '$location' => $location
926 * Format a string with map bbcode to an array with location data.
928 * Note: The string must only contain location data. A string with no bbcode will be
929 * handled as location name.
931 * @param string $s The string with the bbcode formatted location data.
933 * @return array The array with the location data.
934 * 'name' => The name of the location,<br>
935 * 'address' => The address of the location,<br>
936 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
937 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
939 private static function locationToArray($s = '') {
944 $location = ['name' => $s];
946 // Map tag with location name - e.g. [map]Paris[/map].
947 if (strpos($s, '[/map]') !== false) {
948 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
949 if (intval($found) > 0 && array_key_exists(1, $match)) {
950 $location['address'] = $match[1];
951 // Remove the map bbcode from the location name.
952 $location['name'] = str_replace($match[0], "", $s);
954 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
955 } elseif (strpos($s, '[map=') !== false) {
956 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
957 if (intval($found) > 0 && array_key_exists(1, $match)) {
958 $location['coordinates'] = $match[1];
959 // Remove the map bbcode from the location name.
960 $location['name'] = str_replace($match[0], "", $s);
964 $location['name'] = BBCode::convert($location['name']);
966 // Construct the map HTML.
967 if (isset($location['address'])) {
968 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
969 } elseif (isset($location['coordinates'])) {
970 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
977 * Add new birthday event for this person
979 * @param array $contact Contact array, expects: id, uid, url, name
980 * @param string $birthday Birthday of the contact
984 public static function createBirthday($contact, $birthday)
986 // Check for duplicates
988 'uid' => $contact['uid'],
989 'cid' => $contact['id'],
990 'start' => DateTimeFormat::utc($birthday),
993 if (DBA::exists('event', $condition)) {
998 * Add new birthday event for this person
1000 * summary is just a readable placeholder in case the event is shared
1001 * with others. We will replace it during presentation to our $importer
1002 * to contain a sparkle link and perhaps a photo.
1005 'uid' => $contact['uid'],
1006 'cid' => $contact['id'],
1007 'start' => DateTimeFormat::utc($birthday),
1008 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1009 'summary' => DI::l10n()->t('%s\'s birthday', $contact['name']),
1010 'desc' => DI::l10n()->t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1011 'type' => 'birthday',
1014 self::store($values);