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