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