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