3 * @file src/Model/Event.php
6 namespace Friendica\Model;
8 use Friendica\BaseObject;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
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
25 class Event extends BaseObject
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)
51 if (!empty($event['summary'])) {
52 $o = "<h3>" . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . "</h3>";
55 if (!empty($event['desc'])) {
56 $o .= "<div>" . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . "</div>";
59 $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
61 if (!$event['nofinish']) {
62 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end . "</p>";
65 if (!empty($event['location'])) {
66 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple) . "</p>";
72 $o = '<div class="vevent">' . "\r\n";
74 $o .= '<div class="summary event-summary">' . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . '</div>' . "\r\n";
76 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
77 . DateTimeFormat::utc($event['start'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
78 . '" >' . $event_start
79 . '</span></div>' . "\r\n";
81 if (!$event['nofinish']) {
82 $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
83 . DateTimeFormat::utc($event['finish'], (!empty($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
85 . '</span></div>' . "\r\n";
88 if (!empty($event['desc'])) {
89 $o .= '<div class="description event-description">' . BBCode::convert(Strings::escapeHtml($event['desc']), false, $simple) . '</div>' . "\r\n";
92 if (!empty($event['location'])) {
93 $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span> <span class="location">'
94 . BBCode::convert(Strings::escapeHtml($event['location']), false, $simple)
95 . '</span></div>' . "\r\n";
97 // Include a map of the location if the [map] BBCode is used.
98 if (strpos($event['location'], "[map") !== false) {
99 $map = Map::byLocation($event['location'], $simple);
100 if ($map !== $event['location']) {
106 $o .= '</div>' . "\r\n";
111 * @brief Convert an array with event data to bbcode.
113 * @param array $event Array which contains the event data.
114 * @return string The event as a bbcode formatted string.
116 private static function getBBCode(array $event)
120 if ($event['summary']) {
121 $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
124 if ($event['desc']) {
125 $o .= '[event-description]' . $event['desc'] . '[/event-description]';
128 if ($event['start']) {
129 $o .= '[event-start]' . $event['start'] . '[/event-start]';
132 if (($event['finish']) && (!$event['nofinish'])) {
133 $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
136 if ($event['location']) {
137 $o .= '[event-location]' . $event['location'] . '[/event-location]';
140 if ($event['adjust']) {
141 $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
148 * @brief Extract bbcode formatted event data from a string.
150 * @params: string $s The string which should be parsed for event data.
152 * @return array The array with the event information.
154 public static function fromBBCode($text)
159 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
160 $ev['summary'] = $match[1];
164 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
165 $ev['desc'] = $match[1];
169 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
170 $ev['start'] = $match[1];
174 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
175 $ev['finish'] = $match[1];
179 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
180 $ev['location'] = $match[1];
184 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
185 $ev['adjust'] = $match[1];
188 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
193 public static function sortByDate($event_list)
195 usort($event_list, ['self', 'compareDatesCallback']);
199 private static function compareDatesCallback($event_a, $event_b)
201 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
202 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
204 if ($date_a === $date_b) {
205 return strcasecmp($event_a['desc'], $event_b['desc']);
208 return strcmp($date_a, $date_b);
212 * @brief Delete an event from the event table.
214 * Note: This function does only delete the event from the event table not its
215 * related entry in the item table.
217 * @param int $event_id Event ID.
221 public static function delete($event_id)
223 if ($event_id == 0) {
227 DBA::delete('event', ['id' => $event_id]);
228 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
232 * @brief Store the event.
234 * Store the event in the event table and create an event item in the item table.
236 * @param array $arr Array with event data.
237 * @return int The new event id.
238 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
240 public static function store($arr)
243 $event['id'] = intval(defaults($arr, 'id' , 0));
244 $event['uid'] = intval(defaults($arr, 'uid' , 0));
245 $event['cid'] = intval(defaults($arr, 'cid' , 0));
246 $event['uri'] = defaults($arr, 'uri' , Item::newURI($event['uid']));
247 $event['type'] = defaults($arr, 'type' , 'event');
248 $event['summary'] = defaults($arr, 'summary' , '');
249 $event['desc'] = defaults($arr, 'desc' , '');
250 $event['location'] = defaults($arr, 'location' , '');
251 $event['allow_cid'] = defaults($arr, 'allow_cid', '');
252 $event['allow_gid'] = defaults($arr, 'allow_gid', '');
253 $event['deny_cid'] = defaults($arr, 'deny_cid' , '');
254 $event['deny_gid'] = defaults($arr, 'deny_gid' , '');
255 $event['adjust'] = intval(defaults($arr, 'adjust' , 0));
256 $event['nofinish'] = intval(defaults($arr, 'nofinish' , !empty($event['start']) && empty($event['finish'])));
258 $event['created'] = DateTimeFormat::utc(defaults($arr, 'created' , 'now'));
259 $event['edited'] = DateTimeFormat::utc(defaults($arr, 'edited' , 'now'));
260 $event['start'] = DateTimeFormat::utc(defaults($arr, 'start' , DBA::NULL_DATETIME));
261 $event['finish'] = DateTimeFormat::utc(defaults($arr, 'finish' , DBA::NULL_DATETIME));
262 if ($event['finish'] < DBA::NULL_DATETIME) {
263 $event['finish'] = DBA::NULL_DATETIME;
265 $private = intval(defaults($arr, 'private', 0));
267 $conditions = ['uid' => $event['uid']];
269 $conditions['id'] = $event['cid'];
271 $conditions['self'] = true;
274 $contact = DBA::selectFirst('contact', [], $conditions);
276 // Existing event being modified.
278 // has the event actually changed?
279 $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
280 if (!DBA::isResult($existing_event) || ($existing_event['edited'] === $event['edited'])) {
282 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
284 return DBA::isResult($item) ? $item['id'] : 0;
288 'edited' => $event['edited'],
289 'start' => $event['start'],
290 'finish' => $event['finish'],
291 'summary' => $event['summary'],
292 'desc' => $event['desc'],
293 'location' => $event['location'],
294 'type' => $event['type'],
295 'adjust' => $event['adjust'],
296 'nofinish' => $event['nofinish'],
299 DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
301 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
302 if (DBA::isResult($item)) {
303 $object = '<object><type>' . XML::escape(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
304 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
305 $object .= '</object>' . "\n";
307 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
308 Item::update($fields, ['id' => $item['id']]);
310 $item_id = $item['id'];
315 Hook::callAll('event_updated', $event['id']);
317 $event['guid'] = defaults($arr, 'guid', System::createUUID());
319 // New event. Store it.
320 DBA::insert('event', $event);
324 // Don't create an item for birthday events
325 if ($event['type'] == 'event') {
326 $event['id'] = DBA::lastInsertId();
330 $item_arr['uid'] = $event['uid'];
331 $item_arr['contact-id'] = $event['cid'];
332 $item_arr['uri'] = $event['uri'];
333 $item_arr['parent-uri'] = $event['uri'];
334 $item_arr['guid'] = $event['guid'];
335 $item_arr['plink'] = defaults($arr, 'plink', '');
336 $item_arr['post-type'] = Item::PT_EVENT;
337 $item_arr['wall'] = $event['cid'] ? 0 : 1;
338 $item_arr['contact-id'] = $contact['id'];
339 $item_arr['owner-name'] = $contact['name'];
340 $item_arr['owner-link'] = $contact['url'];
341 $item_arr['owner-avatar'] = $contact['thumb'];
342 $item_arr['author-name'] = $contact['name'];
343 $item_arr['author-link'] = $contact['url'];
344 $item_arr['author-avatar'] = $contact['thumb'];
345 $item_arr['title'] = '';
346 $item_arr['allow_cid'] = $event['allow_cid'];
347 $item_arr['allow_gid'] = $event['allow_gid'];
348 $item_arr['deny_cid'] = $event['deny_cid'];
349 $item_arr['deny_gid'] = $event['deny_gid'];
350 $item_arr['private'] = $private;
351 $item_arr['visible'] = 1;
352 $item_arr['verb'] = ACTIVITY_POST;
353 $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
354 $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0;
355 $item_arr['body'] = self::getBBCode($event);
356 $item_arr['event-id'] = $event['id'];
358 $item_arr['object'] = '<object><type>' . XML::escape(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
359 $item_arr['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
360 $item_arr['object'] .= '</object>' . "\n";
362 $item_id = Item::insert($item_arr);
365 Hook::callAll("event_created", $event['id']);
372 * @brief Create an array with translation strings used for events.
374 * @return array Array with translations strings.
375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
377 public static function getStrings()
379 // First day of the week (0 = Sunday).
380 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
383 "firstDay" => $firstDay,
384 "allday" => L10n::t("all-day"),
386 "Sun" => L10n::t("Sun"),
387 "Mon" => L10n::t("Mon"),
388 "Tue" => L10n::t("Tue"),
389 "Wed" => L10n::t("Wed"),
390 "Thu" => L10n::t("Thu"),
391 "Fri" => L10n::t("Fri"),
392 "Sat" => L10n::t("Sat"),
394 "Sunday" => L10n::t("Sunday"),
395 "Monday" => L10n::t("Monday"),
396 "Tuesday" => L10n::t("Tuesday"),
397 "Wednesday" => L10n::t("Wednesday"),
398 "Thursday" => L10n::t("Thursday"),
399 "Friday" => L10n::t("Friday"),
400 "Saturday" => L10n::t("Saturday"),
402 "Jan" => L10n::t("Jan"),
403 "Feb" => L10n::t("Feb"),
404 "Mar" => L10n::t("Mar"),
405 "Apr" => L10n::t("Apr"),
406 "May" => L10n::t("May"),
407 "Jun" => L10n::t("Jun"),
408 "Jul" => L10n::t("Jul"),
409 "Aug" => L10n::t("Aug"),
410 "Sep" => L10n::t("Sept"),
411 "Oct" => L10n::t("Oct"),
412 "Nov" => L10n::t("Nov"),
413 "Dec" => L10n::t("Dec"),
415 "January" => L10n::t("January"),
416 "February" => L10n::t("February"),
417 "March" => L10n::t("March"),
418 "April" => L10n::t("April"),
419 "June" => L10n::t("June"),
420 "July" => L10n::t("July"),
421 "August" => L10n::t("August"),
422 "September" => L10n::t("September"),
423 "October" => L10n::t("October"),
424 "November" => L10n::t("November"),
425 "December" => L10n::t("December"),
427 "today" => L10n::t("today"),
428 "month" => L10n::t("month"),
429 "week" => L10n::t("week"),
430 "day" => L10n::t("day"),
432 "noevent" => L10n::t("No events to display"),
434 "dtstart_label" => L10n::t("Starts:"),
435 "dtend_label" => L10n::t("Finishes:"),
436 "location_label" => L10n::t("Location:")
443 * @brief Removes duplicated birthday events.
445 * @param array $dates Array of possibly duplicated events.
446 * @return array Cleaned events.
448 * @todo We should replace this with a separate update function if there is some time left.
450 private static function removeDuplicates(array $dates)
454 foreach ($dates as $date) {
455 if ($date['type'] == 'birthday') {
456 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
461 return array_values($dates2);
465 * @brief Get an event by its event ID.
467 * @param int $owner_uid The User ID of the owner of the event
468 * @param int $event_id The ID of the event in the event table
469 * @param string $sql_extra
470 * @return array Query result
473 public static function getListById($owner_uid, $event_id, $sql_extra = '')
477 // Ownly allow events if there is a valid owner_id.
478 if ($owner_uid == 0) {
482 // Query for the event by event id
483 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
484 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
485 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
490 if (DBA::isResult($r)) {
491 $return = self::removeDuplicates($r);
498 * @brief Get all events in a specific time frame.
500 * @param int $owner_uid The User ID of the owner of the events.
501 * @param array $event_params An associative array with
503 * string 'start' => Start time of the timeframe.
504 * string 'finish' => Finish time of the timeframe.
505 * string 'adjust_start' =>
506 * string 'adjust_finish' =>
508 * @param string $sql_extra Additional sql conditions (e.g. permission request).
510 * @return array Query results.
513 public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
517 // Only allow events if there is a valid owner_id.
518 if ($owner_uid == 0) {
522 // Query for the event by date.
523 // @todo Slow query (518 seconds to run), to be optimzed
524 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
525 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
526 WHERE `event`.`uid` = %d AND event.ignore = %d
527 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
528 OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
531 intval($event_params["ignore"]),
532 DBA::escape($event_params["start"]),
533 DBA::escape($event_params["start"]),
534 DBA::escape($event_params["finish"]),
535 DBA::escape($event_params["adjust_start"]),
536 DBA::escape($event_params["adjust_start"]),
537 DBA::escape($event_params["adjust_finish"])
540 if (DBA::isResult($r)) {
541 $return = self::removeDuplicates($r);
548 * @brief Convert an array query results in an array which could be used by the events template.
550 * @param array $event_result Event query array.
551 * @return array Event array for the template.
552 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
553 * @throws \ImagickException
555 public static function prepareListForTemplate(array $event_result)
560 $fmt = L10n::t('l, F j');
561 foreach ($event_result as $event) {
562 $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
563 if (!DBA::isResult($item)) {
564 // Using default values when no item had been found
565 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
568 $event = array_merge($event, $item);
570 $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
571 $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
572 $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
573 $day = L10n::getDay($day);
575 if ($event['nofinish']) {
578 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
581 $is_first = ($day !== $last_date);
585 // Show edit and drop actions only if the user is the owner of the event and the event
586 // is a real event (no bithdays).
590 if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
591 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event') , '', ''] : null;
592 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
593 $drop = [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event') , '', ''];
596 $title = BBCode::convert(Strings::escapeHtml($event['summary']));
598 list($title, $_trash) = explode("<br", BBCode::convert(Strings::escapeHtml($event['desc'])), 2);
601 $author_link = $event['author-link'];
602 $plink = $event['plink'];
604 $event['author-link'] = Contact::magicLink($author_link);
605 $event['plink'] = Contact::magicLink($author_link, $plink);
607 $html = self::getHTML($event);
608 $event['summary'] = BBCode::convert(Strings::escapeHtml($event['summary']));
609 $event['desc'] = BBCode::convert(Strings::escapeHtml($event['desc']));
610 $event['location'] = BBCode::convert(Strings::escapeHtml($event['location']));
612 'id' => $event['id'],
622 'is_first' => $is_first,
625 'plink' => [$event['plink'], L10n::t('link to source'), '', ''],
633 * @brief Format event to export format (ical/csv).
635 * @param array $events Query result for events.
636 * @param string $format The output format (ical/csv).
639 * @return string Content according to selected export format.
641 * @todo Implement timezone support
643 private static function formatListForExport(array $events, $format)
645 if (!count($events)) {
650 // Format the exported data as a CSV file.
652 header("Content-type: text/csv");
653 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
655 foreach ($events as $event) {
656 /// @todo The time / date entries don't include any information about the
657 /// timezone the event is scheduled in :-/
658 $tmp1 = strtotime($event['start']);
659 $tmp2 = strtotime($event['finish']);
660 $time_format = "%H:%M:%S";
661 $date_format = "%Y-%m-%d";
663 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
664 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
665 '", "' . strftime($date_format, $tmp2) .
666 '", "' . strftime($time_format, $tmp2) .
667 '", "' . $event['location'] . '"' . PHP_EOL;
671 // Format the exported data as a ics file.
673 header("Content-type: text/ics");
674 $o = 'BEGIN:VCALENDAR' . PHP_EOL
675 . 'VERSION:2.0' . PHP_EOL
676 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
677 /// @todo include timezone informations in cases were the time is not in UTC
678 // see http://tools.ietf.org/html/rfc2445#section-4.8.3
679 // . 'BEGIN:VTIMEZONE' . PHP_EOL
680 // . 'TZID:' . $timezone . PHP_EOL
681 // . 'END:VTIMEZONE' . PHP_EOL;
682 // TODO instead of PHP_EOL CRLF should be used for long entries
683 // but test your solution against http://icalvalid.cloudapp.net/
684 // also long lines SHOULD be split at 75 characters length
685 foreach ($events as $event) {
686 if ($event['adjust'] == 1) {
691 $o .= 'BEGIN:VEVENT' . PHP_EOL;
693 if ($event['start']) {
694 $tmp = strtotime($event['start']);
695 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
696 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
699 if (!$event['nofinish']) {
700 $tmp = strtotime($event['finish']);
701 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
702 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
705 if ($event['summary']) {
706 $tmp = $event['summary'];
707 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
708 $tmp = addcslashes($tmp, ',;');
709 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
712 if ($event['desc']) {
713 $tmp = $event['desc'];
714 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
715 $tmp = addcslashes($tmp, ',;');
716 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
719 if ($event['location']) {
720 $tmp = $event['location'];
721 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
722 $tmp = addcslashes($tmp, ',;');
723 $o .= 'LOCATION:' . $tmp . PHP_EOL;
726 $o .= 'END:VEVENT' . PHP_EOL;
730 $o .= 'END:VCALENDAR' . PHP_EOL;
738 * @brief Get all events for a user ID.
740 * The query for events is done permission sensitive.
741 * If the user is the owner of the calendar they
742 * will get all of their available events.
743 * If the user is only a visitor only the public events will
746 * @param int $uid The user ID.
748 * @return array Query results.
751 private static function getListByUserId($uid = 0)
759 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
761 $conditions = ['uid' => $uid, 'cid' => 0];
763 // Does the user who requests happen to be the owner of the events
764 // requested? then show all of your events, otherwise only those that
765 // don't have limitations set in allow_cid and allow_gid.
766 if (local_user() != $uid) {
767 $conditions += ['allow_cid' => '', 'allow_gid' => ''];
770 $events = DBA::select('event', $fields, $conditions);
771 if (DBA::isResult($events)) {
772 $return = DBA::toArray($events);
780 * @param int $uid The user ID.
781 * @param string $format Output format (ical/csv).
782 * @return array With the results:
783 * bool 'success' => True if the processing was successful,<br>
784 * string 'format' => The output format,<br>
785 * string 'extension' => The file extension of the output format,<br>
786 * string 'content' => The formatted output content.<br>
789 * @todo Respect authenticated users with events_by_uid().
791 public static function exportListByUserId($uid, $format = 'ical')
795 // Get all events which are owned by a uid (respects permissions).
796 $events = self::getListByUserId($uid);
798 // We have the events that are available for the requestor.
799 // Now format the output according to the requested format.
800 $res = self::formatListForExport($events, $format);
802 // If there are results the precess was successful.
807 // Get the file extension for the format.
822 'success' => $process,
824 'extension' => $file_ext,
832 * @brief Format an item array with event data to HTML.
834 * @param array $item Array with item and event data.
835 * @return string HTML output.
836 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
837 * @throws \ImagickException
839 public static function getItemHTML(array $item) {
843 // Set the different time formats.
844 $dformat = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
845 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
846 $tformat = L10n::t('g:i A'); // 8:01 AM.
848 // Convert the time to different formats.
849 $dtstart_dt = L10n::getDay(
850 $item['event-adjust'] ?
851 DateTimeFormat::local($item['event-start'], $dformat)
852 : DateTimeFormat::utc($item['event-start'], $dformat)
854 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
855 // Format: Jan till Dec.
856 $month_short = L10n::getDayShort(
857 $item['event-adjust'] ?
858 DateTimeFormat::local($item['event-start'], 'M')
859 : DateTimeFormat::utc($item['event-start'], 'M')
861 // Format: 1 till 31.
862 $date_short = $item['event-adjust'] ?
863 DateTimeFormat::local($item['event-start'], 'j')
864 : DateTimeFormat::utc($item['event-start'], 'j');
865 $start_time = $item['event-adjust'] ?
866 DateTimeFormat::local($item['event-start'], $tformat)
867 : DateTimeFormat::utc($item['event-start'], $tformat);
868 $start_short = L10n::getDayShort(
869 $item['event-adjust'] ?
870 DateTimeFormat::local($item['event-start'], $dformat_short)
871 : DateTimeFormat::utc($item['event-start'], $dformat_short)
874 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
875 if (!$item['event-nofinish']) {
877 $dtend_dt = L10n::getDay(
878 $item['event-adjust'] ?
879 DateTimeFormat::local($item['event-finish'], $dformat)
880 : DateTimeFormat::utc($item['event-finish'], $dformat)
882 $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
883 $end_short = L10n::getDayShort(
884 $item['event-adjust'] ?
885 DateTimeFormat::local($item['event-finish'], $dformat_short)
886 : DateTimeFormat::utc($item['event-finish'], $dformat_short)
888 $end_time = $item['event-adjust'] ?
889 DateTimeFormat::local($item['event-finish'], $tformat)
890 : DateTimeFormat::utc($item['event-finish'], $tformat);
891 // Check if start and finish time is at the same day.
892 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
902 // Format the event location.
903 $location = self::locationToArray($item['event-location']);
905 // Construct the profile link (magic-auth).
906 $profile_link = Contact::magicLinkById($item['author-id']);
908 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
909 $return = Renderer::replaceMacros($tpl, [
910 '$id' => $item['event-id'],
911 '$title' => prepare_text($item['event-summary']),
912 '$dtstart_label' => L10n::t('Starts:'),
913 '$dtstart_title' => $dtstart_title,
914 '$dtstart_dt' => $dtstart_dt,
915 '$finish' => $finish,
916 '$dtend_label' => L10n::t('Finishes:'),
917 '$dtend_title' => $dtend_title,
918 '$dtend_dt' => $dtend_dt,
919 '$month_short' => $month_short,
920 '$date_short' => $date_short,
921 '$same_date' => $same_date,
922 '$start_time' => $start_time,
923 '$start_short' => $start_short,
924 '$end_time' => $end_time,
925 '$end_short' => $end_short,
926 '$author_name' => $item['author-name'],
927 '$author_link' => $profile_link,
928 '$author_avatar' => $item['author-avatar'],
929 '$description' => prepare_text($item['event-desc']),
930 '$location_label' => L10n::t('Location:'),
931 '$show_map_label' => L10n::t('Show map'),
932 '$hide_map_label' => L10n::t('Hide map'),
933 '$map_btn_label' => L10n::t('Show map'),
934 '$location' => $location
941 * @brief Format a string with map bbcode to an array with location data.
943 * Note: The string must only contain location data. A string with no bbcode will be
944 * handled as location name.
946 * @param string $s The string with the bbcode formatted location data.
948 * @return array The array with the location data.
949 * 'name' => The name of the location,<br>
950 * 'address' => The address of the location,<br>
951 * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954 private static function locationToArray($s = '') {
959 $location = ['name' => $s];
961 // Map tag with location name - e.g. [map]Paris[/map].
962 if (strpos($s, '[/map]') !== false) {
963 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
964 if (intval($found) > 0 && array_key_exists(1, $match)) {
965 $location['address'] = $match[1];
966 // Remove the map bbcode from the location name.
967 $location['name'] = str_replace($match[0], "", $s);
969 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
970 } elseif (strpos($s, '[map=') !== false) {
971 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
972 if (intval($found) > 0 && array_key_exists(1, $match)) {
973 $location['coordinates'] = $match[1];
974 // Remove the map bbcode from the location name.
975 $location['name'] = str_replace($match[0], "", $s);
979 $location['name'] = prepare_text($location['name']);
981 // Construct the map HTML.
982 if (isset($location['address'])) {
983 $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
984 } elseif (isset($location['coordinates'])) {
985 $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
992 * @brief Add new birthday event for this person
994 * @param array $contact Contact array, expects: id, uid, url, name
995 * @param string $birthday Birthday of the contact
999 public static function createBirthday($contact, $birthday)
1001 // Check for duplicates
1003 'uid' => $contact['uid'],
1004 'cid' => $contact['id'],
1005 'start' => DateTimeFormat::utc($birthday),
1006 'type' => 'birthday'
1008 if (DBA::exists('event', $condition)) {
1013 * Add new birthday event for this person
1015 * summary is just a readable placeholder in case the event is shared
1016 * with others. We will replace it during presentation to our $importer
1017 * to contain a sparkle link and perhaps a photo.
1020 'uid' => $contact['uid'],
1021 'cid' => $contact['id'],
1022 'start' => DateTimeFormat::utc($birthday),
1023 'finish' => DateTimeFormat::utc($birthday . ' + 1 day '),
1024 'summary' => L10n::t('%s\'s birthday', $contact['name']),
1025 'desc' => L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1026 'type' => 'birthday',
1030 self::store($values);