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