3 * @file src/Model/Event.php
6 namespace Friendica\Model;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Hook;
10 use Friendica\Core\L10n;
11 use Friendica\Core\Logger;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\Renderer;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Protocol\Activity;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Map;
19 use Friendica\Util\Strings;
20 use Friendica\Util\XML;
23 * @brief functions for interacting with the event database table
28 public static function getHTML(array $event, $simple = false)
34 $bd_format = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8 AM.
36 $event_start = L10n::getDay(
37 !empty($event['adjust']) ?
38 DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
41 if (!empty($event['finish'])) {
42 $event_end = L10n::getDay(
43 !empty($event['adjust']) ?
44 DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
53 if (!empty($event['summary'])) {
54 $o .= "<h3>" . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . "</h3>";
57 if (!empty($event['desc'])) {
58 $o .= "<div>" . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . "</div>";
61 $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
63 if (!$event['nofinish']) {
64 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end . "</p>";
67 if (!empty($event['location'])) {
68 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple) . "</p>";
74 $o = '<div class="vevent">' . "\r\n";
76 $o .= '<div class="summary event-summary">' . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . '</div>' . "\r\n";
78 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
79 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
80 . '" >' . $event_start
81 . '</span></div>' . "\r\n";
83 if (!$event['nofinish']) {
84 $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
85 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
87 . '</span></div>' . "\r\n";
90 if (!empty($event['desc'])) {
91 $o .= '<div class="description event-description">' . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . '</div>' . "\r\n";
94 if (!empty($event['location'])) {
95 $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span> <span class="location">'
96 . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple)
97 . '</span></div>' . "\r\n";
99 // Include a map of the location if the [map] BBCode is used.
100 if (strpos($event['location'], "[map") !== false) {
101 $map = Map::byLocation($event['location'], $simple);
102 if ($map !== $event['location']) {
108 $o .= '</div>' . "\r\n";
113 * @brief Convert an array with event data to bbcode.
115 * @param array $event Array which contains the event data.
116 * @return string The event as a bbcode formatted string.
118 private static function getBBCode(array $event)
122 if ($event['summary']) {
123 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
126 if ($event['desc']) {
127 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
130 if ($event['start']) {
131 $o .= '[event-start]' . $event['start'] . '[/event-start]';
134 if (($event['finish']) && (!$event['nofinish'])) {
135 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
138 if ($event['location']) {
139 $o .= '[event-location]' . $event['location'] . '[/event-location]';
142 if ($event['adjust']) {
143 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
150 * @brief Extract bbcode formatted event data from a string.
152 * @params: string $s The string which should be parsed for event data.
154 * @return array The array with the event information.
156 public static function fromBBCode($text)
161 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
162 $ev['summary'] = $match[1];
166 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
167 $ev['desc'] = $match[1];
171 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
172 $ev['start'] = $match[1];
176 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
177 $ev['finish'] = $match[1];
181 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
182 $ev['location'] = $match[1];
186 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
187 $ev['adjust'] = $match[1];
190 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
195 public static function sortByDate($event_list)
197 usort($event_list, ['self', 'compareDatesCallback']);
201 private static function compareDatesCallback($event_a, $event_b)
203 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
204 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
206 if ($date_a === $date_b) {
207 return strcasecmp($event_a['desc'], $event_b['desc']);
210 return strcmp($date_a, $date_b);
214 * @brief Delete an event from the event table.
216 * Note: This function does only delete the event from the event table not its
217 * related entry in the item table.
219 * @param int $event_id Event ID.
223 public static function delete($event_id)
225 if ($event_id == 0) {
229 DBA::delete('event', ['id' => $event_id], ['cascade' => false]);
230 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
234 * @brief Store the event.
236 * Store the event in the event table and create an event item in the item table.
238 * @param array $arr Array with event data.
239 * @return int The new event id.
240 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
242 public static function store($arr)
245 $event['id'] = intval($arr['id'] ?? 0);
246 $event['uid'] = intval($arr['uid'] ?? 0);
247 $event['cid'] = intval($arr['cid'] ?? 0);
248 $event['guid'] = ($arr['guid'] ?? '') ?: System::createUUID();
249 $event['uri'] = ($arr['uri'] ?? '') ?: Item::newURI($event['uid'], $event['guid']);
250 $event['type'] = ($arr['type'] ?? '') ?: 'event';
251 $event['summary'] = $arr['summary'] ?? '';
252 $event['desc'] = $arr['desc'] ?? '';
253 $event['location'] = $arr['location'] ?? '';
254 $event['allow_cid'] = $arr['allow_cid'] ?? '';
255 $event['allow_gid'] = $arr['allow_gid'] ?? '';
256 $event['deny_cid'] = $arr['deny_cid'] ?? '';
257 $event['deny_gid'] = $arr['deny_gid'] ?? '';
258 $event['adjust'] = intval($arr['adjust'] ?? 0);
259 $event['nofinish'] = intval($arr['nofinish'] ?? (!empty($event['start']) && empty($event['finish'])));
261 $event['created'] = DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now');
262 $event['edited'] = DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now');
263 $event['start'] = DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME);
264 $event['finish'] = DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME);
265 if ($event['finish'] < DBA::NULL_DATETIME) {
266 $event['finish'] = DBA::NULL_DATETIME;
268 $private = intval($arr['private'] ?? 0);
270 $conditions = ['uid' => $event['uid']];
272 $conditions['id'] = $event['cid'];
274 $conditions['self'] = true;
277 $contact = DBA::selectFirst('contact', [], $conditions);
279 // Existing event being modified.
281 // has the event actually changed?
282 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
283 if (!DBA::isResult($existing_event) || ($existing_event['edited'] === $event['edited'])) {
285 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
287 return DBA::isResult($item) ? $item['id'] : 0;
291 'edited' => $event['edited'],
292 'start' => $event['start'],
293 'finish' => $event['finish'],
294 'summary' => $event['summary'],
295 'desc' => $event['desc'],
296 'location' => $event['location'],
297 'type' => $event['type'],
298 'adjust' => $event['adjust'],
299 'nofinish' => $event['nofinish'],
302 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
304 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
305 if (DBA::isResult($item)) {
306 $object = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
307 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
308 $object .= '</object>' . "\n";
310 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
311 Item::update($fields, ['id' => $item['id']]);
313 $item_id = $item['id'];
318 Hook::callAll('event_updated', $event['id']);
320 // New event. Store it.
321 DBA::insert('event', $event);
325 // Don't create an item for birthday events
326 if ($event['type'] == 'event') {
327 $event['id'] = DBA::lastInsertId();
331 $item_arr['uid'] = $event['uid'];
332 $item_arr['contact-id'] = $event['cid'];
333 $item_arr['uri'] = $event['uri'];
334 $item_arr['parent-uri'] = $event['uri'];
335 $item_arr['guid'] = $event['guid'];
336 $item_arr['plink'] = $arr['plink'] ?? '';
337 $item_arr['post-type'] = Item::PT_EVENT;
338 $item_arr['wall'] = $event['cid'] ? 0 : 1;
339 $item_arr['contact-id'] = $contact['id'];
340 $item_arr['owner-name'] = $contact['name'];
341 $item_arr['owner-link'] = $contact['url'];
342 $item_arr['owner-avatar'] = $contact['thumb'];
343 $item_arr['author-name'] = $contact['name'];
344 $item_arr['author-link'] = $contact['url'];
345 $item_arr['author-avatar'] = $contact['thumb'];
346 $item_arr['title'] = '';
347 $item_arr['allow_cid'] = $event['allow_cid'];
348 $item_arr['allow_gid'] = $event['allow_gid'];
349 $item_arr['deny_cid'] = $event['deny_cid'];
350 $item_arr['deny_gid'] = $event['deny_gid'];
351 $item_arr['private'] = $private;
352 $item_arr['visible'] = 1;
353 $item_arr['verb'] = Activity::POST;
354 $item_arr['object-type'] = Activity\ObjectType::EVENT;
355 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
356 $item_arr['body'] = self::getBBCode($event);
357 $item_arr['event-id'] = $event['id'];
359 $item_arr['object'] = '<object><type>' . XML::escape(Activity\ObjectType::EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
360 $item_arr['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
361 $item_arr['object'] .= '</object>' . "\n";
363 $item_id = Item::insert($item_arr);
366 Hook::callAll("event_created", $event['id']);
373 * @brief Create an array with translation strings used for events.
375 * @return array Array with translations strings.
376 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
378 public static function getStrings()
380 // First day of the week (0 = Sunday).
381 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
384 "firstDay" => $firstDay,
385 "allday" => L10n::t("all-day"),
387 "Sun" => L10n::t("Sun"),
388 "Mon" => L10n::t("Mon"),
389 "Tue" => L10n::t("Tue"),
390 "Wed" => L10n::t("Wed"),
391 "Thu" => L10n::t("Thu"),
392 "Fri" => L10n::t("Fri"),
393 "Sat" => L10n::t("Sat"),
395 "Sunday" => L10n::t("Sunday"),
396 "Monday" => L10n::t("Monday"),
397 "Tuesday" => L10n::t("Tuesday"),
398 "Wednesday" => L10n::t("Wednesday"),
399 "Thursday" => L10n::t("Thursday"),
400 "Friday" => L10n::t("Friday"),
401 "Saturday" => L10n::t("Saturday"),
403 "Jan" => L10n::t("Jan"),
404 "Feb" => L10n::t("Feb"),
405 "Mar" => L10n::t("Mar"),
406 "Apr" => L10n::t("Apr"),
407 "May" => L10n::t("May"),
408 "Jun" => L10n::t("Jun"),
409 "Jul" => L10n::t("Jul"),
410 "Aug" => L10n::t("Aug"),
411 "Sep" => L10n::t("Sept"),
412 "Oct" => L10n::t("Oct"),
413 "Nov" => L10n::t("Nov"),
414 "Dec" => L10n::t("Dec"),
416 "January" => L10n::t("January"),
417 "February" => L10n::t("February"),
418 "March" => L10n::t("March"),
419 "April" => L10n::t("April"),
420 "June" => L10n::t("June"),
421 "July" => L10n::t("July"),
422 "August" => L10n::t("August"),
423 "September" => L10n::t("September"),
424 "October" => L10n::t("October"),
425 "November" => L10n::t("November"),
426 "December" => L10n::t("December"),
428 "today" => L10n::t("today"),
429 "month" => L10n::t("month"),
430 "week" => L10n::t("week"),
431 "day" => L10n::t("day"),
433 "noevent" => L10n::t("No events to display"),
435 "dtstart_label" => L10n::t("Starts:"),
436 "dtend_label" => L10n::t("Finishes:"),
437 "location_label" => L10n::t("Location:")
444 * @brief Removes duplicated birthday events.
446 * @param array $dates Array of possibly duplicated events.
447 * @return array Cleaned events.
449 * @todo We should replace this with a separate update function if there is some time left.
451 private static function removeDuplicates(array $dates)
455 foreach ($dates as $date) {
456 if ($date['type'] == 'birthday') {
457 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
462 return array_values($dates2);
466 * @brief Get an event by its event ID.
468 * @param int $owner_uid The User ID of the owner of the event
469 * @param int $event_id The ID of the event in the event table
470 * @param string $sql_extra
471 * @return array Query result
474 public static function getListById($owner_uid, $event_id, $sql_extra = '')
478 // Ownly allow events if there is a valid owner_id.
479 if ($owner_uid == 0) {
483 // Query for the event by event id
484 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
485 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
486 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
491 if (DBA::isResult($r)) {
492 $return = self::removeDuplicates($r);
499 * @brief Get all events in a specific time frame.
501 * @param int $owner_uid The User ID of the owner of the events.
502 * @param array $event_params An associative array with
504 * string 'start' => Start time of the timeframe.
505 * string 'finish' => Finish time of the timeframe.
506 * string 'adjust_start' =>
507 * string 'adjust_finish' =>
509 * @param string $sql_extra Additional sql conditions (e.g. permission request).
511 * @return array Query results.
514 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
518 // Only allow events if there is a valid owner_id.
519 if ($owner_uid == 0) {
523 // Query for the event by date.
524 // @todo Slow query (518 seconds to run), to be optimzed
525 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
526 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
527 WHERE `event`.`uid` = %d AND event.ignore = %d
528 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
529 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
532 intval($event_params["ignore"]),
533 DBA::escape($event_params["start"]),
534 DBA::escape($event_params["start"]),
535 DBA::escape($event_params["finish"]),
536 DBA::escape($event_params["adjust_start"]),
537 DBA::escape($event_params["adjust_start"]),
538 DBA::escape($event_params["adjust_finish"])
541 if (DBA::isResult($r)) {
542 $return = self::removeDuplicates($r);
549 * @brief Convert an array query results in an array which could be used by the events template.
551 * @param array $event_result Event query array.
552 * @return array Event array for the template.
553 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
554 * @throws \ImagickException
556 public static function prepareListForTemplate(array $event_result)
561 $fmt = L10n::t('l, F j');
562 foreach ($event_result as $event) {
563 $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
564 if (!DBA::isResult($item)) {
565 // Using default values when no item had been found
566 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
569 $event = array_merge($event, $item);
571 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
572 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
573 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
574 $day = L10n::getDay($day);
576 if ($event['nofinish']) {
579 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
582 $is_first = ($day !== $last_date);
586 // Show edit and drop actions only if the user is the owner of the event and the event
587 // is a real event (no bithdays).
591 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
592 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event') , '', ''] : null;
593 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
594 $drop = [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event') , '', ''];
597 $title = BBCode::convert(Strings::escapeHtml($event['summary']));
599 list($title, $_trash) = explode("<br", BBCode::convert(Strings::escapeHtml($event['desc'])), 2);
602 $author_link = $event['author-link'];
603 $plink = $event['plink'];
605 $event['author-link'] = Contact::magicLink($author_link);
606 $event['plink'] = Contact::magicLink($author_link, $plink);
608 $html = self::getHTML($event);
609 $event['summary'] = BBCode::convert(Strings::escapeHtml($event['summary']));
610 $event['desc'] = BBCode::convert(Strings::escapeHtml($event['desc']));
611 $event['location'] = BBCode::convert(Strings::escapeHtml($event['location']));
613 'id' => $event['id'],
623 'is_first' => $is_first,
626 'plink' => [$event['plink'], L10n::t('link to source'), '', ''],
634 * @brief Format event to export format (ical/csv).
636 * @param array $events Query result for events.
637 * @param string $format The output format (ical/csv).
640 * @return string Content according to selected export format.
642 * @todo Implement timezone support
644 private static function formatListForExport(array $events, $format)
648 if (!count($events)) {
653 // Format the exported data as a CSV file.
655 header("Content-type: text/csv");
656 $o .= '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
658 foreach ($events as $event) {
659 /// @todo The time / date entries don't include any information about the
660 /// timezone the event is scheduled in :-/
661 $tmp1 = strtotime($event['start']);
662 $tmp2 = strtotime($event['finish']);
663 $time_format = "%H:%M:%S";
664 $date_format = "%Y-%m-%d";
666 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
667 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
668 '", "' . strftime($date_format, $tmp2) .
669 '", "' . strftime($time_format, $tmp2) .
670 '", "' . $event['location'] . '"' . PHP_EOL;
674 // Format the exported data as a ics file.
676 header("Content-type: text/ics");
677 $o = 'BEGIN:VCALENDAR' . PHP_EOL
678 . 'VERSION:2.0' . PHP_EOL
679 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
680 /// @todo include timezone informations in cases were the time is not in UTC
681 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
682 // . 'BEGIN:VTIMEZONE' . PHP_EOL
683 // . 'TZID:' . $timezone . PHP_EOL
684 // . 'END:VTIMEZONE' . PHP_EOL;
685 // TODO instead of PHP_EOL CRLF should be used for long entries
686 // but test your solution against http://icalvalid.cloudapp.net/
687 // also long lines SHOULD be split at 75 characters length
688 foreach ($events as $event) {
689 if ($event['adjust'] == 1) {
694 $o .= 'BEGIN:VEVENT' . PHP_EOL;
696 if ($event['start']) {
697 $tmp = strtotime($event['start']);
698 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
699 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
702 if (!$event['nofinish']) {
703 $tmp = strtotime($event['finish']);
704 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
705 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
708 if ($event['summary']) {
709 $tmp = $event['summary'];
710 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
711 $tmp = addcslashes($tmp, ',;');
712 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
715 if ($event['desc']) {
716 $tmp = $event['desc'];
717 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
718 $tmp = addcslashes($tmp, ',;');
719 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
722 if ($event['location']) {
723 $tmp = $event['location'];
724 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
725 $tmp = addcslashes($tmp, ',;');
726 $o .= 'LOCATION:' . $tmp . PHP_EOL;
729 $o .= 'END:VEVENT' . PHP_EOL;
733 $o .= 'END:VCALENDAR' . PHP_EOL;
741 * @brief Get all events for a user ID.
743 * The query for events is done permission sensitive.
744 * If the user is the owner of the calendar they
745 * will get all of their available events.
746 * If the user is only a visitor only the public events will
749 * @param int $uid The user ID.
751 * @return array Query results.
754 private static function getListByUserId($uid = 0)
762 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
764 $conditions = ['uid' => $uid, 'cid' => 0];
766 // Does the user who requests happen to be the owner of the events
767 // requested? then show all of your events, otherwise only those that
768 // don't have limitations set in allow_cid and allow_gid.
769 if (local_user() != $uid) {
770 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
773 $events = DBA::select('event', $fields, $conditions);
774 if (DBA::isResult($events)) {
775 $return = DBA::toArray($events);
783 * @param int $uid The user ID.
784 * @param string $format Output format (ical/csv).
785 * @return array With the results:
786 * bool 'success' => True if the processing was successful,<br>
787 * string 'format' => The output format,<br>
788 * string 'extension' => The file extension of the output format,<br>
789 * string 'content' => The formatted output content.<br>
792 * @todo Respect authenticated users with events_by_uid().
794 public static function exportListByUserId($uid, $format = 'ical')
798 // Get all events which are owned by a uid (respects permissions).
799 $events = self::getListByUserId($uid);
801 // We have the events that are available for the requestor.
802 // Now format the output according to the requested format.
803 $res = self::formatListForExport($events, $format);
805 // If there are results the precess was successful.
810 // Get the file extension for the format.
825 'success' => $process,
827 'extension' => $file_ext,
835 * @brief Format an item array with event data to HTML.
837 * @param array $item Array with item and event data.
838 * @return string HTML output.
839 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
840 * @throws \ImagickException
842 public static function getItemHTML(array $item) {
846 // Set the different time formats.
847 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
848 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
849 $tformat = L10n::t('g:i A'); // 8:01 AM.
851 // Convert the time to different formats.
852 $dtstart_dt = L10n::getDay(
853 $item['event-adjust'] ?
854 DateTimeFormat::local($item['event-start'], $dformat)
855 : DateTimeFormat::utc($item['event-start'], $dformat)
857 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
858 // Format: Jan till Dec.
859 $month_short = L10n::getDayShort(
860 $item['event-adjust'] ?
861 DateTimeFormat::local($item['event-start'], 'M')
862 : DateTimeFormat::utc($item['event-start'], 'M')
864 // Format: 1 till 31.
865 $date_short = $item['event-adjust'] ?
866 DateTimeFormat::local($item['event-start'], 'j')
867 : DateTimeFormat::utc($item['event-start'], 'j');
868 $start_time = $item['event-adjust'] ?
869 DateTimeFormat::local($item['event-start'], $tformat)
870 : DateTimeFormat::utc($item['event-start'], $tformat);
871 $start_short = L10n::getDayShort(
872 $item['event-adjust'] ?
873 DateTimeFormat::local($item['event-start'], $dformat_short)
874 : DateTimeFormat::utc($item['event-start'], $dformat_short)
877 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
878 if (!$item['event-nofinish']) {
880 $dtend_dt = L10n::getDay(
881 $item['event-adjust'] ?
882 DateTimeFormat::local($item['event-finish'], $dformat)
883 : DateTimeFormat::utc($item['event-finish'], $dformat)
885 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
886 $end_short = L10n::getDayShort(
887 $item['event-adjust'] ?
888 DateTimeFormat::local($item['event-finish'], $dformat_short)
889 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
891 $end_time = $item['event-adjust'] ?
892 DateTimeFormat::local($item['event-finish'], $tformat)
893 : DateTimeFormat::utc($item['event-finish'], $tformat);
894 // Check if start and finish time is at the same day.
895 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
905 // Format the event location.
906 $location = self::locationToArray($item['event-location']);
908 // Construct the profile link (magic-auth).
909 $profile_link = Contact::magicLinkById($item['author-id']);
911 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
912 $return = Renderer::replaceMacros($tpl, [
913 '$id' => $item['event-id'],
914 '$title' => BBCode::convert($item['event-summary']),
915 '$dtstart_label' => L10n::t('Starts:'),
916 '$dtstart_title' => $dtstart_title,
917 '$dtstart_dt' => $dtstart_dt,
918 '$finish' => $finish,
919 '$dtend_label' => L10n::t('Finishes:'),
920 '$dtend_title' => $dtend_title,
921 '$dtend_dt' => $dtend_dt,
922 '$month_short' => $month_short,
923 '$date_short' => $date_short,
924 '$same_date' => $same_date,
925 '$start_time' => $start_time,
926 '$start_short' => $start_short,
927 '$end_time' => $end_time,
928 '$end_short' => $end_short,
929 '$author_name' => $item['author-name'],
930 '$author_link' => $profile_link,
931 '$author_avatar' => $item['author-avatar'],
932 '$description' => BBCode::convert($item['event-desc']),
933 '$location_label' => L10n::t('Location:'),
934 '$show_map_label' => L10n::t('Show map'),
935 '$hide_map_label' => L10n::t('Hide map'),
936 '$map_btn_label' => L10n::t('Show map'),
937 '$location' => $location
944 * @brief Format a string with map bbcode to an array with location data.
946 * Note: The string must only contain location data. A string with no bbcode will be
947 * handled as location name.
949 * @param string $s The string with the bbcode formatted location data.
951 * @return array The array with the location data.
952 * 'name' => The name of the location,<br>
953 * 'address' => The address of the location,<br>
954 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
955 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957 private static function locationToArray($s = '') {
962 $location = ['name' => $s];
964 // Map tag with location name - e.g. [map]Paris[/map].
965 if (strpos($s, '[/map]') !== false) {
966 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
967 if (intval($found) > 0 && array_key_exists(1, $match)) {
968 $location['address'] = $match[1];
969 // Remove the map bbcode from the location name.
970 $location['name'] = str_replace($match[0], "", $s);
972 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
973 } elseif (strpos($s, '[map=') !== false) {
974 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
975 if (intval($found) > 0 && array_key_exists(1, $match)) {
976 $location['coordinates'] = $match[1];
977 // Remove the map bbcode from the location name.
978 $location['name'] = str_replace($match[0], "", $s);
982 $location['name'] = BBCode::convert($location['name']);
984 // Construct the map HTML.
985 if (isset($location['address'])) {
986 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
987 } elseif (isset($location['coordinates'])) {
988 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
995 * @brief Add new birthday event for this person
997 * @param array $contact Contact array, expects: id, uid, url, name
998 * @param string $birthday Birthday of the contact
1000 * @throws \Exception
1002 public static function createBirthday($contact, $birthday)
1004 // Check for duplicates
1006 'uid' => $contact['uid'],
1007 'cid' => $contact['id'],
1008 'start' => DateTimeFormat::utc($birthday),
1009 'type' => 'birthday'
1011 if (DBA::exists('event', $condition)) {
1016 * Add new birthday event for this person
1018 * summary is just a readable placeholder in case the event is shared
1019 * with others. We will replace it during presentation to our $importer
1020 * to contain a sparkle link and perhaps a photo.
1023 'uid' => $contact['uid'],
1024 'cid' => $contact['id'],
1025 'start' => DateTimeFormat::utc($birthday),
1026 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1027 'summary' => L10n::t('%s\'s birthday', $contact['name']),
1028 'desc' => L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1029 'type' => 'birthday',
1033 self::store($values);