3 * @copyright Copyright (C) 2020, Friendica
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)
50 $bd_format = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8 AM.
52 $event_start = DI::l10n()->getDay(
53 !empty($event['adjust']) ?
54 DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
57 if (!empty($event['finish'])) {
58 $event_end = DI::l10n()->getDay(
59 !empty($event['adjust']) ?
60 DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
69 if (!empty($event['summary'])) {
70 $o .= "<h3>" . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . "</h3>";
73 if (!empty($event['desc'])) {
74 $o .= "<div>" . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . "</div>";
77 $o .= "<h4>" . DI::l10n()->t('Starts:') . "</h4><p>" . $event_start . "</p>";
79 if (!$event['nofinish']) {
80 $o .= "<h4>" . DI::l10n()->t('Finishes:') . "</h4><p>" . $event_end . "</p>";
83 if (!empty($event['location'])) {
84 $o .= "<h4>" . DI::l10n()->t('Location:') . "</h4><p>" . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple) . "</p>";
90 $o = '<div class="vevent">' . "\r\n";
92 $o .= '<div class="summary event-summary">' . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . '</div>' . "\r\n";
94 $o .= '<div class="event-start"><span class="event-label">' . DI::l10n()->t('Starts:') . '</span> <span class="dtstart" title="'
95 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
96 . '" >' . $event_start
97 . '</span></div>' . "\r\n";
99 if (!$event['nofinish']) {
100 $o .= '<div class="event-end" ><span class="event-label">' . DI::l10n()->t('Finishes:') . '</span> <span class="dtend" title="'
101 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
103 . '</span></div>' . "\r\n";
106 if (!empty($event['desc'])) {
107 $o .= '<div class="description event-description">' . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . '</div>' . "\r\n";
110 if (!empty($event['location'])) {
111 $o .= '<div class="event-location"><span class="event-label">' . DI::l10n()->t('Location:') . '</span> <span class="location">'
112 . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple)
113 . '</span></div>' . "\r\n";
115 // Include a map of the location if the [map] BBCode is used.
116 if (strpos($event['location'], "[map") !== false) {
117 $map = Map::byLocation($event['location'], $simple);
118 if ($map !== $event['location']) {
124 $o .= '</div>' . "\r\n";
129 * Convert an array with event data to bbcode.
131 * @param array $event Array which contains the event data.
132 * @return string The event as a bbcode formatted string.
134 private static function getBBCode(array $event)
138 if ($event['summary']) {
139 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
142 if ($event['desc']) {
143 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
146 if ($event['start']) {
147 $o .= '[event-start]' . $event['start'] . '[/event-start]';
150 if (($event['finish']) && (!$event['nofinish'])) {
151 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
154 if ($event['location']) {
155 $o .= '[event-location]' . $event['location'] . '[/event-location]';
158 if ($event['adjust']) {
159 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
166 * Extract bbcode formatted event data from a string.
168 * @params: string $s The string which should be parsed for event data.
170 * @return array The array with the event information.
172 public static function fromBBCode($text)
177 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
178 $ev['summary'] = $match[1];
182 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
183 $ev['desc'] = $match[1];
187 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
188 $ev['start'] = $match[1];
192 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
193 $ev['finish'] = $match[1];
197 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
198 $ev['location'] = $match[1];
202 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
203 $ev['adjust'] = $match[1];
206 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
211 public static function sortByDate($event_list)
213 usort($event_list, ['self', 'compareDatesCallback']);
217 private static function compareDatesCallback($event_a, $event_b)
219 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
220 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
222 if ($date_a === $date_b) {
223 return strcasecmp($event_a['desc'], $event_b['desc']);
226 return strcmp($date_a, $date_b);
230 * Delete an event from the event table.
232 * Note: This function does only delete the event from the event table not its
233 * related entry in the item table.
235 * @param int $event_id Event ID.
239 public static function delete($event_id)
241 if ($event_id == 0) {
245 DBA::delete('event', ['id' => $event_id], ['cascade' => false]);
246 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
252 * Store the event in the event table and create an event item in the item table.
254 * @param array $arr Array with event data.
255 * @return int The new event id.
256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258 public static function store($arr)
260 $network = $arr['network'] ?? Protocol::DFRN;
261 $protocol = $arr['protocol'] ?? Conversation::PARCEL_UNKNOWN;
262 $direction = $arr['direction'] ?? Conversation::UNKNOWN;
263 $source = $arr['source'] ?? '';
265 unset($arr['network']);
266 unset($arr['protocol']);
267 unset($arr['direction']);
268 unset($arr['source']);
271 $event['id'] = intval($arr['id'] ?? 0);
272 $event['uid'] = intval($arr['uid'] ?? 0);
273 $event['cid'] = intval($arr['cid'] ?? 0);
274 $event['guid'] = ($arr['guid'] ?? '') ?: System::createUUID();
275 $event['uri'] = ($arr['uri'] ?? '') ?: Item::newURI($event['uid'], $event['guid']);
276 $event['type'] = ($arr['type'] ?? '') ?: 'event';
277 $event['summary'] = $arr['summary'] ?? '';
278 $event['desc'] = $arr['desc'] ?? '';
279 $event['location'] = $arr['location'] ?? '';
280 $event['allow_cid'] = $arr['allow_cid'] ?? '';
281 $event['allow_gid'] = $arr['allow_gid'] ?? '';
282 $event['deny_cid'] = $arr['deny_cid'] ?? '';
283 $event['deny_gid'] = $arr['deny_gid'] ?? '';
284 $event['adjust'] = intval($arr['adjust'] ?? 0);
285 $event['nofinish'] = intval($arr['nofinish'] ?? (!empty($event['start']) && empty($event['finish'])));
287 $event['created'] = DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now');
288 $event['edited'] = DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now');
289 $event['start'] = DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME);
290 $event['finish'] = DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME);
291 if ($event['finish'] < DBA::NULL_DATETIME) {
292 $event['finish'] = DBA::NULL_DATETIME;
294 $private = intval($arr['private'] ?? 0);
296 $conditions = ['uid' => $event['uid']];
298 $conditions['id'] = $event['cid'];
300 $conditions['self'] = true;
303 $contact = DBA::selectFirst('contact', [], $conditions);
304 if (!DBA::isResult($contact)) {
305 Logger::warning('Contact not found', ['condition' => $conditions, 'callstack' => System::callstack(20)]);
308 // Existing event being modified.
310 // has the event actually changed?
311 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
312 if (!DBA::isResult($existing_event) || ($existing_event['edited'] === $event['edited'])) {
314 $item = Post::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
316 return DBA::isResult($item) ? $item['id'] : 0;
320 'edited' => $event['edited'],
321 'start' => $event['start'],
322 'finish' => $event['finish'],
323 'summary' => $event['summary'],
324 'desc' => $event['desc'],
325 'location' => $event['location'],
326 'type' => $event['type'],
327 'adjust' => $event['adjust'],
328 'nofinish' => $event['nofinish'],
331 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
333 $item = Post::selectFirst(['id', 'uri-id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
334 if (DBA::isResult($item)) {
335 $object = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
336 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
337 $object .= '</object>' . "\n";
339 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
340 Item::update($fields, ['id' => $item['id']]);
342 $uriid = $item['uri-id'];
347 Hook::callAll('event_updated', $event['id']);
349 // New event. Store it.
350 DBA::insert('event', $event);
354 // Don't create an item for birthday events
355 if ($event['type'] == 'event') {
356 $event['id'] = DBA::lastInsertId();
360 $item_arr['uid'] = $event['uid'];
361 $item_arr['contact-id'] = $event['cid'];
362 $item_arr['uri'] = $event['uri'];
363 $item_arr['uri-id'] = ItemURI::getIdByURI($event['uri']);
364 $item_arr['guid'] = $event['guid'];
365 $item_arr['plink'] = $arr['plink'] ?? '';
366 $item_arr['post-type'] = Item::PT_EVENT;
367 $item_arr['wall'] = $event['cid'] ? 0 : 1;
368 $item_arr['contact-id'] = $contact['id'];
369 $item_arr['owner-name'] = $contact['name'];
370 $item_arr['owner-link'] = $contact['url'];
371 $item_arr['owner-avatar'] = $contact['thumb'];
372 $item_arr['author-name'] = $contact['name'];
373 $item_arr['author-link'] = $contact['url'];
374 $item_arr['author-avatar'] = $contact['thumb'];
375 $item_arr['title'] = '';
376 $item_arr['allow_cid'] = $event['allow_cid'];
377 $item_arr['allow_gid'] = $event['allow_gid'];
378 $item_arr['deny_cid'] = $event['deny_cid'];
379 $item_arr['deny_gid'] = $event['deny_gid'];
380 $item_arr['private'] = $private;
381 $item_arr['visible'] = 1;
382 $item_arr['verb'] = Activity::POST;
383 $item_arr['object-type'] = Activity\ObjectType::EVENT;
384 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
385 $item_arr['body'] = self::getBBCode($event);
386 $item_arr['event-id'] = $event['id'];
387 $item_arr['network'] = $network;
388 $item_arr['protocol'] = $protocol;
389 $item_arr['direction'] = $direction;
390 $item_arr['source'] = $source;
392 $item_arr['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
393 $item_arr['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
394 $item_arr['object'] .= '</object>' . "\n";
396 if (Item::insert($item_arr)) {
397 $uriid = $item_arr['uri-id'];
401 Hook::callAll("event_created", $event['id']);
408 * Create an array with translation strings used for events.
410 * @return array Array with translations strings.
411 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
413 public static function getStrings()
415 // First day of the week (0 = Sunday).
416 $firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0);
419 "firstDay" => $firstDay,
420 "allday" => DI::l10n()->t("all-day"),
422 "Sun" => DI::l10n()->t("Sun"),
423 "Mon" => DI::l10n()->t("Mon"),
424 "Tue" => DI::l10n()->t("Tue"),
425 "Wed" => DI::l10n()->t("Wed"),
426 "Thu" => DI::l10n()->t("Thu"),
427 "Fri" => DI::l10n()->t("Fri"),
428 "Sat" => DI::l10n()->t("Sat"),
430 "Sunday" => DI::l10n()->t("Sunday"),
431 "Monday" => DI::l10n()->t("Monday"),
432 "Tuesday" => DI::l10n()->t("Tuesday"),
433 "Wednesday" => DI::l10n()->t("Wednesday"),
434 "Thursday" => DI::l10n()->t("Thursday"),
435 "Friday" => DI::l10n()->t("Friday"),
436 "Saturday" => DI::l10n()->t("Saturday"),
438 "Jan" => DI::l10n()->t("Jan"),
439 "Feb" => DI::l10n()->t("Feb"),
440 "Mar" => DI::l10n()->t("Mar"),
441 "Apr" => DI::l10n()->t("Apr"),
442 "May" => DI::l10n()->t("May"),
443 "Jun" => DI::l10n()->t("Jun"),
444 "Jul" => DI::l10n()->t("Jul"),
445 "Aug" => DI::l10n()->t("Aug"),
446 "Sep" => DI::l10n()->t("Sept"),
447 "Oct" => DI::l10n()->t("Oct"),
448 "Nov" => DI::l10n()->t("Nov"),
449 "Dec" => DI::l10n()->t("Dec"),
451 "January" => DI::l10n()->t("January"),
452 "February" => DI::l10n()->t("February"),
453 "March" => DI::l10n()->t("March"),
454 "April" => DI::l10n()->t("April"),
455 "June" => DI::l10n()->t("June"),
456 "July" => DI::l10n()->t("July"),
457 "August" => DI::l10n()->t("August"),
458 "September" => DI::l10n()->t("September"),
459 "October" => DI::l10n()->t("October"),
460 "November" => DI::l10n()->t("November"),
461 "December" => DI::l10n()->t("December"),
463 "today" => DI::l10n()->t("today"),
464 "month" => DI::l10n()->t("month"),
465 "week" => DI::l10n()->t("week"),
466 "day" => DI::l10n()->t("day"),
468 "noevent" => DI::l10n()->t("No events to display"),
470 "dtstart_label" => DI::l10n()->t("Starts:"),
471 "dtend_label" => DI::l10n()->t("Finishes:"),
472 "location_label" => DI::l10n()->t("Location:")
479 * Removes duplicated birthday events.
481 * @param array $dates Array of possibly duplicated events.
482 * @return array Cleaned events.
484 * @todo We should replace this with a separate update function if there is some time left.
486 private static function removeDuplicates(array $dates)
490 foreach ($dates as $date) {
491 if ($date['type'] == 'birthday') {
492 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
497 return array_values($dates2);
501 * Get an event by its event ID.
503 * @param int $owner_uid The User ID of the owner of the event
504 * @param int $event_id The ID of the event in the event table
505 * @param string $sql_extra
506 * @return array Query result
509 public static function getListById($owner_uid, $event_id, $sql_extra = '')
513 // Ownly allow events if there is a valid owner_id.
514 if ($owner_uid == 0) {
518 // Query for the event by event id
519 $events = DBA::toArray(DBA::p("SELECT `event`.*, `post-view`.`id` AS `itemid` FROM `event`
520 LEFT JOIN `post-view` ON `post-view`.`event-id` = `event`.`id` AND `post-view`.`uid` = `event`.`uid`
521 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
522 $owner_uid, $event_id));
524 if (DBA::isResult($events)) {
525 $return = self::removeDuplicates($events);
532 * Get all events in a specific time frame.
534 * @param int $owner_uid The User ID of the owner of the events.
535 * @param array $event_params An associative array with
537 * string 'start' => Start time of the timeframe.
538 * string 'finish' => Finish time of the timeframe.
539 * string 'adjust_start' =>
540 * string 'adjust_finish' =>
542 * @param string $sql_extra Additional sql conditions (e.g. permission request).
544 * @return array Query results.
547 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
551 // Only allow events if there is a valid owner_id.
552 if ($owner_uid == 0) {
556 // Query for the event by date.
557 // @todo Slow query (518 seconds to run), to be optimzed
558 $events = DBA::toArray(DBA::p("SELECT `event`.*, `post-view`.`id` AS `itemid` FROM `event`
559 LEFT JOIN `post-view` ON `post-view`.`event-id` = `event`.`id` AND `post-view`.`uid` = `event`.`uid`
560 WHERE `event`.`uid` = ? AND `event`.`ignore` = ?
561 AND ((NOT `adjust` AND (`finish` >= ? OR (`nofinish` AND `start` >= ?)) AND `start` <= ?)
562 OR (`adjust` AND (`finish` >= ? OR (`nofinish` AND `start` >= ?)) AND `start` <= ?))" . $sql_extra,
563 $owner_uid, $event_params["ignore"],
564 $event_params["start"], $event_params["start"], $event_params["finish"],
565 $event_params["adjust_start"], $event_params["adjust_start"], $event_params["adjust_finish"]));
567 if (DBA::isResult($events)) {
568 $return = self::removeDuplicates($events);
575 * Convert an array query results in an array which could be used by the events template.
577 * @param array $event_result Event query array.
578 * @return array Event array for the template.
579 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
580 * @throws \ImagickException
582 public static function prepareListForTemplate(array $event_result)
587 $fmt = DI::l10n()->t('l, F j');
588 foreach ($event_result as $event) {
589 $item = Post::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
590 if (!DBA::isResult($item)) {
591 // Using default values when no item had been found
592 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
595 $event = array_merge($event, $item);
597 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
598 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
599 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
600 $day = DI::l10n()->getDay($day);
602 if ($event['nofinish']) {
605 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
608 $is_first = ($day !== $last_date);
612 // Show edit and drop actions only if the user is the owner of the event and the event
613 // is a real event (no bithdays).
617 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
618 $edit = !$event['cid'] ? [DI::baseUrl() . '/events/event/' . $event['id'], DI::l10n()->t('Edit event') , '', ''] : null;
619 $copy = !$event['cid'] ? [DI::baseUrl() . '/events/copy/' . $event['id'] , DI::l10n()->t('Duplicate event'), '', ''] : null;
620 $drop = [DI::baseUrl() . '/events/drop/' . $event['id'] , DI::l10n()->t('Delete event') , '', ''];
623 $title = BBCode::convert(Strings::escapeHtml($event['summary']));
625 list($title, $_trash) = explode("<br", BBCode::convert(Strings::escapeHtml($event['desc'])), BBCode::API);
628 $author_link = $event['author-link'];
630 $event['author-link'] = Contact::magicLink($author_link);
632 $html = self::getHTML($event);
633 $event['summary'] = BBCode::convert(Strings::escapeHtml($event['summary']));
634 $event['desc'] = BBCode::convert(Strings::escapeHtml($event['desc']));
635 $event['location'] = BBCode::convert(Strings::escapeHtml($event['location']));
637 'id' => $event['id'],
647 'is_first' => $is_first,
650 'plink' => Item::getPlink($event),
658 * Format event to export format (ical/csv).
660 * @param array $events Query result for events.
661 * @param string $format The output format (ical/csv).
664 * @return string Content according to selected export format.
666 * @todo Implement timezone support
668 private static function formatListForExport(array $events, $format)
672 if (!count($events)) {
677 // Format the exported data as a CSV file.
679 header("Content-type: text/csv");
680 $o .= '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
682 foreach ($events as $event) {
683 /// @todo The time / date entries don't include any information about the
684 /// timezone the event is scheduled in :-/
685 $tmp1 = strtotime($event['start']);
686 $tmp2 = strtotime($event['finish']);
687 $time_format = "%H:%M:%S";
688 $date_format = "%Y-%m-%d";
690 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
691 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
692 '", "' . strftime($date_format, $tmp2) .
693 '", "' . strftime($time_format, $tmp2) .
694 '", "' . $event['location'] . '"' . PHP_EOL;
698 // Format the exported data as a ics file.
700 header("Content-type: text/ics");
701 $o = 'BEGIN:VCALENDAR' . PHP_EOL
702 . 'VERSION:2.0' . PHP_EOL
703 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
704 /// @todo include timezone informations in cases were the time is not in UTC
705 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
706 // . 'BEGIN:VTIMEZONE' . PHP_EOL
707 // . 'TZID:' . $timezone . PHP_EOL
708 // . 'END:VTIMEZONE' . PHP_EOL;
709 // TODO instead of PHP_EOL CRLF should be used for long entries
710 // but test your solution against http://icalvalid.cloudapp.net/
711 // also long lines SHOULD be split at 75 characters length
712 foreach ($events as $event) {
713 if ($event['adjust'] == 1) {
718 $o .= 'BEGIN:VEVENT' . PHP_EOL;
720 if ($event['start']) {
721 $tmp = strtotime($event['start']);
722 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
723 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
726 if (!$event['nofinish']) {
727 $tmp = strtotime($event['finish']);
728 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
729 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
732 if ($event['summary']) {
733 $tmp = $event['summary'];
734 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
735 $tmp = addcslashes($tmp, ',;');
736 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
739 if ($event['desc']) {
740 $tmp = $event['desc'];
741 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
742 $tmp = addcslashes($tmp, ',;');
743 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
746 if ($event['location']) {
747 $tmp = $event['location'];
748 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
749 $tmp = addcslashes($tmp, ',;');
750 $o .= 'LOCATION:' . $tmp . PHP_EOL;
753 $o .= 'END:VEVENT' . PHP_EOL;
757 $o .= 'END:VCALENDAR' . PHP_EOL;
765 * Get all events for a user ID.
767 * The query for events is done permission sensitive.
768 * If the user is the owner of the calendar they
769 * will get all of their available events.
770 * If the user is only a visitor only the public events will
773 * @param int $uid The user ID.
775 * @return array Query results.
778 private static function getListByUserId($uid = 0)
786 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
788 $conditions = ['uid' => $uid, 'cid' => 0];
790 // Does the user who requests happen to be the owner of the events
791 // requested? then show all of your events, otherwise only those that
792 // don't have limitations set in allow_cid and allow_gid.
793 if (local_user() != $uid) {
794 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
797 $events = DBA::select('event', $fields, $conditions);
798 if (DBA::isResult($events)) {
799 $return = DBA::toArray($events);
807 * @param int $uid The user ID.
808 * @param string $format Output format (ical/csv).
809 * @return array With the results:
810 * bool 'success' => True if the processing was successful,<br>
811 * string 'format' => The output format,<br>
812 * string 'extension' => The file extension of the output format,<br>
813 * string 'content' => The formatted output content.<br>
816 * @todo Respect authenticated users with events_by_uid().
818 public static function exportListByUserId($uid, $format = 'ical')
822 // Get all events which are owned by a uid (respects permissions).
823 $events = self::getListByUserId($uid);
825 // We have the events that are available for the requestor.
826 // Now format the output according to the requested format.
827 $res = self::formatListForExport($events, $format);
829 // If there are results the precess was successful.
834 // Get the file extension for the format.
849 'success' => $process,
851 'extension' => $file_ext,
859 * Format an item array with event data to HTML.
861 * @param array $item Array with item and event data.
862 * @return string HTML output.
863 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
864 * @throws \ImagickException
866 public static function getItemHTML(array $item) {
870 // Set the different time formats.
871 $dformat = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
872 $dformat_short = DI::l10n()->t('D g:i A'); // Fri 8:01 AM.
873 $tformat = DI::l10n()->t('g:i A'); // 8:01 AM.
875 // Convert the time to different formats.
876 $dtstart_dt = DI::l10n()->getDay(
877 $item['event-adjust'] ?
878 DateTimeFormat::local($item['event-start'], $dformat)
879 : DateTimeFormat::utc($item['event-start'], $dformat)
881 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
882 // Format: Jan till Dec.
883 $month_short = DI::l10n()->getDayShort(
884 $item['event-adjust'] ?
885 DateTimeFormat::local($item['event-start'], 'M')
886 : DateTimeFormat::utc($item['event-start'], 'M')
888 // Format: 1 till 31.
889 $date_short = $item['event-adjust'] ?
890 DateTimeFormat::local($item['event-start'], 'j')
891 : DateTimeFormat::utc($item['event-start'], 'j');
892 $start_time = $item['event-adjust'] ?
893 DateTimeFormat::local($item['event-start'], $tformat)
894 : DateTimeFormat::utc($item['event-start'], $tformat);
895 $start_short = DI::l10n()->getDayShort(
896 $item['event-adjust'] ?
897 DateTimeFormat::local($item['event-start'], $dformat_short)
898 : DateTimeFormat::utc($item['event-start'], $dformat_short)
901 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
902 if (!$item['event-nofinish']) {
904 $dtend_dt = DI::l10n()->getDay(
905 $item['event-adjust'] ?
906 DateTimeFormat::local($item['event-finish'], $dformat)
907 : DateTimeFormat::utc($item['event-finish'], $dformat)
909 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
910 $end_short = DI::l10n()->getDayShort(
911 $item['event-adjust'] ?
912 DateTimeFormat::local($item['event-finish'], $dformat_short)
913 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
915 $end_time = $item['event-adjust'] ?
916 DateTimeFormat::local($item['event-finish'], $tformat)
917 : DateTimeFormat::utc($item['event-finish'], $tformat);
918 // Check if start and finish time is at the same day.
919 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
929 // Format the event location.
930 $location = self::locationToArray($item['event-location']);
932 // Construct the profile link (magic-auth).
933 $profile_link = Contact::magicLinkById($item['author-id']);
935 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
936 $return = Renderer::replaceMacros($tpl, [
937 '$id' => $item['event-id'],
938 '$title' => BBCode::convert($item['event-summary']),
939 '$dtstart_label' => DI::l10n()->t('Starts:'),
940 '$dtstart_title' => $dtstart_title,
941 '$dtstart_dt' => $dtstart_dt,
942 '$finish' => $finish,
943 '$dtend_label' => DI::l10n()->t('Finishes:'),
944 '$dtend_title' => $dtend_title,
945 '$dtend_dt' => $dtend_dt,
946 '$month_short' => $month_short,
947 '$date_short' => $date_short,
948 '$same_date' => $same_date,
949 '$start_time' => $start_time,
950 '$start_short' => $start_short,
951 '$end_time' => $end_time,
952 '$end_short' => $end_short,
953 '$author_name' => $item['author-name'],
954 '$author_link' => $profile_link,
955 '$author_avatar' => $item['author-avatar'],
956 '$description' => BBCode::convert($item['event-desc']),
957 '$location_label' => DI::l10n()->t('Location:'),
958 '$show_map_label' => DI::l10n()->t('Show map'),
959 '$hide_map_label' => DI::l10n()->t('Hide map'),
960 '$map_btn_label' => DI::l10n()->t('Show map'),
961 '$location' => $location
968 * Format a string with map bbcode to an array with location data.
970 * Note: The string must only contain location data. A string with no bbcode will be
971 * handled as location name.
973 * @param string $s The string with the bbcode formatted location data.
975 * @return array The array with the location data.
976 * 'name' => The name of the location,<br>
977 * 'address' => The address of the location,<br>
978 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
981 private static function locationToArray($s = '') {
986 $location = ['name' => $s];
988 // Map tag with location name - e.g. [map]Paris[/map].
989 if (strpos($s, '[/map]') !== false) {
990 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
991 if (intval($found) > 0 && array_key_exists(1, $match)) {
992 $location['address'] = $match[1];
993 // Remove the map bbcode from the location name.
994 $location['name'] = str_replace($match[0], "", $s);
996 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
997 } elseif (strpos($s, '[map=') !== false) {
998 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
999 if (intval($found) > 0 && array_key_exists(1, $match)) {
1000 $location['coordinates'] = $match[1];
1001 // Remove the map bbcode from the location name.
1002 $location['name'] = str_replace($match[0], "", $s);
1006 $location['name'] = BBCode::convert($location['name']);
1008 // Construct the map HTML.
1009 if (isset($location['address'])) {
1010 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
1011 } elseif (isset($location['coordinates'])) {
1012 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
1019 * Add new birthday event for this person
1021 * @param array $contact Contact array, expects: id, uid, url, name
1022 * @param string $birthday Birthday of the contact
1024 * @throws \Exception
1026 public static function createBirthday($contact, $birthday)
1028 // Check for duplicates
1030 'uid' => $contact['uid'],
1031 'cid' => $contact['id'],
1032 'start' => DateTimeFormat::utc($birthday),
1033 'type' => 'birthday'
1035 if (DBA::exists('event', $condition)) {
1040 * Add new birthday event for this person
1042 * summary is just a readable placeholder in case the event is shared
1043 * with others. We will replace it during presentation to our $importer
1044 * to contain a sparkle link and perhaps a photo.
1047 'uid' => $contact['uid'],
1048 'cid' => $contact['id'],
1049 'start' => DateTimeFormat::utc($birthday),
1050 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1051 'summary' => DI::l10n()->t('%s\'s birthday', $contact['name']),
1052 'desc' => DI::l10n()->t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1053 'type' => 'birthday',
1057 self::store($values);