]> git.mxchange.org Git - friendica.git/blob - src/Model/Event.php
9b258960e6264ceded8d1bbb616678169ef98e81
[friendica.git] / src / Model / Event.php
1 <?php
2 /**
3  * @file src/Model/Event.php
4  */
5
6 namespace Friendica\Model;
7
8 use dba;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Item;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Map;
19
20 require_once 'boot.php';
21 require_once 'include/dba.php';
22 require_once 'include/items.php';
23
24 /**
25  * @brief functions for interacting with the event database table
26  */
27 class Event extends BaseObject
28 {
29
30         public static function getHTML(array $event, $simple = false)
31         {
32                 if (empty($event)) {
33                         return '';
34                 }
35
36                 $bd_format = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8 AM.
37
38                 $event_start = day_translate(
39                         $event['adjust'] ?
40                         DateTimeFormat::local($event['start'], $bd_format) : DateTimeFormat::utc($event['start'], $bd_format)
41                 );
42
43                 $event_end = day_translate(
44                         $event['adjust'] ?
45                         DateTimeFormat::local($event['finish'], $bd_format) : DateTimeFormat::utc($event['finish'], $bd_format)
46                 );
47
48                 if ($simple) {
49                         $o = "<h3>" . BBCode::convert($event['summary'], false, $simple) . "</h3>";
50
51                         $o .= "<div>" . BBCode::convert($event['desc'], false, $simple) . "</div>";
52
53                         $o .= "<h4>" . L10n::t('Starts:') . "</h4><p>" . $event_start . "</p>";
54
55                         if (!$event['nofinish']) {
56                                 $o .= "<h4>" . L10n::t('Finishes:') . "</h4><p>" . $event_end . "</p>";
57                         }
58
59                         if (strlen($event['location'])) {
60                                 $o .= "<h4>" . L10n::t('Location:') . "</h4><p>" . BBCode::convert($event['location'], false, $simple) . "</p>";
61                         }
62
63                         return $o;
64                 }
65
66                 $o = '<div class="vevent">' . "\r\n";
67
68                 $o .= '<div class="summary event-summary">' . BBCode::convert($event['summary'], false, $simple) . '</div>' . "\r\n";
69
70                 $o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span>&nbsp;<span class="dtstart" title="'
71                         . DateTimeFormat::utc($event['start'], (($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
72                         . '" >' . $event_start
73                         . '</span></div>' . "\r\n";
74
75                 if (!$event['nofinish']) {
76                         $o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span>&nbsp;<span class="dtend" title="'
77                                 . DateTimeFormat::utc($event['finish'], (($event['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s'))
78                                 . '" >' . $event_end
79                                 . '</span></div>' . "\r\n";
80                 }
81
82                 $o .= '<div class="description event-description">' . BBCode::convert($event['desc'], false, $simple) . '</div>' . "\r\n";
83
84                 if (strlen($event['location'])) {
85                         $o .= '<div class="event-location"><span class="event-label">' . L10n::t('Location:') . '</span>&nbsp;<span class="location">'
86                                 . BBCode::convert($event['location'], false, $simple)
87                                 . '</span></div>' . "\r\n";
88
89                         // Include a map of the location if the [map] BBCode is used.
90                         if (strpos($event['location'], "[map") !== false) {
91                                 $map = Map::byLocation($event['location'], $simple);
92                                 if ($map !== $event['location']) {
93                                         $o .= $map;
94                                 }
95                         }
96                 }
97
98                 $o .= '</div>' . "\r\n";
99                 return $o;
100         }
101
102         /**
103          * @brief Convert an array with event data to bbcode.
104          *
105          * @param array $event Array which contains the event data.
106          * @return string The event as a bbcode formatted string.
107          */
108         private static function getBBCode(array $event)
109         {
110                 $o = '';
111
112                 if ($event['summary']) {
113                         $o .= '[event-summary]' . $event['summary'] . '[/event-summary]';
114                 }
115
116                 if ($event['desc']) {
117                         $o .= '[event-description]' . $event['desc'] . '[/event-description]';
118                 }
119
120                 if ($event['start']) {
121                         $o .= '[event-start]' . $event['start'] . '[/event-start]';
122                 }
123
124                 if (($event['finish']) && (!$event['nofinish'])) {
125                         $o .= '[event-finish]' . $event['finish'] . '[/event-finish]';
126                 }
127
128                 if ($event['location']) {
129                         $o .= '[event-location]' . $event['location'] . '[/event-location]';
130                 }
131
132                 if ($event['adjust']) {
133                         $o .= '[event-adjust]' . $event['adjust'] . '[/event-adjust]';
134                 }
135
136                 return $o;
137         }
138
139         /**
140          * @brief Extract bbcode formatted event data from a string.
141          *
142          * @params: string $s The string which should be parsed for event data.
143          * @return array The array with the event information.
144          */
145         public static function fromBBCode($text)
146         {
147                 $ev = [];
148
149                 $match = '';
150                 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
151                         $ev['summary'] = $match[1];
152                 }
153
154                 $match = '';
155                 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
156                         $ev['desc'] = $match[1];
157                 }
158
159                 $match = '';
160                 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
161                         $ev['start'] = $match[1];
162                 }
163
164                 $match = '';
165                 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
166                         $ev['finish'] = $match[1];
167                 }
168
169                 $match = '';
170                 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
171                         $ev['location'] = $match[1];
172                 }
173
174                 $match = '';
175                 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
176                         $ev['adjust'] = $match[1];
177                 }
178
179                 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
180
181                 return $ev;
182         }
183
184         public static function sortByDate($event_list)
185         {
186                 usort($event_list, ['self', 'compareDatesCallback']);
187                 return $event_list;
188         }
189
190         private static function compareDatesCallback($event_a, $event_b)
191         {
192                 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
193                 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
194
195                 if ($date_a === $date_b) {
196                         return strcasecmp($event_a['desc'], $event_b['desc']);
197                 }
198
199                 return strcmp($date_a, $date_b);
200         }
201
202         /**
203          * @brief Delete an event from the event table.
204          *
205          * Note: This function does only delete the event from the event table not its
206          * related entry in the item table.
207          *
208          * @param int $event_id Event ID.
209          * @return void
210          */
211         public static function delete($event_id)
212         {
213                 if ($event_id == 0) {
214                         return;
215                 }
216
217                 dba::delete('event', ['id' => $event_id]);
218                 logger("Deleted event ".$event_id, LOGGER_DEBUG);
219         }
220
221         /**
222          * @brief Store the event.
223          *
224          * Store the event in the event table and create an event item in the item table.
225          *
226          * @param array $arr Array with event data.
227          * @return int The new event id.
228          */
229         public static function store($arr)
230         {
231                 $a = self::getApp();
232
233                 $event = [];
234                 $event['id']        = intval(defaults($arr, 'id'       , 0));
235                 $event['uid']       = intval(defaults($arr, 'uid'      , 0));
236                 $event['cid']       = intval(defaults($arr, 'cid'      , 0));
237                 $event['uri']       =        defaults($arr, 'uri'      , Item::newURI($event['uid']));
238                 $event['type']      =        defaults($arr, 'type'     , 'event');
239                 $event['summary']   =        defaults($arr, 'summary'  , '');
240                 $event['desc']      =        defaults($arr, 'desc'     , '');
241                 $event['location']  =        defaults($arr, 'location' , '');
242                 $event['allow_cid'] =        defaults($arr, 'allow_cid', '');
243                 $event['allow_gid'] =        defaults($arr, 'allow_gid', '');
244                 $event['deny_cid']  =        defaults($arr, 'deny_cid' , '');
245                 $event['deny_gid']  =        defaults($arr, 'deny_gid' , '');
246                 $event['adjust']    = intval(defaults($arr, 'adjust'   , 0));
247                 $event['nofinish']  = intval(defaults($arr, 'nofinish' , !empty($event['start']) && empty($event['finish'])));
248
249                 $event['created']   = DateTimeFormat::utc(defaults($arr, 'created'  , 'now'));
250                 $event['edited']    = DateTimeFormat::utc(defaults($arr, 'edited'   , 'now'));
251                 $event['start']     = DateTimeFormat::utc(defaults($arr, 'start'    , NULL_DATE));
252                 $event['finish']    = DateTimeFormat::utc(defaults($arr, 'finish'   , NULL_DATE));
253                 if ($event['finish'] < NULL_DATE) {
254                         $event['finish'] = NULL_DATE;
255                 }
256                 $private = intval(defaults($arr, 'private', 0));
257
258                 $conditions = ['uid' => $event['uid']];
259                 if ($event['cid']) {
260                         $conditions['id'] = $event['cid'];
261                 } else {
262                         $conditions['self'] = true;
263                 }
264
265                 $contact = dba::selectFirst('contact', [], $conditions);
266
267                 // Existing event being modified.
268                 if ($event['id']) {
269                         // has the event actually changed?
270                         $existing_event = dba::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
271                         if ((! DBM::is_result($existing_event)) || ($existing_event['edited'] === $event['edited'])) {
272
273                                 $item = dba::selectFirst('item', [], ['event-id' => $event['id'], 'uid' => $event['uid']]);
274
275                                 return DBM::is_result($item) ? $item['id'] : 0;
276                         }
277
278                         $updated_fields = [
279                                 'edited'   => $event['edited'],
280                                 'start'    => $event['start'],
281                                 'finish'   => $event['finish'],
282                                 'summary'  => $event['summary'],
283                                 'desc'     => $event['desc'],
284                                 'location' => $event['location'],
285                                 'type'     => $event['type'],
286                                 'adjust'   => $event['adjust'],
287                                 'nofinish' => $event['nofinish'],
288                         ];
289
290                         dba::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
291
292                         $item = dba::selectFirst('item', ['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
293                         if (DBM::is_result($item)) {
294                                 $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($event['uri']) . '</id>';
295                                 $object .= '<content>' . xmlify(self::getBBCode($event)) . '</content>';
296                                 $object .= '</object>' . "\n";
297
298                                 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
299                                 Item::update($fields, ['id' => $item['id']]);
300
301                                 $item_id = $item['id'];
302                         } else {
303                                 $item_id = 0;
304                         }
305
306                         Addon::callHooks('event_updated', $event['id']);
307                 } else {
308                         $event['guid'] = get_guid(32);
309
310                         // New event. Store it.
311                         dba::insert('event', $event);
312
313                         $event['id'] = dba::lastInsertId();
314
315                         $item_arr = [];
316
317                         $item_arr['uid']           = $event['uid'];
318                         $item_arr['contact-id']    = $event['cid'];
319                         $item_arr['uri']           = $event['uri'];
320                         $item_arr['parent-uri']    = $event['uri'];
321                         $item_arr['guid']          = $event['guid'];
322                         $item_arr['type']          = 'activity';
323                         $item_arr['wall']          = $event['cid'] ? 0 : 1;
324                         $item_arr['contact-id']    = $contact['id'];
325                         $item_arr['owner-name']    = $contact['name'];
326                         $item_arr['owner-link']    = $contact['url'];
327                         $item_arr['owner-avatar']  = $contact['thumb'];
328                         $item_arr['author-name']   = $contact['name'];
329                         $item_arr['author-link']   = $contact['url'];
330                         $item_arr['author-avatar'] = $contact['thumb'];
331                         $item_arr['title']         = '';
332                         $item_arr['allow_cid']     = $event['allow_cid'];
333                         $item_arr['allow_gid']     = $event['allow_gid'];
334                         $item_arr['deny_cid']      = $event['deny_cid'];
335                         $item_arr['deny_gid']      = $event['deny_gid'];
336                         $item_arr['private']       = $private;
337                         $item_arr['visible']       = 1;
338                         $item_arr['verb']          = ACTIVITY_POST;
339                         $item_arr['object-type']   = ACTIVITY_OBJ_EVENT;
340                         $item_arr['origin']        = $event['cid'] === 0 ? 1 : 0;
341                         $item_arr['body']          = self::getBBCode($event);
342                         $item_arr['event-id']      = $event['id'];
343
344                         $item_arr['object']  = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($event['uri']) . '</id>';
345                         $item_arr['object'] .= '<content>' . xmlify(self::getBBCode($event)) . '</content>';
346                         $item_arr['object'] .= '</object>' . "\n";
347
348                         $item_id = Item::insert($item_arr);
349
350                         Addon::callHooks("event_created", $event['id']);
351                 }
352
353                 return $item_id;
354         }
355
356         /**
357          * @brief Create an array with translation strings used for events.
358          *
359          * @return array Array with translations strings.
360          */
361         public static function getStrings()
362         {
363                 // First day of the week (0 = Sunday).
364                 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
365
366                 $i18n = [
367                         "firstDay" => $firstDay,
368                         "allday"   => L10n::t("all-day"),
369
370                         "Sun" => L10n::t("Sun"),
371                         "Mon" => L10n::t("Mon"),
372                         "Tue" => L10n::t("Tue"),
373                         "Wed" => L10n::t("Wed"),
374                         "Thu" => L10n::t("Thu"),
375                         "Fri" => L10n::t("Fri"),
376                         "Sat" => L10n::t("Sat"),
377
378                         "Sunday"    => L10n::t("Sunday"),
379                         "Monday"    => L10n::t("Monday"),
380                         "Tuesday"   => L10n::t("Tuesday"),
381                         "Wednesday" => L10n::t("Wednesday"),
382                         "Thursday"  => L10n::t("Thursday"),
383                         "Friday"    => L10n::t("Friday"),
384                         "Saturday"  => L10n::t("Saturday"),
385
386                         "Jan" => L10n::t("Jan"),
387                         "Feb" => L10n::t("Feb"),
388                         "Mar" => L10n::t("Mar"),
389                         "Apr" => L10n::t("Apr"),
390                         "May" => L10n::t("May"),
391                         "Jun" => L10n::t("Jun"),
392                         "Jul" => L10n::t("Jul"),
393                         "Aug" => L10n::t("Aug"),
394                         "Sep" => L10n::t("Sept"),
395                         "Oct" => L10n::t("Oct"),
396                         "Nov" => L10n::t("Nov"),
397                         "Dec" => L10n::t("Dec"),
398
399                         "January"   => L10n::t("January"),
400                         "February"  => L10n::t("February"),
401                         "March"     => L10n::t("March"),
402                         "April"     => L10n::t("April"),
403                         "May"       => L10n::t("May"),
404                         "June"      => L10n::t("June"),
405                         "July"      => L10n::t("July"),
406                         "August"    => L10n::t("August"),
407                         "September" => L10n::t("September"),
408                         "October"   => L10n::t("October"),
409                         "November"  => L10n::t("November"),
410                         "December"  => L10n::t("December"),
411
412                         "today" => L10n::t("today"),
413                         "month" => L10n::t("month"),
414                         "week"  => L10n::t("week"),
415                         "day"   => L10n::t("day"),
416
417                         "noevent" => L10n::t("No events to display"),
418
419                         "dtstart_label"  => L10n::t("Starts:"),
420                         "dtend_label"    => L10n::t("Finishes:"),
421                         "location_label" => L10n::t("Location:")
422                 ];
423
424                 return $i18n;
425         }
426
427         /**
428          * @brief Removes duplicated birthday events.
429          *
430          * @param array $dates Array of possibly duplicated events.
431          * @return array Cleaned events.
432          *
433          * @todo We should replace this with a separate update function if there is some time left.
434          */
435         private static function removeDuplicates(array $dates)
436         {
437                 $dates2 = [];
438
439                 foreach ($dates as $date) {
440                         if ($date['type'] == 'birthday') {
441                                 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
442                         } else {
443                                 $dates2[] = $date;
444                         }
445                 }
446                 return array_values($dates2);
447         }
448
449         /**
450          * @brief Get an event by its event ID.
451          *
452          * @param int    $owner_uid The User ID of the owner of the event
453          * @param int    $event_id  The ID of the event in the event table
454          * @param string $sql_extra
455          * @return array Query result
456          */
457         public static function getListById($owner_uid, $event_id, $sql_extra = '')
458         {
459                 $return = [];
460
461                 // Ownly allow events if there is a valid owner_id.
462                 if ($owner_uid == 0) {
463                         return $return;
464                 }
465
466                 // Query for the event by event id
467                 $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
468                                 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
469                         LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
470                         WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
471                         intval($owner_uid),
472                         intval($event_id)
473                 );
474
475                 if (DBM::is_result($r)) {
476                         $return = self::removeDuplicates($r);
477                 }
478
479                 return $return;
480         }
481
482         /**
483          * @brief Get all events in a specific time frame.
484          *
485          * @param int $owner_uid The User ID of the owner of the events.
486          * @param array $event_params An associative array with
487          *      int 'ignore' =>
488          *      string 'start' => Start time of the timeframe.
489          *      string 'finish' => Finish time of the timeframe.
490          *      string 'adjust_start' =>
491          *      string 'adjust_finish' =>
492          *
493          * @param string $sql_extra Additional sql conditions (e.g. permission request).
494          *
495          * @return array Query results.
496          */
497         public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
498         {
499                 $return = [];
500
501                 // Only allow events if there is a valid owner_id.
502                 if ($owner_uid == 0) {
503                         return $return;
504                 }
505
506                 // Query for the event by date.
507                 // @todo Slow query (518 seconds to run), to be optimzed
508                 $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
509                                         `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
510                                 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
511                                 WHERE `event`.`uid` = %d AND event.ignore = %d
512                                 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
513                                 OR  (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
514                                 $sql_extra ",
515                                 intval($owner_uid),
516                                 intval($event_params["ignore"]),
517                                 dbesc($event_params["start"]),
518                                 dbesc($event_params["start"]),
519                                 dbesc($event_params["finish"]),
520                                 dbesc($event_params["adjust_start"]),
521                                 dbesc($event_params["adjust_start"]),
522                                 dbesc($event_params["adjust_finish"])
523                 );
524
525                 if (DBM::is_result($r)) {
526                         $return = self::removeDuplicates($r);
527                 }
528
529                 return $return;
530         }
531
532         /**
533          * @brief Convert an array query results in an array which could be used by the events template.
534          *
535          * @param array $event_result Event query array.
536          * @return array Event array for the template.
537          */
538         public static function prepareListForTemplate(array $event_result)
539         {
540                 $event_list = [];
541
542                 $last_date = '';
543                 $fmt = L10n::t('l, F j');
544                 foreach ($event_result as $event) {
545                         $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c')  : DateTimeFormat::utc($event['start'], 'c');
546                         $j     = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j')  : DateTimeFormat::utc($event['start'], 'j');
547                         $day   = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
548                         $day   = day_translate($day);
549
550                         if ($event['nofinish']) {
551                                 $end = null;
552                         } else {
553                                 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
554                         }
555
556                         $is_first = ($day !== $last_date);
557
558                         $last_date = $day;
559
560                         // Show edit and drop actions only if the user is the owner of the event and the event
561                         // is a real event (no bithdays).
562                         $edit = null;
563                         $copy = null;
564                         $drop = null;
565                         if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
566                                 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event')     , '', ''] : null;
567                                 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
568                                 $drop =                  [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event')   , '', ''];
569                         }
570
571                         $title = strip_tags(html_entity_decode(BBCode::convert($event['summary']), ENT_QUOTES, 'UTF-8'));
572                         if (!$title) {
573                                 list($title, $_trash) = explode("<br", BBCode::convert($event['desc']), 2);
574                                 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
575                         }
576
577                         $html = self::getHTML($event);
578                         $event['desc']     = BBCode::convert($event['desc']);
579                         $event['location'] = BBCode::convert($event['location']);
580                         $event_list[] = [
581                                 'id'       => $event['id'],
582                                 'start'    => $start,
583                                 'end'      => $end,
584                                 'allDay'   => false,
585                                 'title'    => $title,
586                                 'j'        => $j,
587                                 'd'        => $day,
588                                 'edit'     => $edit,
589                                 'drop'     => $drop,
590                                 'copy'     => $copy,
591                                 'is_first' => $is_first,
592                                 'item'     => $event,
593                                 'html'     => $html,
594                                 'plink'    => [$event['plink'], L10n::t('link to source'), '', ''],
595                         ];
596                 }
597
598                 return $event_list;
599         }
600
601         /**
602          * @brief Format event to export format (ical/csv).
603          *
604          * @param array  $events   Query result for events.
605          * @param string $format   The output format (ical/csv).
606          * @param string $timezone The timezone of the user (not implemented yet).
607          *
608          * @return string Content according to selected export format.
609          *
610          * @todo Implement timezone support
611          */
612         private static function formatListForExport(array $events, $format, $timezone)
613         {
614                 if (!count($events)) {
615                         return '';
616                 }
617
618                 switch ($format) {
619                         // Format the exported data as a CSV file.
620                         case "csv":
621                                 header("Content-type: text/csv");
622                                 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
623
624                                 foreach ($events as $event) {
625                                         /// @todo The time / date entries don't include any information about the
626                                         /// timezone the event is scheduled in :-/
627                                         $tmp1 = strtotime($event['start']);
628                                         $tmp2 = strtotime($event['finish']);
629                                         $time_format = "%H:%M:%S";
630                                         $date_format = "%Y-%m-%d";
631
632                                         $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
633                                                 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
634                                                 '", "' . strftime($date_format, $tmp2) .
635                                                 '", "' . strftime($time_format, $tmp2) .
636                                                 '", "' . $event['location'] . '"' . PHP_EOL;
637                                 }
638                                 break;
639
640                         // Format the exported data as a ics file.
641                         case "ical":
642                                 header("Content-type: text/ics");
643                                 $o = 'BEGIN:VCALENDAR' . PHP_EOL
644                                         . 'VERSION:2.0' . PHP_EOL
645                                         . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
646                                 ///  @todo include timezone informations in cases were the time is not in UTC
647                                 //  see http://tools.ietf.org/html/rfc2445#section-4.8.3
648                                 //              . 'BEGIN:VTIMEZONE' . PHP_EOL
649                                 //              . 'TZID:' . $timezone . PHP_EOL
650                                 //              . 'END:VTIMEZONE' . PHP_EOL;
651                                 //  TODO instead of PHP_EOL CRLF should be used for long entries
652                                 //       but test your solution against http://icalvalid.cloudapp.net/
653                                 //       also long lines SHOULD be split at 75 characters length
654                                 foreach ($events as $event) {
655                                         if ($event['adjust'] == 1) {
656                                                 $UTC = 'Z';
657                                         } else {
658                                                 $UTC = '';
659                                         }
660                                         $o .= 'BEGIN:VEVENT' . PHP_EOL;
661
662                                         if ($event['start']) {
663                                                 $tmp = strtotime($event['start']);
664                                                 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
665                                                 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
666                                         }
667
668                                         if (!$event['nofinish']) {
669                                                 $tmp = strtotime($event['finish']);
670                                                 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
671                                                 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
672                                         }
673
674                                         if ($event['summary']) {
675                                                 $tmp = $event['summary'];
676                                                 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
677                                                 $tmp = addcslashes($tmp, ',;');
678                                                 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
679                                         }
680
681                                         if ($event['desc']) {
682                                                 $tmp = $event['desc'];
683                                                 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
684                                                 $tmp = addcslashes($tmp, ',;');
685                                                 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
686                                         }
687
688                                         if ($event['location']) {
689                                                 $tmp = $event['location'];
690                                                 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
691                                                 $tmp = addcslashes($tmp, ',;');
692                                                 $o .= 'LOCATION:' . $tmp . PHP_EOL;
693                                         }
694
695                                         $o .= 'END:VEVENT' . PHP_EOL;
696                                         $o .= PHP_EOL;
697                                 }
698
699                                 $o .= 'END:VCALENDAR' . PHP_EOL;
700                                 break;
701                 }
702
703                 return $o;
704         }
705
706         /**
707          * @brief Get all events for a user ID.
708          *
709          *    The query for events is done permission sensitive.
710          *    If the user is the owner of the calendar they
711          *    will get all of their available events.
712          *    If the user is only a visitor only the public events will
713          *    be available.
714          *
715          * @param int $uid The user ID.
716          *
717          * @return array Query results.
718          */
719         private static function getListByUserId($uid = 0)
720         {
721                 $return = [];
722
723                 if ($uid == 0) {
724                         return $return;
725                 }
726
727                 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
728
729                 $conditions = ['uid' => $uid, 'cid' => 0];
730
731                 // Does the user who requests happen to be the owner of the events
732                 // requested? then show all of your events, otherwise only those that
733                 // don't have limitations set in allow_cid and allow_gid.
734                 if (local_user() != $uid) {
735                         $conditions += ['allow_cid' => '', 'allow_gid' => ''];
736                 }
737
738                 $events = dba::select('event', $fields, $conditions);
739                 if (DBM::is_result($events)) {
740                         $return = dba::inArray($events);
741                 }
742
743                 return $return;
744         }
745
746         /**
747          *
748          * @param int $uid The user ID.
749          * @param string $format Output format (ical/csv).
750          * @return array With the results:
751          *      bool 'success' => True if the processing was successful,<br>
752          *      string 'format' => The output format,<br>
753          *      string 'extension' => The file extension of the output format,<br>
754          *      string 'content' => The formatted output content.<br>
755          *
756          * @todo Respect authenticated users with events_by_uid().
757          */
758         public static function exportListByUserId($uid, $format = 'ical')
759         {
760                 $process = false;
761
762                 $user = dba::selectFirst('user', ['timezone'], ['uid' => $uid]);
763                 if (DBM::is_result($user)) {
764                         $timezone = $user['timezone'];
765                 }
766
767                 // Get all events which are owned by a uid (respects permissions).
768                 $events = self::getListByUserId($uid);
769
770                 // We have the events that are available for the requestor.
771                 // Now format the output according to the requested format.
772                 $res = self::formatListForExport($events, $format, $timezone);
773
774                 // If there are results the precess was successfull.
775                 if (!empty($res)) {
776                         $process = true;
777                 }
778
779                 // Get the file extension for the format.
780                 switch ($format) {
781                         case "ical":
782                                 $file_ext = "ics";
783                                 break;
784
785                         case "csv":
786                                 $file_ext = "csv";
787                                 break;
788
789                         default:
790                                 $file_ext = "";
791                 }
792
793                 $return = [
794                         'success'   => $process,
795                         'format'    => $format,
796                         'extension' => $file_ext,
797                         'content'   => $res,
798                 ];
799
800                 return $return;
801         }
802
803         /**
804          * @brief Format an item array with event data to HTML.
805          *
806          * @param array $item Array with item and event data.
807          * @return string HTML output.
808          */
809         public static function getItemHTML(array $item) {
810                 $same_date = false;
811                 $finish    = false;
812
813                 // Set the different time formats.
814                 $dformat       = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
815                 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
816                 $tformat       = L10n::t('g:i A'); // 8:01 AM.
817
818                 // Convert the time to different formats.
819                 $dtstart_dt = day_translate(
820                         $item['event-adjust'] ?
821                                 DateTimeFormat::local($item['event-start'], $dformat)
822                                 : DateTimeFormat::utc($item['event-start'], $dformat)
823                 );
824                 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
825                 // Format: Jan till Dec.
826                 $month_short = day_short_translate(
827                         $item['event-adjust'] ?
828                                 DateTimeFormat::local($item['event-start'], 'M')
829                                 : DateTimeFormat::utc($item['event-start'], 'M')
830                 );
831                 // Format: 1 till 31.
832                 $date_short = $item['event-adjust'] ?
833                         DateTimeFormat::local($item['event-start'], 'j')
834                         : DateTimeFormat::utc($item['event-start'], 'j');
835                 $start_time = $item['event-adjust'] ?
836                         DateTimeFormat::local($item['event-start'], $tformat)
837                         : DateTimeFormat::utc($item['event-start'], $tformat);
838                 $start_short = day_short_translate(
839                         $item['event-adjust'] ?
840                                 DateTimeFormat::local($item['event-start'], $dformat_short)
841                                 : DateTimeFormat::utc($item['event-start'], $dformat_short)
842                 );
843
844                 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
845                 if (!$item['event-nofinish']) {
846                         $finish = true;
847                         $dtend_dt  = day_translate(
848                                 $item['event-adjust'] ?
849                                         DateTimeFormat::local($item['event-finish'], $dformat)
850                                         : DateTimeFormat::utc($item['event-finish'], $dformat)
851                         );
852                         $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
853                         $end_short = day_short_translate(
854                                 $item['event-adjust'] ?
855                                         DateTimeFormat::local($item['event-finish'], $dformat_short)
856                                         : DateTimeFormat::utc($item['event-finish'], $dformat_short)
857                         );
858                         $end_time = $item['event-adjust'] ?
859                                 DateTimeFormat::local($item['event-finish'], $tformat)
860                                 : DateTimeFormat::utc($item['event-finish'], $tformat);
861                         // Check if start and finish time is at the same day.
862                         if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
863                                 $same_date = true;
864                         }
865                 }
866
867                 // Format the event location.
868                 $location = self::locationToArray($item['event-location']);
869
870                 // Construct the profile link (magic-auth).
871                 $profile_link = Contact::magicLinkById($item['author-id']);
872
873                 $tpl = get_markup_template('event_stream_item.tpl');
874                 $return = replace_macros($tpl, [
875                         '$id'             => $item['event-id'],
876                         '$title'          => prepare_text($item['event-summary']),
877                         '$dtstart_label'  => L10n::t('Starts:'),
878                         '$dtstart_title'  => $dtstart_title,
879                         '$dtstart_dt'     => $dtstart_dt,
880                         '$finish'         => $finish,
881                         '$dtend_label'    => L10n::t('Finishes:'),
882                         '$dtend_title'    => $dtend_title,
883                         '$dtend_dt'       => $dtend_dt,
884                         '$month_short'    => $month_short,
885                         '$date_short'     => $date_short,
886                         '$same_date'      => $same_date,
887                         '$start_time'     => $start_time,
888                         '$start_short'    => $start_short,
889                         '$end_time'       => $end_time,
890                         '$end_short'      => $end_short,
891                         '$author_name'    => $item['author-name'],
892                         '$author_link'    => $profile_link,
893                         '$author_avatar'  => $item['author-avatar'],
894                         '$description'    => prepare_text($item['event-desc']),
895                         '$location_label' => L10n::t('Location:'),
896                         '$show_map_label' => L10n::t('Show map'),
897                         '$hide_map_label' => L10n::t('Hide map'),
898                         '$map_btn_label'  => L10n::t('Show map'),
899                         '$location'       => $location
900                 ]);
901
902                 return $return;
903         }
904
905         /**
906          * @brief Format a string with map bbcode to an array with location data.
907          *
908          * Note: The string must only contain location data. A string with no bbcode will be
909          * handled as location name.
910          *
911          * @param string $s The string with the bbcode formatted location data.
912          *
913          * @return array The array with the location data.
914          *  'name' => The name of the location,<br>
915          * 'address' => The address of the location,<br>
916          * 'coordinates' => Latitude‎ and longitude‎ (e.g. '48.864716,2.349014').<br>
917          */
918         private static function locationToArray($s = '') {
919                 if ($s == '') {
920                         return [];
921                 }
922
923                 $location = ['name' => $s];
924
925                 // Map tag with location name - e.g. [map]Paris[/map].
926                 if (strpos($s, '[/map]') !== false) {
927                         $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
928                         if (intval($found) > 0 && array_key_exists(1, $match)) {
929                                 $location['address'] =  $match[1];
930                                 // Remove the map bbcode from the location name.
931                                 $location['name'] = str_replace($match[0], "", $s);
932                         }
933                 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
934                 } elseif (strpos($s, '[map=') !== false) {
935                         $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
936                         if (intval($found) > 0 && array_key_exists(1, $match)) {
937                                 $location['coordinates'] =  $match[1];
938                                 // Remove the map bbcode from the location name.
939                                 $location['name'] = str_replace($match[0], "", $s);
940                         }
941                 }
942
943                 $location['name'] = prepare_text($location['name']);
944
945                 // Construct the map HTML.
946                 if (isset($location['address'])) {
947                         $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
948                 } elseif (isset($location['coordinates'])) {
949                         $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
950                 }
951
952                 return $location;
953         }
954 }