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