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