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\Renderer;
28 use Friendica\Core\System;
29 use Friendica\Database\DBA;
31 use Friendica\Protocol\Activity;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Map;
34 use Friendica\Util\Strings;
35 use Friendica\Util\XML;
38 * functions for interacting with the event database table
43 public static function getHTML(array $event, $simple = false)
49 $bd_format = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8 AM.
51 $event_start = DI::l10n()->getDay(
52 !empty($event['adjust']) ?
53 DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
56 if (!empty($event['finish'])) {
57 $event_end = DI::l10n()->getDay(
58 !empty($event['adjust']) ?
59 DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
68 if (!empty($event['summary'])) {
69 $o .= "<h3>" . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . "</h3>";
72 if (!empty($event['desc'])) {
73 $o .= "<div>" . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . "</div>";
76 $o .= "<h4>" . DI::l10n()->t('Starts:') . "</h4><p>" . $event_start . "</p>";
78 if (!$event['nofinish']) {
79 $o .= "<h4>" . DI::l10n()->t('Finishes:') . "</h4><p>" . $event_end . "</p>";
82 if (!empty($event['location'])) {
83 $o .= "<h4>" . DI::l10n()->t('Location:') . "</h4><p>" . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple) . "</p>";
89 $o = '<div class="vevent">' . "\r\n";
91 $o .= '<div class="summary event-summary">' . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . '</div>' . "\r\n";
93 $o .= '<div class="event-start"><span class="event-label">' . DI::l10n()->t('Starts:') . '</span> <span class="dtstart" title="'
94 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
95 . '" >' . $event_start
96 . '</span></div>' . "\r\n";
98 if (!$event['nofinish']) {
99 $o .= '<div class="event-end" ><span class="event-label">' . DI::l10n()->t('Finishes:') . '</span> <span class="dtend" title="'
100 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
102 . '</span></div>' . "\r\n";
105 if (!empty($event['desc'])) {
106 $o .= '<div class="description event-description">' . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . '</div>' . "\r\n";
109 if (!empty($event['location'])) {
110 $o .= '<div class="event-location"><span class="event-label">' . DI::l10n()->t('Location:') . '</span> <span class="location">'
111 . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple)
112 . '</span></div>' . "\r\n";
114 // Include a map of the location if the [map] BBCode is used.
115 if (strpos($event['location'], "[map") !== false) {
116 $map = Map::byLocation($event['location'], $simple);
117 if ($map !== $event['location']) {
123 $o .= '</div>' . "\r\n";
128 * Convert an array with event data to bbcode.
130 * @param array $event Array which contains the event data.
131 * @return string The event as a bbcode formatted string.
133 private static function getBBCode(array $event)
137 if ($event['summary']) {
138 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
141 if ($event['desc']) {
142 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
145 if ($event['start']) {
146 $o .= '[event-start]' . $event['start'] . '[/event-start]';
149 if (($event['finish']) && (!$event['nofinish'])) {
150 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
153 if ($event['location']) {
154 $o .= '[event-location]' . $event['location'] . '[/event-location]';
157 if ($event['adjust']) {
158 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
165 * Extract bbcode formatted event data from a string.
167 * @params: string $s The string which should be parsed for event data.
169 * @return array The array with the event information.
171 public static function fromBBCode($text)
176 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
177 $ev['summary'] = $match[1];
181 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
182 $ev['desc'] = $match[1];
186 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
187 $ev['start'] = $match[1];
191 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
192 $ev['finish'] = $match[1];
196 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
197 $ev['location'] = $match[1];
201 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
202 $ev['adjust'] = $match[1];
205 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
210 public static function sortByDate($event_list)
212 usort($event_list, ['self', 'compareDatesCallback']);
216 private static function compareDatesCallback($event_a, $event_b)
218 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
219 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
221 if ($date_a === $date_b) {
222 return strcasecmp($event_a['desc'], $event_b['desc']);
225 return strcmp($date_a, $date_b);
229 * Delete an event from the event table.
231 * Note: This function does only delete the event from the event table not its
232 * related entry in the item table.
234 * @param int $event_id Event ID.
238 public static function delete($event_id)
240 if ($event_id == 0) {
244 DBA::delete('event', ['id' => $event_id], ['cascade' => false]);
245 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
251 * Store the event in the event table and create an event item in the item table.
253 * @param array $arr Array with event data.
254 * @return int The new event id.
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
257 public static function store($arr)
260 $event['id'] = intval($arr['id'] ?? 0);
261 $event['uid'] = intval($arr['uid'] ?? 0);
262 $event['cid'] = intval($arr['cid'] ?? 0);
263 $event['guid'] = ($arr['guid'] ?? '') ?: System::createUUID();
264 $event['uri'] = ($arr['uri'] ?? '') ?: Item::newURI($event['uid'], $event['guid']);
265 $event['type'] = ($arr['type'] ?? '') ?: 'event';
266 $event['summary'] = $arr['summary'] ?? '';
267 $event['desc'] = $arr['desc'] ?? '';
268 $event['location'] = $arr['location'] ?? '';
269 $event['allow_cid'] = $arr['allow_cid'] ?? '';
270 $event['allow_gid'] = $arr['allow_gid'] ?? '';
271 $event['deny_cid'] = $arr['deny_cid'] ?? '';
272 $event['deny_gid'] = $arr['deny_gid'] ?? '';
273 $event['adjust'] = intval($arr['adjust'] ?? 0);
274 $event['nofinish'] = intval($arr['nofinish'] ?? (!empty($event['start']) && empty($event['finish'])));
276 $event['created'] = DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now');
277 $event['edited'] = DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now');
278 $event['start'] = DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME);
279 $event['finish'] = DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME);
280 if ($event['finish'] < DBA::NULL_DATETIME) {
281 $event['finish'] = DBA::NULL_DATETIME;
283 $private = intval($arr['private'] ?? 0);
285 $conditions = ['uid' => $event['uid']];
287 $conditions['id'] = $event['cid'];
289 $conditions['self'] = true;
292 $contact = DBA::selectFirst('contact', [], $conditions);
294 // Existing event being modified.
296 // has the event actually changed?
297 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
298 if (!DBA::isResult($existing_event) || ($existing_event['edited'] === $event['edited'])) {
300 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
302 return DBA::isResult($item) ? $item['id'] : 0;
306 'edited' => $event['edited'],
307 'start' => $event['start'],
308 'finish' => $event['finish'],
309 'summary' => $event['summary'],
310 'desc' => $event['desc'],
311 'location' => $event['location'],
312 'type' => $event['type'],
313 'adjust' => $event['adjust'],
314 'nofinish' => $event['nofinish'],
317 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
319 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
320 if (DBA::isResult($item)) {
321 $object = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
322 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
323 $object .= '</object>' . "\n";
325 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
326 Item::update($fields, ['id' => $item['id']]);
328 $item_id = $item['id'];
333 Hook::callAll('event_updated', $event['id']);
335 // New event. Store it.
336 DBA::insert('event', $event);
340 // Don't create an item for birthday events
341 if ($event['type'] == 'event') {
342 $event['id'] = DBA::lastInsertId();
346 $item_arr['uid'] = $event['uid'];
347 $item_arr['contact-id'] = $event['cid'];
348 $item_arr['uri'] = $event['uri'];
349 $item_arr['parent-uri'] = $event['uri'];
350 $item_arr['guid'] = $event['guid'];
351 $item_arr['plink'] = $arr['plink'] ?? '';
352 $item_arr['post-type'] = Item::PT_EVENT;
353 $item_arr['wall'] = $event['cid'] ? 0 : 1;
354 $item_arr['contact-id'] = $contact['id'];
355 $item_arr['owner-name'] = $contact['name'];
356 $item_arr['owner-link'] = $contact['url'];
357 $item_arr['owner-avatar'] = $contact['thumb'];
358 $item_arr['author-name'] = $contact['name'];
359 $item_arr['author-link'] = $contact['url'];
360 $item_arr['author-avatar'] = $contact['thumb'];
361 $item_arr['title'] = '';
362 $item_arr['allow_cid'] = $event['allow_cid'];
363 $item_arr['allow_gid'] = $event['allow_gid'];
364 $item_arr['deny_cid'] = $event['deny_cid'];
365 $item_arr['deny_gid'] = $event['deny_gid'];
366 $item_arr['private'] = $private;
367 $item_arr['visible'] = 1;
368 $item_arr['verb'] = Activity::POST;
369 $item_arr['object-type'] = Activity\ObjectType::EVENT;
370 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
371 $item_arr['body'] = self::getBBCode($event);
372 $item_arr['event-id'] = $event['id'];
374 $item_arr['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
375 $item_arr['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
376 $item_arr['object'] .= '</object>' . "\n";
378 $item_id = Item::insert($item_arr);
381 Hook::callAll("event_created", $event['id']);
388 * Create an array with translation strings used for events.
390 * @return array Array with translations strings.
391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
393 public static function getStrings()
395 // First day of the week (0 = Sunday).
396 $firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0);
399 "firstDay" => $firstDay,
400 "allday" => DI::l10n()->t("all-day"),
402 "Sun" => DI::l10n()->t("Sun"),
403 "Mon" => DI::l10n()->t("Mon"),
404 "Tue" => DI::l10n()->t("Tue"),
405 "Wed" => DI::l10n()->t("Wed"),
406 "Thu" => DI::l10n()->t("Thu"),
407 "Fri" => DI::l10n()->t("Fri"),
408 "Sat" => DI::l10n()->t("Sat"),
410 "Sunday" => DI::l10n()->t("Sunday"),
411 "Monday" => DI::l10n()->t("Monday"),
412 "Tuesday" => DI::l10n()->t("Tuesday"),
413 "Wednesday" => DI::l10n()->t("Wednesday"),
414 "Thursday" => DI::l10n()->t("Thursday"),
415 "Friday" => DI::l10n()->t("Friday"),
416 "Saturday" => DI::l10n()->t("Saturday"),
418 "Jan" => DI::l10n()->t("Jan"),
419 "Feb" => DI::l10n()->t("Feb"),
420 "Mar" => DI::l10n()->t("Mar"),
421 "Apr" => DI::l10n()->t("Apr"),
422 "May" => DI::l10n()->t("May"),
423 "Jun" => DI::l10n()->t("Jun"),
424 "Jul" => DI::l10n()->t("Jul"),
425 "Aug" => DI::l10n()->t("Aug"),
426 "Sep" => DI::l10n()->t("Sept"),
427 "Oct" => DI::l10n()->t("Oct"),
428 "Nov" => DI::l10n()->t("Nov"),
429 "Dec" => DI::l10n()->t("Dec"),
431 "January" => DI::l10n()->t("January"),
432 "February" => DI::l10n()->t("February"),
433 "March" => DI::l10n()->t("March"),
434 "April" => DI::l10n()->t("April"),
435 "June" => DI::l10n()->t("June"),
436 "July" => DI::l10n()->t("July"),
437 "August" => DI::l10n()->t("August"),
438 "September" => DI::l10n()->t("September"),
439 "October" => DI::l10n()->t("October"),
440 "November" => DI::l10n()->t("November"),
441 "December" => DI::l10n()->t("December"),
443 "today" => DI::l10n()->t("today"),
444 "month" => DI::l10n()->t("month"),
445 "week" => DI::l10n()->t("week"),
446 "day" => DI::l10n()->t("day"),
448 "noevent" => DI::l10n()->t("No events to display"),
450 "dtstart_label" => DI::l10n()->t("Starts:"),
451 "dtend_label" => DI::l10n()->t("Finishes:"),
452 "location_label" => DI::l10n()->t("Location:")
459 * Removes duplicated birthday events.
461 * @param array $dates Array of possibly duplicated events.
462 * @return array Cleaned events.
464 * @todo We should replace this with a separate update function if there is some time left.
466 private static function removeDuplicates(array $dates)
470 foreach ($dates as $date) {
471 if ($date['type'] == 'birthday') {
472 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
477 return array_values($dates2);
481 * Get an event by its event ID.
483 * @param int $owner_uid The User ID of the owner of the event
484 * @param int $event_id The ID of the event in the event table
485 * @param string $sql_extra
486 * @return array Query result
489 public static function getListById($owner_uid, $event_id, $sql_extra = '')
493 // Ownly allow events if there is a valid owner_id.
494 if ($owner_uid == 0) {
498 // Query for the event by event id
499 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
500 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
501 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
506 if (DBA::isResult($r)) {
507 $return = self::removeDuplicates($r);
514 * Get all events in a specific time frame.
516 * @param int $owner_uid The User ID of the owner of the events.
517 * @param array $event_params An associative array with
519 * string 'start' => Start time of the timeframe.
520 * string 'finish' => Finish time of the timeframe.
521 * string 'adjust_start' =>
522 * string 'adjust_finish' =>
524 * @param string $sql_extra Additional sql conditions (e.g. permission request).
526 * @return array Query results.
529 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
533 // Only allow events if there is a valid owner_id.
534 if ($owner_uid == 0) {
538 // Query for the event by date.
539 // @todo Slow query (518 seconds to run), to be optimzed
540 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
541 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
542 WHERE `event`.`uid` = %d AND event.ignore = %d
543 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
544 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
547 intval($event_params["ignore"]),
548 DBA::escape($event_params["start"]),
549 DBA::escape($event_params["start"]),
550 DBA::escape($event_params["finish"]),
551 DBA::escape($event_params["adjust_start"]),
552 DBA::escape($event_params["adjust_start"]),
553 DBA::escape($event_params["adjust_finish"])
556 if (DBA::isResult($r)) {
557 $return = self::removeDuplicates($r);
564 * Convert an array query results in an array which could be used by the events template.
566 * @param array $event_result Event query array.
567 * @return array Event array for the template.
568 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
569 * @throws \ImagickException
571 public static function prepareListForTemplate(array $event_result)
576 $fmt = DI::l10n()->t('l, F j');
577 foreach ($event_result as $event) {
578 $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
579 if (!DBA::isResult($item)) {
580 // Using default values when no item had been found
581 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
584 $event = array_merge($event, $item);
586 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
587 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
588 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
589 $day = DI::l10n()->getDay($day);
591 if ($event['nofinish']) {
594 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
597 $is_first = ($day !== $last_date);
601 // Show edit and drop actions only if the user is the owner of the event and the event
602 // is a real event (no bithdays).
606 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
607 $edit = !$event['cid'] ? [DI::baseUrl() . '/events/event/' . $event['id'], DI::l10n()->t('Edit event') , '', ''] : null;
608 $copy = !$event['cid'] ? [DI::baseUrl() . '/events/copy/' . $event['id'] , DI::l10n()->t('Duplicate event'), '', ''] : null;
609 $drop = [DI::baseUrl() . '/events/drop/' . $event['id'] , DI::l10n()->t('Delete event') , '', ''];
612 $title = BBCode::convert(Strings::escapeHtml($event['summary']));
614 list($title, $_trash) = explode("<br", BBCode::convert(Strings::escapeHtml($event['desc'])), 2);
617 $author_link = $event['author-link'];
618 $plink = $event['plink'];
620 $event['author-link'] = Contact::magicLink($author_link);
621 $event['plink'] = Contact::magicLink($author_link, $plink);
623 $html = self::getHTML($event);
624 $event['summary'] = BBCode::convert(Strings::escapeHtml($event['summary']));
625 $event['desc'] = BBCode::convert(Strings::escapeHtml($event['desc']));
626 $event['location'] = BBCode::convert(Strings::escapeHtml($event['location']));
628 'id' => $event['id'],
638 'is_first' => $is_first,
641 'plink' => [$event['plink'], DI::l10n()->t('link to source'), '', ''],
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 if ($event['adjust'] == 1) {
709 $o .= 'BEGIN:VEVENT' . PHP_EOL;
711 if ($event['start']) {
712 $tmp = strtotime($event['start']);
713 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
714 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
717 if (!$event['nofinish']) {
718 $tmp = strtotime($event['finish']);
719 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
720 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
723 if ($event['summary']) {
724 $tmp = $event['summary'];
725 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
726 $tmp = addcslashes($tmp, ',;');
727 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
730 if ($event['desc']) {
731 $tmp = $event['desc'];
732 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
733 $tmp = addcslashes($tmp, ',;');
734 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
737 if ($event['location']) {
738 $tmp = $event['location'];
739 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
740 $tmp = addcslashes($tmp, ',;');
741 $o .= 'LOCATION:' . $tmp . PHP_EOL;
744 $o .= 'END:VEVENT' . PHP_EOL;
748 $o .= 'END:VCALENDAR' . PHP_EOL;
756 * Get all events for a user ID.
758 * The query for events is done permission sensitive.
759 * If the user is the owner of the calendar they
760 * will get all of their available events.
761 * If the user is only a visitor only the public events will
764 * @param int $uid The user ID.
766 * @return array Query results.
769 private static function getListByUserId($uid = 0)
777 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
779 $conditions = ['uid' => $uid, 'cid' => 0];
781 // Does the user who requests happen to be the owner of the events
782 // requested? then show all of your events, otherwise only those that
783 // don't have limitations set in allow_cid and allow_gid.
784 if (local_user() != $uid) {
785 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
788 $events = DBA::select('event', $fields, $conditions);
789 if (DBA::isResult($events)) {
790 $return = DBA::toArray($events);
798 * @param int $uid The user ID.
799 * @param string $format Output format (ical/csv).
800 * @return array With the results:
801 * bool 'success' => True if the processing was successful,<br>
802 * string 'format' => The output format,<br>
803 * string 'extension' => The file extension of the output format,<br>
804 * string 'content' => The formatted output content.<br>
807 * @todo Respect authenticated users with events_by_uid().
809 public static function exportListByUserId($uid, $format = 'ical')
813 // Get all events which are owned by a uid (respects permissions).
814 $events = self::getListByUserId($uid);
816 // We have the events that are available for the requestor.
817 // Now format the output according to the requested format.
818 $res = self::formatListForExport($events, $format);
820 // If there are results the precess was successful.
825 // Get the file extension for the format.
840 'success' => $process,
842 'extension' => $file_ext,
850 * Format an item array with event data to HTML.
852 * @param array $item Array with item and event data.
853 * @return string HTML output.
854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
855 * @throws \ImagickException
857 public static function getItemHTML(array $item) {
861 // Set the different time formats.
862 $dformat = DI::l10n()->t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
863 $dformat_short = DI::l10n()->t('D g:i A'); // Fri 8:01 AM.
864 $tformat = DI::l10n()->t('g:i A'); // 8:01 AM.
866 // Convert the time to different formats.
867 $dtstart_dt = DI::l10n()->getDay(
868 $item['event-adjust'] ?
869 DateTimeFormat::local($item['event-start'], $dformat)
870 : DateTimeFormat::utc($item['event-start'], $dformat)
872 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
873 // Format: Jan till Dec.
874 $month_short = DI::l10n()->getDayShort(
875 $item['event-adjust'] ?
876 DateTimeFormat::local($item['event-start'], 'M')
877 : DateTimeFormat::utc($item['event-start'], 'M')
879 // Format: 1 till 31.
880 $date_short = $item['event-adjust'] ?
881 DateTimeFormat::local($item['event-start'], 'j')
882 : DateTimeFormat::utc($item['event-start'], 'j');
883 $start_time = $item['event-adjust'] ?
884 DateTimeFormat::local($item['event-start'], $tformat)
885 : DateTimeFormat::utc($item['event-start'], $tformat);
886 $start_short = DI::l10n()->getDayShort(
887 $item['event-adjust'] ?
888 DateTimeFormat::local($item['event-start'], $dformat_short)
889 : DateTimeFormat::utc($item['event-start'], $dformat_short)
892 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
893 if (!$item['event-nofinish']) {
895 $dtend_dt = DI::l10n()->getDay(
896 $item['event-adjust'] ?
897 DateTimeFormat::local($item['event-finish'], $dformat)
898 : DateTimeFormat::utc($item['event-finish'], $dformat)
900 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
901 $end_short = DI::l10n()->getDayShort(
902 $item['event-adjust'] ?
903 DateTimeFormat::local($item['event-finish'], $dformat_short)
904 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
906 $end_time = $item['event-adjust'] ?
907 DateTimeFormat::local($item['event-finish'], $tformat)
908 : DateTimeFormat::utc($item['event-finish'], $tformat);
909 // Check if start and finish time is at the same day.
910 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
920 // Format the event location.
921 $location = self::locationToArray($item['event-location']);
923 // Construct the profile link (magic-auth).
924 $profile_link = Contact::magicLinkById($item['author-id']);
926 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
927 $return = Renderer::replaceMacros($tpl, [
928 '$id' => $item['event-id'],
929 '$title' => BBCode::convert($item['event-summary']),
930 '$dtstart_label' => DI::l10n()->t('Starts:'),
931 '$dtstart_title' => $dtstart_title,
932 '$dtstart_dt' => $dtstart_dt,
933 '$finish' => $finish,
934 '$dtend_label' => DI::l10n()->t('Finishes:'),
935 '$dtend_title' => $dtend_title,
936 '$dtend_dt' => $dtend_dt,
937 '$month_short' => $month_short,
938 '$date_short' => $date_short,
939 '$same_date' => $same_date,
940 '$start_time' => $start_time,
941 '$start_short' => $start_short,
942 '$end_time' => $end_time,
943 '$end_short' => $end_short,
944 '$author_name' => $item['author-name'],
945 '$author_link' => $profile_link,
946 '$author_avatar' => $item['author-avatar'],
947 '$description' => BBCode::convert($item['event-desc']),
948 '$location_label' => DI::l10n()->t('Location:'),
949 '$show_map_label' => DI::l10n()->t('Show map'),
950 '$hide_map_label' => DI::l10n()->t('Hide map'),
951 '$map_btn_label' => DI::l10n()->t('Show map'),
952 '$location' => $location
959 * Format a string with map bbcode to an array with location data.
961 * Note: The string must only contain location data. A string with no bbcode will be
962 * handled as location name.
964 * @param string $s The string with the bbcode formatted location data.
966 * @return array The array with the location data.
967 * 'name' => The name of the location,<br>
968 * 'address' => The address of the location,<br>
969 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
970 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
972 private static function locationToArray($s = '') {
977 $location = ['name' => $s];
979 // Map tag with location name - e.g. [map]Paris[/map].
980 if (strpos($s, '[/map]') !== false) {
981 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
982 if (intval($found) > 0 && array_key_exists(1, $match)) {
983 $location['address'] = $match[1];
984 // Remove the map bbcode from the location name.
985 $location['name'] = str_replace($match[0], "", $s);
987 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
988 } elseif (strpos($s, '[map=') !== false) {
989 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
990 if (intval($found) > 0 && array_key_exists(1, $match)) {
991 $location['coordinates'] = $match[1];
992 // Remove the map bbcode from the location name.
993 $location['name'] = str_replace($match[0], "", $s);
997 $location['name'] = BBCode::convert($location['name']);
999 // Construct the map HTML.
1000 if (isset($location['address'])) {
1001 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
1002 } elseif (isset($location['coordinates'])) {
1003 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
1010 * Add new birthday event for this person
1012 * @param array $contact Contact array, expects: id, uid, url, name
1013 * @param string $birthday Birthday of the contact
1015 * @throws \Exception
1017 public static function createBirthday($contact, $birthday)
1019 // Check for duplicates
1021 'uid' => $contact['uid'],
1022 'cid' => $contact['id'],
1023 'start' => DateTimeFormat::utc($birthday),
1024 'type' => 'birthday'
1026 if (DBA::exists('event', $condition)) {
1031 * Add new birthday event for this person
1033 * summary is just a readable placeholder in case the event is shared
1034 * with others. We will replace it during presentation to our $importer
1035 * to contain a sparkle link and perhaps a photo.
1038 'uid' => $contact['uid'],
1039 'cid' => $contact['id'],
1040 'start' => DateTimeFormat::utc($birthday),
1041 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1042 'summary' => DI::l10n()->t('%s\'s birthday', $contact['name']),
1043 'desc' => DI::l10n()->t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1044 'type' => 'birthday',
1048 self::store($values);