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