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