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