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