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