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