]> git.mxchange.org Git - friendica.git/blob - src/Model/Event.php
Update more PHPDoc, including in include/
[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                         if (!empty($event['summary'])) {
52                                 $o = "<h3>" . BBCode::convert(Strings::escapeHtml($event['summary']), false, $simple) . "</h3>";
53                         }
54
55                         if (!empty($event['desc'])) {
56                                 $o .= "<div>" . BBCode::convert(Strings::escapeHtml($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(Strings::escapeHtml($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(Strings::escapeHtml($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(Strings::escapeHtml($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(Strings::escapeHtml($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          * @param $text
152          * @return array The array with the event information.
153          */
154         public static function fromBBCode($text)
155         {
156                 $ev = [];
157
158                 $match = '';
159                 if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $text, $match)) {
160                         $ev['summary'] = $match[1];
161                 }
162
163                 $match = '';
164                 if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $text, $match)) {
165                         $ev['desc'] = $match[1];
166                 }
167
168                 $match = '';
169                 if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $text, $match)) {
170                         $ev['start'] = $match[1];
171                 }
172
173                 $match = '';
174                 if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $text, $match)) {
175                         $ev['finish'] = $match[1];
176                 }
177
178                 $match = '';
179                 if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $text, $match)) {
180                         $ev['location'] = $match[1];
181                 }
182
183                 $match = '';
184                 if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $text, $match)) {
185                         $ev['adjust'] = $match[1];
186                 }
187
188                 $ev['nofinish'] = !empty($ev['start']) && empty($ev['finish']) ? 1 : 0;
189
190                 return $ev;
191         }
192
193         public static function sortByDate($event_list)
194         {
195                 usort($event_list, ['self', 'compareDatesCallback']);
196                 return $event_list;
197         }
198
199         private static function compareDatesCallback($event_a, $event_b)
200         {
201                 $date_a = (($event_a['adjust']) ? DateTimeFormat::local($event_a['start']) : $event_a['start']);
202                 $date_b = (($event_b['adjust']) ? DateTimeFormat::local($event_b['start']) : $event_b['start']);
203
204                 if ($date_a === $date_b) {
205                         return strcasecmp($event_a['desc'], $event_b['desc']);
206                 }
207
208                 return strcmp($date_a, $date_b);
209         }
210
211         /**
212          * @brief Delete an event from the event table.
213          *
214          * Note: This function does only delete the event from the event table not its
215          * related entry in the item table.
216          *
217          * @param int $event_id Event ID.
218          * @return void
219          * @throws \Exception
220          */
221         public static function delete($event_id)
222         {
223                 if ($event_id == 0) {
224                         return;
225                 }
226
227                 DBA::delete('event', ['id' => $event_id]);
228                 Logger::log("Deleted event ".$event_id, Logger::DEBUG);
229         }
230
231         /**
232          * @brief Store the event.
233          *
234          * Store the event in the event table and create an event item in the item table.
235          *
236          * @param array $arr Array with event data.
237          * @return int The new event id.
238          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
239          */
240         public static function store($arr)
241         {
242                 $a = self::getApp();
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['uri']       =        defaults($arr, 'uri'      , Item::newURI($event['uid']));
249                 $event['type']      =        defaults($arr, 'type'     , 'event');
250                 $event['summary']   =        defaults($arr, 'summary'  , '');
251                 $event['desc']      =        defaults($arr, 'desc'     , '');
252                 $event['location']  =        defaults($arr, 'location' , '');
253                 $event['allow_cid'] =        defaults($arr, 'allow_cid', '');
254                 $event['allow_gid'] =        defaults($arr, 'allow_gid', '');
255                 $event['deny_cid']  =        defaults($arr, 'deny_cid' , '');
256                 $event['deny_gid']  =        defaults($arr, 'deny_gid' , '');
257                 $event['adjust']    = intval(defaults($arr, 'adjust'   , 0));
258                 $event['nofinish']  = intval(defaults($arr, 'nofinish' , !empty($event['start']) && empty($event['finish'])));
259
260                 $event['created']   = DateTimeFormat::utc(defaults($arr, 'created'  , 'now'));
261                 $event['edited']    = DateTimeFormat::utc(defaults($arr, 'edited'   , 'now'));
262                 $event['start']     = DateTimeFormat::utc(defaults($arr, 'start'    , DBA::NULL_DATETIME));
263                 $event['finish']    = DateTimeFormat::utc(defaults($arr, 'finish'   , DBA::NULL_DATETIME));
264                 if ($event['finish'] < DBA::NULL_DATETIME) {
265                         $event['finish'] = DBA::NULL_DATETIME;
266                 }
267                 $private = intval(defaults($arr, 'private', 0));
268
269                 $conditions = ['uid' => $event['uid']];
270                 if ($event['cid']) {
271                         $conditions['id'] = $event['cid'];
272                 } else {
273                         $conditions['self'] = true;
274                 }
275
276                 $contact = DBA::selectFirst('contact', [], $conditions);
277
278                 // Existing event being modified.
279                 if ($event['id']) {
280                         // has the event actually changed?
281                         $existing_event = DBA::selectFirst('event', ['edited'], ['id' => $event['id'], 'uid' => $event['uid']]);
282                         if (!DBA::isResult($existing_event) || ($existing_event['edited'] === $event['edited'])) {
283
284                                 $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
285
286                                 return DBA::isResult($item) ? $item['id'] : 0;
287                         }
288
289                         $updated_fields = [
290                                 'edited'   => $event['edited'],
291                                 'start'    => $event['start'],
292                                 'finish'   => $event['finish'],
293                                 'summary'  => $event['summary'],
294                                 'desc'     => $event['desc'],
295                                 'location' => $event['location'],
296                                 'type'     => $event['type'],
297                                 'adjust'   => $event['adjust'],
298                                 'nofinish' => $event['nofinish'],
299                         ];
300
301                         DBA::update('event', $updated_fields, ['id' => $event['id'], 'uid' => $event['uid']]);
302
303                         $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]);
304                         if (DBA::isResult($item)) {
305                                 $object = '<object><type>' . XML::escape(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
306                                 $object .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
307                                 $object .= '</object>' . "\n";
308
309                                 $fields = ['body' => self::getBBCode($event), 'object' => $object, 'edited' => $event['edited']];
310                                 Item::update($fields, ['id' => $item['id']]);
311
312                                 $item_id = $item['id'];
313                         } else {
314                                 $item_id = 0;
315                         }
316
317                         Hook::callAll('event_updated', $event['id']);
318                 } else {
319                         $event['guid']  = defaults($arr, 'guid', System::createUUID());
320
321                         // New event. Store it.
322                         DBA::insert('event', $event);
323
324                         $item_id = 0;
325
326                         // Don't create an item for birthday events
327                         if ($event['type'] == 'event') {
328                                 $event['id'] = DBA::lastInsertId();
329
330                                 $item_arr = [];
331
332                                 $item_arr['uid']           = $event['uid'];
333                                 $item_arr['contact-id']    = $event['cid'];
334                                 $item_arr['uri']           = $event['uri'];
335                                 $item_arr['parent-uri']    = $event['uri'];
336                                 $item_arr['guid']          = $event['guid'];
337                                 $item_arr['plink']         = defaults($arr, 'plink', '');
338                                 $item_arr['post-type']     = Item::PT_EVENT;
339                                 $item_arr['wall']          = $event['cid'] ? 0 : 1;
340                                 $item_arr['contact-id']    = $contact['id'];
341                                 $item_arr['owner-name']    = $contact['name'];
342                                 $item_arr['owner-link']    = $contact['url'];
343                                 $item_arr['owner-avatar']  = $contact['thumb'];
344                                 $item_arr['author-name']   = $contact['name'];
345                                 $item_arr['author-link']   = $contact['url'];
346                                 $item_arr['author-avatar'] = $contact['thumb'];
347                                 $item_arr['title']         = '';
348                                 $item_arr['allow_cid']     = $event['allow_cid'];
349                                 $item_arr['allow_gid']     = $event['allow_gid'];
350                                 $item_arr['deny_cid']      = $event['deny_cid'];
351                                 $item_arr['deny_gid']      = $event['deny_gid'];
352                                 $item_arr['private']       = $private;
353                                 $item_arr['visible']       = 1;
354                                 $item_arr['verb']          = ACTIVITY_POST;
355                                 $item_arr['object-type']   = ACTIVITY_OBJ_EVENT;
356                                 $item_arr['origin']        = $event['cid'] === 0 ? 1 : 0;
357                                 $item_arr['body']          = self::getBBCode($event);
358                                 $item_arr['event-id']      = $event['id'];
359
360                                 $item_arr['object']  = '<object><type>' . XML::escape(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . XML::escape($event['uri']) . '</id>';
361                                 $item_arr['object'] .= '<content>' . XML::escape(self::getBBCode($event)) . '</content>';
362                                 $item_arr['object'] .= '</object>' . "\n";
363
364                                 $item_id = Item::insert($item_arr);
365                         }
366
367                         Hook::callAll("event_created", $event['id']);
368                 }
369
370                 return $item_id;
371         }
372
373         /**
374          * @brief Create an array with translation strings used for events.
375          *
376          * @return array Array with translations strings.
377          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
378          */
379         public static function getStrings()
380         {
381                 // First day of the week (0 = Sunday).
382                 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
383
384                 $i18n = [
385                         "firstDay" => $firstDay,
386                         "allday"   => L10n::t("all-day"),
387
388                         "Sun" => L10n::t("Sun"),
389                         "Mon" => L10n::t("Mon"),
390                         "Tue" => L10n::t("Tue"),
391                         "Wed" => L10n::t("Wed"),
392                         "Thu" => L10n::t("Thu"),
393                         "Fri" => L10n::t("Fri"),
394                         "Sat" => L10n::t("Sat"),
395
396                         "Sunday"    => L10n::t("Sunday"),
397                         "Monday"    => L10n::t("Monday"),
398                         "Tuesday"   => L10n::t("Tuesday"),
399                         "Wednesday" => L10n::t("Wednesday"),
400                         "Thursday"  => L10n::t("Thursday"),
401                         "Friday"    => L10n::t("Friday"),
402                         "Saturday"  => L10n::t("Saturday"),
403
404                         "Jan" => L10n::t("Jan"),
405                         "Feb" => L10n::t("Feb"),
406                         "Mar" => L10n::t("Mar"),
407                         "Apr" => L10n::t("Apr"),
408                         "May" => L10n::t("May"),
409                         "Jun" => L10n::t("Jun"),
410                         "Jul" => L10n::t("Jul"),
411                         "Aug" => L10n::t("Aug"),
412                         "Sep" => L10n::t("Sept"),
413                         "Oct" => L10n::t("Oct"),
414                         "Nov" => L10n::t("Nov"),
415                         "Dec" => L10n::t("Dec"),
416
417                         "January"   => L10n::t("January"),
418                         "February"  => L10n::t("February"),
419                         "March"     => L10n::t("March"),
420                         "April"     => L10n::t("April"),
421                         "May"       => L10n::t("May"),
422                         "June"      => L10n::t("June"),
423                         "July"      => L10n::t("July"),
424                         "August"    => L10n::t("August"),
425                         "September" => L10n::t("September"),
426                         "October"   => L10n::t("October"),
427                         "November"  => L10n::t("November"),
428                         "December"  => L10n::t("December"),
429
430                         "today" => L10n::t("today"),
431                         "month" => L10n::t("month"),
432                         "week"  => L10n::t("week"),
433                         "day"   => L10n::t("day"),
434
435                         "noevent" => L10n::t("No events to display"),
436
437                         "dtstart_label"  => L10n::t("Starts:"),
438                         "dtend_label"    => L10n::t("Finishes:"),
439                         "location_label" => L10n::t("Location:")
440                 ];
441
442                 return $i18n;
443         }
444
445         /**
446          * @brief Removes duplicated birthday events.
447          *
448          * @param array $dates Array of possibly duplicated events.
449          * @return array Cleaned events.
450          *
451          * @todo We should replace this with a separate update function if there is some time left.
452          */
453         private static function removeDuplicates(array $dates)
454         {
455                 $dates2 = [];
456
457                 foreach ($dates as $date) {
458                         if ($date['type'] == 'birthday') {
459                                 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
460                         } else {
461                                 $dates2[] = $date;
462                         }
463                 }
464                 return array_values($dates2);
465         }
466
467         /**
468          * @brief Get an event by its event ID.
469          *
470          * @param int    $owner_uid The User ID of the owner of the event
471          * @param int    $event_id  The ID of the event in the event table
472          * @param string $sql_extra
473          * @return array Query result
474          * @throws \Exception
475          */
476         public static function getListById($owner_uid, $event_id, $sql_extra = '')
477         {
478                 $return = [];
479
480                 // Ownly allow events if there is a valid owner_id.
481                 if ($owner_uid == 0) {
482                         return $return;
483                 }
484
485                 // Query for the event by event id
486                 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
487                         LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
488                         WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
489                         intval($owner_uid),
490                         intval($event_id)
491                 );
492
493                 if (DBA::isResult($r)) {
494                         $return = self::removeDuplicates($r);
495                 }
496
497                 return $return;
498         }
499
500         /**
501          * @brief Get all events in a specific time frame.
502          *
503          * @param int    $owner_uid    The User ID of the owner of the events.
504          * @param array  $event_params An associative array with
505          *                             int 'ignore' =>
506          *                             string 'start' => Start time of the timeframe.
507          *                             string 'finish' => Finish time of the timeframe.
508          *                             string 'adjust_start' =>
509          *                             string 'adjust_finish' =>
510          *
511          * @param string $sql_extra    Additional sql conditions (e.g. permission request).
512          *
513          * @return array Query results.
514          * @throws \Exception
515          */
516         public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
517         {
518                 $return = [];
519
520                 // Only allow events if there is a valid owner_id.
521                 if ($owner_uid == 0) {
522                         return $return;
523                 }
524
525                 // Query for the event by date.
526                 // @todo Slow query (518 seconds to run), to be optimzed
527                 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
528                                 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
529                                 WHERE `event`.`uid` = %d AND event.ignore = %d
530                                 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
531                                 OR  (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
532                                 $sql_extra ",
533                                 intval($owner_uid),
534                                 intval($event_params["ignore"]),
535                                 DBA::escape($event_params["start"]),
536                                 DBA::escape($event_params["start"]),
537                                 DBA::escape($event_params["finish"]),
538                                 DBA::escape($event_params["adjust_start"]),
539                                 DBA::escape($event_params["adjust_start"]),
540                                 DBA::escape($event_params["adjust_finish"])
541                 );
542
543                 if (DBA::isResult($r)) {
544                         $return = self::removeDuplicates($r);
545                 }
546
547                 return $return;
548         }
549
550         /**
551          * @brief Convert an array query results in an array which could be used by the events template.
552          *
553          * @param array $event_result Event query array.
554          * @return array Event array for the template.
555          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
556          * @throws \ImagickException
557          */
558         public static function prepareListForTemplate(array $event_result)
559         {
560                 $event_list = [];
561
562                 $last_date = '';
563                 $fmt = L10n::t('l, F j');
564                 foreach ($event_result as $event) {
565                         $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
566                         if (!DBA::isResult($item)) {
567                                 // Using default values when no item had been found
568                                 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
569                         }
570
571                         $event = array_merge($event, $item);
572
573                         $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c')  : DateTimeFormat::utc($event['start'], 'c');
574                         $j     = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j')  : DateTimeFormat::utc($event['start'], 'j');
575                         $day   = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
576                         $day   = L10n::getDay($day);
577
578                         if ($event['nofinish']) {
579                                 $end = null;
580                         } else {
581                                 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
582                         }
583
584                         $is_first = ($day !== $last_date);
585
586                         $last_date = $day;
587
588                         // Show edit and drop actions only if the user is the owner of the event and the event
589                         // is a real event (no bithdays).
590                         $edit = null;
591                         $copy = null;
592                         $drop = null;
593                         if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
594                                 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event')     , '', ''] : null;
595                                 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
596                                 $drop =                  [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event')   , '', ''];
597                         }
598
599                         $title = BBCode::convert(Strings::escapeHtml($event['summary']));
600                         if (!$title) {
601                                 list($title, $_trash) = explode("<br", BBCode::convert(Strings::escapeHtml($event['desc'])), 2);
602                         }
603
604                         $author_link = $event['author-link'];
605                         $plink       = $event['plink'];
606
607                         $event['author-link'] = Contact::magicLink($author_link);
608                         $event['plink']       = Contact::magicLink($author_link, $plink);
609
610                         $html = self::getHTML($event);
611                         $event['summary']  = BBCode::convert(Strings::escapeHtml($event['summary']));
612                         $event['desc']     = BBCode::convert(Strings::escapeHtml($event['desc']));
613                         $event['location'] = BBCode::convert(Strings::escapeHtml($event['location']));
614                         $event_list[] = [
615                                 'id'       => $event['id'],
616                                 'start'    => $start,
617                                 'end'      => $end,
618                                 'allDay'   => false,
619                                 'title'    => $title,
620                                 'j'        => $j,
621                                 'd'        => $day,
622                                 'edit'     => $edit,
623                                 'drop'     => $drop,
624                                 'copy'     => $copy,
625                                 'is_first' => $is_first,
626                                 'item'     => $event,
627                                 'html'     => $html,
628                                 'plink'    => [$event['plink'], L10n::t('link to source'), '', ''],
629                         ];
630                 }
631
632                 return $event_list;
633         }
634
635         /**
636          * @brief Format event to export format (ical/csv).
637          *
638          * @param array  $events Query result for events.
639          * @param string $format The output format (ical/csv).
640          *
641          * @param        $timezone
642          * @return string Content according to selected export format.
643          *
644          * @todo  Implement timezone support
645          */
646         private static function formatListForExport(array $events, $format, $timezone)
647         {
648                 if (!count($events)) {
649                         return '';
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                 $user = DBA::selectFirst('user', ['timezone'], ['uid' => $uid]);
799                 if (DBA::isResult($user)) {
800                         $timezone = $user['timezone'];
801                 }
802
803                 // Get all events which are owned by a uid (respects permissions).
804                 $events = self::getListByUserId($uid);
805
806                 // We have the events that are available for the requestor.
807                 // Now format the output according to the requested format.
808                 $res = self::formatListForExport($events, $format, $timezone);
809
810                 // If there are results the precess was successfull.
811                 if (!empty($res)) {
812                         $process = true;
813                 }
814
815                 // Get the file extension for the format.
816                 switch ($format) {
817                         case "ical":
818                                 $file_ext = "ics";
819                                 break;
820
821                         case "csv":
822                                 $file_ext = "csv";
823                                 break;
824
825                         default:
826                                 $file_ext = "";
827                 }
828
829                 $return = [
830                         'success'   => $process,
831                         'format'    => $format,
832                         'extension' => $file_ext,
833                         'content'   => $res,
834                 ];
835
836                 return $return;
837         }
838
839         /**
840          * @brief Format an item array with event data to HTML.
841          *
842          * @param array $item Array with item and event data.
843          * @return string HTML output.
844          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
845          * @throws \ImagickException
846          */
847         public static function getItemHTML(array $item) {
848                 $same_date = false;
849                 $finish    = false;
850
851                 // Set the different time formats.
852                 $dformat       = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
853                 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
854                 $tformat       = L10n::t('g:i A'); // 8:01 AM.
855
856                 // Convert the time to different formats.
857                 $dtstart_dt = L10n::getDay(
858                         $item['event-adjust'] ?
859                                 DateTimeFormat::local($item['event-start'], $dformat)
860                                 : DateTimeFormat::utc($item['event-start'], $dformat)
861                 );
862                 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
863                 // Format: Jan till Dec.
864                 $month_short = L10n::getDayShort(
865                         $item['event-adjust'] ?
866                                 DateTimeFormat::local($item['event-start'], 'M')
867                                 : DateTimeFormat::utc($item['event-start'], 'M')
868                 );
869                 // Format: 1 till 31.
870                 $date_short = $item['event-adjust'] ?
871                         DateTimeFormat::local($item['event-start'], 'j')
872                         : DateTimeFormat::utc($item['event-start'], 'j');
873                 $start_time = $item['event-adjust'] ?
874                         DateTimeFormat::local($item['event-start'], $tformat)
875                         : DateTimeFormat::utc($item['event-start'], $tformat);
876                 $start_short = L10n::getDayShort(
877                         $item['event-adjust'] ?
878                                 DateTimeFormat::local($item['event-start'], $dformat_short)
879                                 : DateTimeFormat::utc($item['event-start'], $dformat_short)
880                 );
881
882                 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
883                 if (!$item['event-nofinish']) {
884                         $finish = true;
885                         $dtend_dt  = L10n::getDay(
886                                 $item['event-adjust'] ?
887                                         DateTimeFormat::local($item['event-finish'], $dformat)
888                                         : DateTimeFormat::utc($item['event-finish'], $dformat)
889                         );
890                         $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
891                         $end_short = L10n::getDayShort(
892                                 $item['event-adjust'] ?
893                                         DateTimeFormat::local($item['event-finish'], $dformat_short)
894                                         : DateTimeFormat::utc($item['event-finish'], $dformat_short)
895                         );
896                         $end_time = $item['event-adjust'] ?
897                                 DateTimeFormat::local($item['event-finish'], $tformat)
898                                 : DateTimeFormat::utc($item['event-finish'], $tformat);
899                         // Check if start and finish time is at the same day.
900                         if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
901                                 $same_date = true;
902                         }
903                 } else {
904                         $dtend_title = '';
905                         $dtend_dt = '';
906                         $end_time = '';
907                         $end_short = '';
908                 }
909
910                 // Format the event location.
911                 $location = self::locationToArray($item['event-location']);
912
913                 // Construct the profile link (magic-auth).
914                 $profile_link = Contact::magicLinkById($item['author-id']);
915
916                 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
917                 $return = Renderer::replaceMacros($tpl, [
918                         '$id'             => $item['event-id'],
919                         '$title'          => prepare_text($item['event-summary']),
920                         '$dtstart_label'  => L10n::t('Starts:'),
921                         '$dtstart_title'  => $dtstart_title,
922                         '$dtstart_dt'     => $dtstart_dt,
923                         '$finish'         => $finish,
924                         '$dtend_label'    => L10n::t('Finishes:'),
925                         '$dtend_title'    => $dtend_title,
926                         '$dtend_dt'       => $dtend_dt,
927                         '$month_short'    => $month_short,
928                         '$date_short'     => $date_short,
929                         '$same_date'      => $same_date,
930                         '$start_time'     => $start_time,
931                         '$start_short'    => $start_short,
932                         '$end_time'       => $end_time,
933                         '$end_short'      => $end_short,
934                         '$author_name'    => $item['author-name'],
935                         '$author_link'    => $profile_link,
936                         '$author_avatar'  => $item['author-avatar'],
937                         '$description'    => prepare_text($item['event-desc']),
938                         '$location_label' => L10n::t('Location:'),
939                         '$show_map_label' => L10n::t('Show map'),
940                         '$hide_map_label' => L10n::t('Hide map'),
941                         '$map_btn_label'  => L10n::t('Show map'),
942                         '$location'       => $location
943                 ]);
944
945                 return $return;
946         }
947
948         /**
949          * @brief Format a string with map bbcode to an array with location data.
950          *
951          * Note: The string must only contain location data. A string with no bbcode will be
952          * handled as location name.
953          *
954          * @param string $s The string with the bbcode formatted location data.
955          *
956          * @return array The array with the location data.
957          *  'name' => The name of the location,<br>
958          * 'address' => The address of the location,<br>
959          * 'coordinates' => Latitude‎ and longitude‎ (e.g. '48.864716,2.349014').<br>
960          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
961          */
962         private static function locationToArray($s = '') {
963                 if ($s == '') {
964                         return [];
965                 }
966
967                 $location = ['name' => $s];
968
969                 // Map tag with location name - e.g. [map]Paris[/map].
970                 if (strpos($s, '[/map]') !== false) {
971                         $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
972                         if (intval($found) > 0 && array_key_exists(1, $match)) {
973                                 $location['address'] =  $match[1];
974                                 // Remove the map bbcode from the location name.
975                                 $location['name'] = str_replace($match[0], "", $s);
976                         }
977                 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
978                 } elseif (strpos($s, '[map=') !== false) {
979                         $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
980                         if (intval($found) > 0 && array_key_exists(1, $match)) {
981                                 $location['coordinates'] =  $match[1];
982                                 // Remove the map bbcode from the location name.
983                                 $location['name'] = str_replace($match[0], "", $s);
984                         }
985                 }
986
987                 $location['name'] = prepare_text($location['name']);
988
989                 // Construct the map HTML.
990                 if (isset($location['address'])) {
991                         $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
992                 } elseif (isset($location['coordinates'])) {
993                         $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
994                 }
995
996                 return $location;
997         }
998
999         /**
1000          * @brief Add new birthday event for this person
1001          *
1002          * @param array  $contact  Contact array, expects: id, uid, url, name
1003          * @param string $birthday Birthday of the contact
1004          * @return bool
1005          * @throws \Exception
1006          */
1007         public static function createBirthday($contact, $birthday)
1008         {
1009                 // Check for duplicates
1010                 $condition = [
1011                         'uid' => $contact['uid'],
1012                         'cid' => $contact['id'],
1013                         'start' => DateTimeFormat::utc($birthday),
1014                         'type' => 'birthday'
1015                 ];
1016                 if (DBA::exists('event', $condition)) {
1017                         return false;
1018                 }
1019
1020                 /*
1021                  * Add new birthday event for this person
1022                  *
1023                  * summary is just a readable placeholder in case the event is shared
1024                  * with others. We will replace it during presentation to our $importer
1025                  * to contain a sparkle link and perhaps a photo.
1026                  */
1027                 $values = [
1028                         'uid'     => $contact['uid'],
1029                         'cid'     => $contact['id'],
1030                         'start'   => DateTimeFormat::utc($birthday),
1031                         'finish'  => DateTimeFormat::utc($birthday . ' + 1 day '),
1032                         'summary' => L10n::t('%s\'s birthday', $contact['name']),
1033                         'desc'    => L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'),
1034                         'type'    => 'birthday',
1035                         'adjust'  => 0
1036                 ];
1037
1038                 self::store($values);
1039
1040                 return true;
1041         }
1042 }