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