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