3 * @copyright Copyright (C) 2010-2021, 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'); // Friday January 18, 2011 @ 8 AM.
54 $event_start = DI::l10n()->getDay(
55 !empty($event['adjust']) ?
56 DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
59 if (!empty($event['finish'])) {
60 $event_end = DI::l10n()->getDay(
61 !empty($event['adjust']) ?
62 DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
71 if (!empty($event['summary'])) {
72 $o .= "<h3>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['summary']), $simple) . "</h3>";
75 if (!empty($event['desc'])) {
76 $o .= "<div>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['desc']), $simple) . "</div>";
79 $o .= "<h4>" . DI::l10n()->t('Starts:') . "</h4><p>" . $event_start . "</p>";
81 if (!$event['nofinish']) {
82 $o .= "<h4>" . DI::l10n()->t('Finishes:') . "</h4><p>" . $event_end . "</p>";
85 if (!empty($event['location'])) {
86 $o .= "<h4>" . DI::l10n()->t('Location:') . "</h4><p>" . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['location']), $simple) . "</p>";
92 $o = '<div class="vevent">' . "\r\n";
94 $o .= '<div class="summary event-summary">' . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['summary']), $simple) . '</div>' . "\r\n";
96 $o .= '<div class="event-start"><span class="event-label">' . DI::l10n()->t('Starts:') . '</span> <span class="dtstart" title="'
97 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
98 . '" >' . $event_start
99 . '</span></div>' . "\r\n";
101 if (!$event['nofinish']) {
102 $o .= '<div class="event-end" ><span class="event-label">' . DI::l10n()->t('Finishes:') . '</span> <span class="dtend" title="'
103 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
105 . '</span></div>' . "\r\n";
108 if (!empty($event['desc'])) {
109 $o .= '<div class="description event-description">' . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['desc']), $simple) . '</div>' . "\r\n";
112 if (!empty($event['location'])) {
113 $o .= '<div class="event-location"><span class="event-label">' . DI::l10n()->t('Location:') . '</span> <span class="location">'
114 . BBCode::convertForUriId($uriid, Strings::escapeHtml($event['location']), $simple)
115 . '</span></div>' . "\r\n";
117 // Include a map of the location if the [map] BBCode is used.
118 if (strpos($event['location'], "[map") !== false) {
119 $map = Map::byLocation($event['location'], $simple);
120 if ($map !== $event['location']) {
126 $o .= '</div>' . "\r\n";
131 * Convert an array with event data to bbcode.
133 * @param array $event Array which contains the event data.
134 * @return string The event as a bbcode formatted string.
136 private static function getBBCode(array $event)
140 if ($event['summary']) {
141 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
144 if ($event['desc']) {
145 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
148 if ($event['start']) {
149 $o .= '[event-start]' . $event['start'] . '[/event-start]';
152 if (($event['finish']) && (!$event['nofinish'])) {
153 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
156 if ($event['location']) {
157 $o .= '[event-location]' . $event['location'] . '[/event-location]';
160 if ($event['adjust']) {
161 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
168 * Extract bbcode formatted event data from a string.
170 * @params: string $s The string which should be parsed for event data.
172 * @return array The array with the event information.
174 public static function fromBBCode($text)
179 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
180 $ev['summary'] = $match[1];
184 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
185 $ev['desc'] = $match[1];
189 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
190 $ev['start'] = $match[1];
194 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
195 $ev['finish'] = $match[1];
199 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
200 $ev['location'] = $match[1];
204 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
205 $ev['adjust'] = $match[1];
208 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
213 public static function sortByDate($event_list)
215 usort($event_list, ['self', 'compareDatesCallback']);
219 private static function compareDatesCallback($event_a, $event_b)
221 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
222 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
224 if ($date_a === $date_b) {
225 return strcasecmp($event_a['desc'], $event_b['desc']);
228 return strcmp($date_a, $date_b);
232 * Delete an event from the event table.
234 * Note: This function does only delete the event from the event table not its
235 * related entry in the item table.
237 * @param int $event_id Event ID.
241 public static function delete($event_id)
243 if ($event_id == 0) {
247 DBA::delete('event', ['id' => $event_id]);
248 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
254 * Store the event in the event table and create an event item in the item table.
256 * @param array $arr Array with event data.
257 * @return int The new event id.
258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260 public static function store($arr)
263 $event['id'] = intval($arr['id'] ?? 0);
264 $event['uid'] = intval($arr['uid'] ?? 0);
265 $event['cid'] = intval($arr['cid'] ?? 0);
266 $event['guid'] = ($arr['guid'] ?? '') ?: System::createUUID();
267 $event['uri'] = ($arr['uri'] ?? '') ?: Item::newURI($event['uid'], $event['guid']);
268 $event['uri-id'] = ItemURI::insert(['uri' => $event['uri'], 'guid' => $event['guid']]);
269 $event['type'] = ($arr['type'] ?? '') ?: 'event';
270 $event['summary'] = $arr['summary'] ?? '';
271 $event['desc'] = $arr['desc'] ?? '';
272 $event['location'] = $arr['location'] ?? '';
273 $event['allow_cid'] = $arr['allow_cid'] ?? '';
274 $event['allow_gid'] = $arr['allow_gid'] ?? '';
275 $event['deny_cid'] = $arr['deny_cid'] ?? '';
276 $event['deny_gid'] = $arr['deny_gid'] ?? '';
277 $event['adjust'] = intval($arr['adjust'] ?? 0);
278 $event['nofinish'] = intval($arr['nofinish'] ?? (!empty($event['start']) && empty($event['finish'])));
280 $event['created'] = DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now');
281 $event['edited'] = DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now');
282 $event['start'] = DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME);
283 $event['finish'] = DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME);
284 if ($event['finish'] < DBA::NULL_DATETIME) {
285 $event['finish'] = DBA::NULL_DATETIME;
288 // Existing event being modified.
290 // has the event actually changed?
291 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
292 if (!DBA::isResult($existing_event)) {
296 if ($existing_event['edited'] === $event['edited']) {
301 'edited' => $event['edited'],
302 'start' => $event['start'],
303 'finish' => $event['finish'],
304 'summary' => $event['summary'],
305 'desc' => $event['desc'],
306 'location' => $event['location'],
307 'type' => $event['type'],
308 'adjust' => $event['adjust'],
309 'nofinish' => $event['nofinish'],
312 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
314 $item = Post::selectFirst(['id', 'uri-id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
315 if (DBA::isResult($item)) {
316 $object = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
317 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
318 $object .= '</object>' . "\n";
320 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
321 Item::update($fields, ['id' => $item['id']]);
324 Hook::callAll('event_updated', $event['id']);
326 // New event. Store it.
327 DBA::insert('event', $event);
329 $event['id'] = DBA::lastInsertId();
331 Hook::callAll("event_created", $event['id']);
337 public static function getItemArrayForId(int $event_id, array $item = []):array
339 if (empty($event_id)) {
343 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
344 if ($event['type'] != 'event') {
349 $conditions = ['id' => $event['cid']];
351 $conditions = ['uid' => $event['uid'], 'self' => true];
354 $contact = DBA::selectFirst('contact', [], $conditions);
356 $event['id'] = $event_id;
358 $item['uid'] = $event['uid'];
359 $item['contact-id'] = $event['cid'];
360 $item['uri'] = $event['uri'];
361 $item['uri-id'] = ItemURI::getIdByURI($event['uri']);
362 $item['guid'] = $event['guid'];
363 $item['plink'] = $arr['plink'] ?? '';
364 $item['post-type'] = Item::PT_EVENT;
365 $item['wall'] = $event['cid'] ? 0 : 1;
366 $item['contact-id'] = $contact['id'];
367 $item['owner-name'] = $contact['name'];
368 $item['owner-link'] = $contact['url'];
369 $item['owner-avatar'] = $contact['thumb'];
370 $item['author-name'] = $contact['name'];
371 $item['author-link'] = $contact['url'];
372 $item['author-avatar'] = $contact['thumb'];
374 $item['allow_cid'] = $event['allow_cid'];
375 $item['allow_gid'] = $event['allow_gid'];
376 $item['deny_cid'] = $event['deny_cid'];
377 $item['deny_gid'] = $event['deny_gid'];
378 $item['private'] = intval($event['private'] ?? 0);
379 $item['visible'] = 1;
380 $item['verb'] = Activity::POST;
381 $item['object-type'] = Activity\ObjectType::EVENT;
382 $item['post-type'] = Item::PT_EVENT;
383 $item['origin'] = $event['cid'] === 0 ? 1 : 0;
384 $item['body'] = self::getBBCode($event);
385 $item['event-id'] = $event['id'];
387 $item['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
388 $item['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
389 $item['object'] .= '</object>' . "\n";
394 public static function getItemArrayForImportedId(int $event_id, array $item = []):array
396 if (empty($event_id)) {
400 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
401 if ($event['type'] != 'event') {
405 $item['post-type'] = Item::PT_EVENT;
407 $item['object-type'] = Activity\ObjectType::EVENT;
408 $item['body'] = self::getBBCode($event);
409 $item['event-id'] = $event_id;
411 $item['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
412 $item['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
413 $item['object'] .= '</object>' . "\n";
419 * Create an array with translation strings used for events.
421 * @return array Array with translations strings.
422 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
424 public static function getStrings()
426 // First day of the week (0 = Sunday).
427 $firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0);
430 "firstDay" => $firstDay,
431 "allday" => DI::l10n()->t("all-day"),
433 "Sun" => DI::l10n()->t("Sun"),
434 "Mon" => DI::l10n()->t("Mon"),
435 "Tue" => DI::l10n()->t("Tue"),
436 "Wed" => DI::l10n()->t("Wed"),
437 "Thu" => DI::l10n()->t("Thu"),
438 "Fri" => DI::l10n()->t("Fri"),
439 "Sat" => DI::l10n()->t("Sat"),
441 "Sunday" => DI::l10n()->t("Sunday"),
442 "Monday" => DI::l10n()->t("Monday"),
443 "Tuesday" => DI::l10n()->t("Tuesday"),
444 "Wednesday" => DI::l10n()->t("Wednesday"),
445 "Thursday" => DI::l10n()->t("Thursday"),
446 "Friday" => DI::l10n()->t("Friday"),
447 "Saturday" => DI::l10n()->t("Saturday"),
449 "Jan" => DI::l10n()->t("Jan"),
450 "Feb" => DI::l10n()->t("Feb"),
451 "Mar" => DI::l10n()->t("Mar"),
452 "Apr" => DI::l10n()->t("Apr"),
453 "May" => DI::l10n()->t("May"),
454 "Jun" => DI::l10n()->t("Jun"),
455 "Jul" => DI::l10n()->t("Jul"),
456 "Aug" => DI::l10n()->t("Aug"),
457 "Sep" => DI::l10n()->t("Sept"),
458 "Oct" => DI::l10n()->t("Oct"),
459 "Nov" => DI::l10n()->t("Nov"),
460 "Dec" => DI::l10n()->t("Dec"),
462 "January" => DI::l10n()->t("January"),
463 "February" => DI::l10n()->t("February"),
464 "March" => DI::l10n()->t("March"),
465 "April" => DI::l10n()->t("April"),
466 "June" => DI::l10n()->t("June"),
467 "July" => DI::l10n()->t("July"),
468 "August" => DI::l10n()->t("August"),
469 "September" => DI::l10n()->t("September"),
470 "October" => DI::l10n()->t("October"),
471 "November" => DI::l10n()->t("November"),
472 "December" => DI::l10n()->t("December"),
474 "today" => DI::l10n()->t("today"),
475 "month" => DI::l10n()->t("month"),
476 "week" => DI::l10n()->t("week"),
477 "day" => DI::l10n()->t("day"),
479 "noevent" => DI::l10n()->t("No events to display"),
481 "dtstart_label" => DI::l10n()->t("Starts:"),
482 "dtend_label" => DI::l10n()->t("Finishes:"),
483 "location_label" => DI::l10n()->t("Location:")
490 * Removes duplicated birthday events.
492 * @param array $dates Array of possibly duplicated events.
493 * @return array Cleaned events.
495 * @todo We should replace this with a separate update function if there is some time left.
497 private static function removeDuplicates(array $dates)
501 foreach ($dates as $date) {
502 if ($date['type'] == 'birthday') {
503 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
508 return array_values($dates2);
512 * Get an event by its event ID.
514 * @param int $owner_uid The User ID of the owner of the event
515 * @param int $event_id The ID of the event in the event table
516 * @param string $sql_extra
517 * @return array Query result
520 public static function getListById($owner_uid, $event_id, $sql_extra = '')
524 // Ownly allow events if there is a valid owner_id.
525 if ($owner_uid == 0) {
529 // Query for the event by event id
530 $events = DBA::toArray(DBA::p("SELECT `event`.*, `post-user`.`id` AS `itemid` FROM `event`
531 LEFT JOIN `post-user` ON `post-user`.`event-id` = `event`.`id` AND `post-user`.`uid` = `event`.`uid`
532 WHERE `event`.`uid` = ? AND `event`.`id` = ? $sql_extra",
533 $owner_uid, $event_id));
535 if (DBA::isResult($events)) {
536 $return = self::removeDuplicates($events);
543 * Get all events in a specific time frame.
545 * @param int $owner_uid The User ID of the owner of the events.
546 * @param array $event_params An associative array with
548 * string 'start' => Start time of the timeframe.
549 * string 'finish' => Finish time of the timeframe.
550 * string 'adjust_start' =>
551 * string 'adjust_finish' =>
553 * @param string $sql_extra Additional sql conditions (e.g. permission request).
555 * @return array Query results.
558 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
562 // Only allow events if there is a valid owner_id.
563 if ($owner_uid == 0) {
567 // Query for the event by date.
568 $events = DBA::toArray(DBA::p("SELECT `event`.*, `post-user`.`id` AS `itemid` FROM `event`
569 LEFT JOIN `post-user` ON `post-user`.`event-id` = `event`.`id` AND `post-user`.`uid` = `event`.`uid`
570 WHERE `event`.`uid` = ? AND `event`.`ignore` = ?
571 AND ((NOT `adjust` AND (`finish` >= ? OR (`nofinish` AND `start` >= ?)) AND `start` <= ?)
572 OR (`adjust` AND (`finish` >= ? OR (`nofinish` AND `start` >= ?)) AND `start` <= ?))" . $sql_extra,
573 $owner_uid, $event_params["ignore"],
574 $event_params["start"], $event_params["start"], $event_params["finish"],
575 $event_params["adjust_start"], $event_params["adjust_start"], $event_params["adjust_finish"]));
577 if (DBA::isResult($events)) {
578 $return = self::removeDuplicates($events);
585 * Convert an array query results in an array which could be used by the events template.
587 * @param array $event_result Event query array.
588 * @return array Event array for the template.
589 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
590 * @throws \ImagickException
592 public static function prepareListForTemplate(array $event_result)
597 $fmt = DI::l10n()->t('l, F j');
598 foreach ($event_result as $event) {
599 $item = Post::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link', 'private', 'uri-id'], ['id' => $event['itemid']]);
600 if (!DBA::isResult($item)) {
601 // Using default values when no item had been found
602 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => '', 'private' => Item::PUBLIC, 'uri-id' => ($event['uri-id'] ?? 0)];
605 $event = array_merge($event, $item);
607 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
608 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
609 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
610 $day = DI::l10n()->getDay($day);
612 if ($event['nofinish']) {
615 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
618 $is_first = ($day !== $last_date);
622 // Show edit and drop actions only if the user is the owner of the event and the event
623 // is a real event (no bithdays).
627 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
628 $edit = !$event['cid'] ? [DI::baseUrl() . '/events/event/' . $event['id'], DI::l10n()->t('Edit event') , '', ''] : null;
629 $copy = !$event['cid'] ? [DI::baseUrl() . '/events/copy/' . $event['id'] , DI::l10n()->t('Duplicate event'), '', ''] : null;
630 $drop = [DI::baseUrl() . '/events/drop/' . $event['id'] , DI::l10n()->t('Delete event') , '', ''];
633 $title = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['summary']));
635 list($title, $_trash) = explode("<br", BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc'])), BBCode::API);
638 $author_link = $event['author-link'];
640 $event['author-link'] = Contact::magicLink($author_link);
642 $html = self::getHTML($event);
643 $event['summary'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['summary']));
644 $event['desc'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc']));
645 $event['location'] = BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['location']));
647 'id' => $event['id'],
657 'is_first' => $is_first,
660 'plink' => Item::getPlink($event),
668 * Format event to export format (ical/csv).
670 * @param array $events Query result for events.
671 * @param string $format The output format (ical/csv).
674 * @return string Content according to selected export format.
676 * @todo Implement timezone support
678 private static function formatListForExport(array $events, $format)
682 if (!count($events)) {
687 // Format the exported data as a CSV file.
689 header("Content-type: text/csv");
690 $o .= '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
692 foreach ($events as $event) {
693 /// @todo The time / date entries don't include any information about the
694 /// timezone the event is scheduled in :-/
695 $tmp1 = strtotime($event['start']);
696 $tmp2 = strtotime($event['finish']);
697 $time_format = "%H:%M:%S";
698 $date_format = "%Y-%m-%d";
700 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
701 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
702 '", "' . strftime($date_format, $tmp2) .
703 '", "' . strftime($time_format, $tmp2) .
704 '", "' . $event['location'] . '"' . PHP_EOL;
708 // Format the exported data as a ics file.
710 header("Content-type: text/ics");
711 $o = 'BEGIN:VCALENDAR' . PHP_EOL
712 . 'VERSION:2.0' . PHP_EOL
713 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
714 /// @todo include timezone informations in cases were the time is not in UTC
715 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
716 // . 'BEGIN:VTIMEZONE' . PHP_EOL
717 // . 'TZID:' . $timezone . PHP_EOL
718 // . 'END:VTIMEZONE' . PHP_EOL;
719 // TODO instead of PHP_EOL CRLF should be used for long entries
720 // but test your solution against http://icalvalid.cloudapp.net/
721 // also long lines SHOULD be split at 75 characters length
722 foreach ($events as $event) {
723 if ($event['adjust'] == 1) {
728 $o .= 'BEGIN:VEVENT' . PHP_EOL;
730 if ($event['start']) {
731 $tmp = strtotime($event['start']);
732 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
733 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
736 if (!$event['nofinish']) {
737 $tmp = strtotime($event['finish']);
738 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
739 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
742 if ($event['summary']) {
743 $tmp = $event['summary'];
744 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
745 $tmp = addcslashes($tmp, ',;');
746 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
749 if ($event['desc']) {
750 $tmp = $event['desc'];
751 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
752 $tmp = addcslashes($tmp, ',;');
753 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
756 if ($event['location']) {
757 $tmp = $event['location'];
758 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
759 $tmp = addcslashes($tmp, ',;');
760 $o .= 'LOCATION:' . $tmp . PHP_EOL;
763 $o .= 'END:VEVENT' . PHP_EOL;
767 $o .= 'END:VCALENDAR' . PHP_EOL;
775 * Get all events for a user ID.
777 * The query for events is done permission sensitive.
778 * If the user is the owner of the calendar they
779 * will get all of their available events.
780 * If the user is only a visitor only the public events will
783 * @param int $uid The user ID.
785 * @return array Query results.
788 private static function getListByUserId($uid = 0)
796 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
798 $conditions = ['uid' => $uid, 'cid' => 0];
800 // Does the user who requests happen to be the owner of the events
801 // requested? then show all of your events, otherwise only those that
802 // don't have limitations set in allow_cid and allow_gid.
803 if (local_user() != $uid) {
804 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
807 $events = DBA::select('event', $fields, $conditions);
808 if (DBA::isResult($events)) {
809 $return = DBA::toArray($events);
817 * @param int $uid The user ID.
818 * @param string $format Output format (ical/csv).
819 * @return array With the results:
820 * bool 'success' => True if the processing was successful,<br>
821 * string 'format' => The output format,<br>
822 * string 'extension' => The file extension of the output format,<br>
823 * string 'content' => The formatted output content.<br>
826 * @todo Respect authenticated users with events_by_uid().
828 public static function exportListByUserId($uid, $format = 'ical')
832 // Get all events which are owned by a uid (respects permissions).
833 $events = self::getListByUserId($uid);
835 // We have the events that are available for the requestor.
836 // Now format the output according to the requested format.
837 $res = self::formatListForExport($events, $format);
839 // If there are results the precess was successful.
844 // Get the file extension for the format.
859 'success' => $process,
861 'extension' => $file_ext,
869 * Format an item array with event data to HTML.
871 * @param array $item Array with item and event data.
872 * @return string HTML output.
873 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
874 * @throws \ImagickException
876 public static function getItemHTML(array $item) {
880 // Set the different time formats.
881 $dformat = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
882 $dformat_short = DI::l10n()->t('D g:i A'); // Fri 8:01 AM.
883 $tformat = DI::l10n()->t('g:i A'); // 8:01 AM.
885 // Convert the time to different formats.
886 $dtstart_dt = DI::l10n()->getDay(
887 $item['event-adjust'] ?
888 DateTimeFormat::local($item['event-start'], $dformat)
889 : DateTimeFormat::utc($item['event-start'], $dformat)
891 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
892 // Format: Jan till Dec.
893 $month_short = DI::l10n()->getDayShort(
894 $item['event-adjust'] ?
895 DateTimeFormat::local($item['event-start'], 'M')
896 : DateTimeFormat::utc($item['event-start'], 'M')
898 // Format: 1 till 31.
899 $date_short = $item['event-adjust'] ?
900 DateTimeFormat::local($item['event-start'], 'j')
901 : DateTimeFormat::utc($item['event-start'], 'j');
902 $start_time = $item['event-adjust'] ?
903 DateTimeFormat::local($item['event-start'], $tformat)
904 : DateTimeFormat::utc($item['event-start'], $tformat);
905 $start_short = DI::l10n()->getDayShort(
906 $item['event-adjust'] ?
907 DateTimeFormat::local($item['event-start'], $dformat_short)
908 : DateTimeFormat::utc($item['event-start'], $dformat_short)
911 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
912 if (!$item['event-nofinish']) {
914 $dtend_dt = DI::l10n()->getDay(
915 $item['event-adjust'] ?
916 DateTimeFormat::local($item['event-finish'], $dformat)
917 : DateTimeFormat::utc($item['event-finish'], $dformat)
919 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
920 $end_short = DI::l10n()->getDayShort(
921 $item['event-adjust'] ?
922 DateTimeFormat::local($item['event-finish'], $dformat_short)
923 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
925 $end_time = $item['event-adjust'] ?
926 DateTimeFormat::local($item['event-finish'], $tformat)
927 : DateTimeFormat::utc($item['event-finish'], $tformat);
928 // Check if start and finish time is at the same day.
929 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
939 // Format the event location.
940 $location = self::locationToArray($item['event-location']);
942 // Construct the profile link (magic-auth).
943 $author = ['uid' => 0, 'id' => $item['author-id'],
944 'network' => $item['author-network'], 'url' => $item['author-link']];
945 $profile_link = Contact::magicLinkByContact($author);
947 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
948 $return = Renderer::replaceMacros($tpl, [
949 '$id' => $item['event-id'],
950 '$title' => BBCode::convertForUriId($item['uri-id'], $item['event-summary']),
951 '$dtstart_label' => DI::l10n()->t('Starts:'),
952 '$dtstart_title' => $dtstart_title,
953 '$dtstart_dt' => $dtstart_dt,
954 '$finish' => $finish,
955 '$dtend_label' => DI::l10n()->t('Finishes:'),
956 '$dtend_title' => $dtend_title,
957 '$dtend_dt' => $dtend_dt,
958 '$month_short' => $month_short,
959 '$date_short' => $date_short,
960 '$same_date' => $same_date,
961 '$start_time' => $start_time,
962 '$start_short' => $start_short,
963 '$end_time' => $end_time,
964 '$end_short' => $end_short,
965 '$author_name' => $item['author-name'],
966 '$author_link' => $profile_link,
967 '$author_avatar' => $item['author-avatar'],
968 '$description' => BBCode::convertForUriId($item['uri-id'], $item['event-desc']),
969 '$location_label' => DI::l10n()->t('Location:'),
970 '$show_map_label' => DI::l10n()->t('Show map'),
971 '$hide_map_label' => DI::l10n()->t('Hide map'),
972 '$map_btn_label' => DI::l10n()->t('Show map'),
973 '$location' => $location
980 * Format a string with map bbcode to an array with location data.
982 * Note: The string must only contain location data. A string with no bbcode will be
983 * handled as location name.
985 * @param string $s The string with the bbcode formatted location data.
987 * @return array The array with the location data.
988 * 'name' => The name of the location,<br>
989 * 'address' => The address of the location,<br>
990 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
993 private static function locationToArray($s = '') {
998 $location = ['name' => $s];
1000 // Map tag with location name - e.g. [map]Paris[/map].
1001 if (strpos($s, '[/map]') !== false) {
1002 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
1003 if (intval($found) > 0 && array_key_exists(1, $match)) {
1004 $location['address'] = $match[1];
1005 // Remove the map bbcode from the location name.
1006 $location['name'] = str_replace($match[0], "", $s);
1008 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
1009 } elseif (strpos($s, '[map=') !== false) {
1010 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
1011 if (intval($found) > 0 && array_key_exists(1, $match)) {
1012 $location['coordinates'] = $match[1];
1013 // Remove the map bbcode from the location name.
1014 $location['name'] = str_replace($match[0], "", $s);
1018 $location['name'] = BBCode::convert($location['name']);
1020 // Construct the map HTML.
1021 if (isset($location['address'])) {
1022 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
1023 } elseif (isset($location['coordinates'])) {
1024 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
1031 * Add new birthday event for this person
1033 * @param array $contact Contact array, expects: id, uid, url, name
1034 * @param string $birthday Birthday of the contact
1036 * @throws \Exception
1038 public static function createBirthday($contact, $birthday)
1040 // Check for duplicates
1042 'uid' => $contact['uid'],
1043 'cid' => $contact['id'],
1044 'start' => DateTimeFormat::utc($birthday),
1045 'type' => 'birthday'
1047 if (DBA::exists('event', $condition)) {
1052 * Add new birthday event for this person
1054 * summary is just a readable placeholder in case the event is shared
1055 * with others. We will replace it during presentation to our $importer
1056 * to contain a sparkle link and perhaps a photo.
1059 'uid' => $contact['uid'],
1060 'cid' => $contact['id'],
1061 'start' => DateTimeFormat::utc($birthday),
1062 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1063 'summary' => DI::l10n()->t('%s\'s birthday', $contact['name']),
1064 'desc' => DI::l10n()->t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1065 'type' => 'birthday',
1069 self::store($values);