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