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