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