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