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