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