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