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