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