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