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