]> git.mxchange.org Git - friendica.git/blob - include/event.php
initilize $sh_disabled
[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                                 $copy = ((! $rr['cid']) ? array(System::baseUrl() . '/events/copy/' . $rr['id'], t('Duplicate event'), '', '') : null);
595                                 $drop = array(System::baseUrl() . '/events/drop/' . $rr['id'], t('Delete event'), '', '');
596                         }
597
598                         $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
599                         if (! $title) {
600                                 list($title, $_trash) = explode("<br", bbcode($rr['desc']), 2);
601                                 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
602                         }
603
604                         $html = format_event_html($rr);
605                         $rr['desc'] = bbcode($rr['desc']);
606                         $rr['location'] = bbcode($rr['location']);
607                         $events[] = array(
608                                 'id'     => $rr['id'],
609                                 'start'  => $start,
610                                 'end'    => $end,
611                                 'allDay' => false,
612                                 'title'  => $title,
613
614                                 'j'        => $j,
615                                 'd'        => $d,
616                                 'edit'     => $edit,
617                                 'drop'     => $drop,
618                                 'copy'     => $copy,
619                                 'is_first' => $is_first,
620                                 'item'     => $rr,
621                                 'html'     => $html,
622                                 'plink'    => array($rr['plink'], t('link to source'), '', ''),
623                         );
624                 }
625         }
626
627         return $events;
628 }
629
630 /**
631  * @brief Format event to export format (ical/csv)
632  *
633  * @param array $events Query result for events
634  * @param string $format The output format (ical/csv)
635  * @param string $timezone The timezone of the user (not implemented yet)
636  *
637  * @return string Content according to selected export format
638  */
639 function event_format_export ($events, $format = 'ical', $timezone) {
640         if (! ((is_array($events)) && count($events))) {
641                 return;
642         }
643
644         switch ($format) {
645                 // Format the exported data as a CSV file
646                 case "csv":
647                         header("Content-type: text/csv");
648                         $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
649
650                         foreach ($events as $event) {
651                                 /// @todo The time / date entries don't include any information about the
652                                 /// timezone the event is scheduled in :-/
653                                 $tmp1 = strtotime($event['start']);
654                                 $tmp2 = strtotime($event['finish']);
655                                 $time_format = "%H:%M:%S";
656                                 $date_format = "%Y-%m-%d";
657
658                                 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
659                                         '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
660                                         '", "' . strftime($date_format, $tmp2) .
661                                         '", "' . strftime($time_format, $tmp2) .
662                                         '", "' . $event['location'] . '"' . PHP_EOL;
663                         }
664                         break;
665
666                 // Format the exported data as a ics file
667                 case "ical":
668                         header("Content-type: text/ics");
669                         $o = 'BEGIN:VCALENDAR' . PHP_EOL
670                                 . 'VERSION:2.0' . PHP_EOL
671                                 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
672                         ///  @todo include timezone informations in cases were the time is not in UTC
673                         //  see http://tools.ietf.org/html/rfc2445#section-4.8.3
674                         //              . 'BEGIN:VTIMEZONE' . PHP_EOL
675                         //              . 'TZID:' . $timezone . PHP_EOL
676                         //              . 'END:VTIMEZONE' . PHP_EOL;
677                         //  TODO instead of PHP_EOL CRLF should be used for long entries
678                         //       but test your solution against http://icalvalid.cloudapp.net/
679                         //       also long lines SHOULD be split at 75 characters length
680                         foreach ($events as $event) {
681
682                                 if ($event['adjust'] == 1) {
683                                         $UTC = 'Z';
684                                 } else {
685                                         $UTC = '';
686                                 }
687                                 $o .= 'BEGIN:VEVENT' . PHP_EOL;
688
689                                 if ($event['start']) {
690                                         $tmp = strtotime($event['start']);
691                                         $dtformat = "%Y%m%dT%H%M%S" . $UTC;
692                                         $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
693                                 }
694
695                                 if (!$event['nofinish']) {
696                                         $tmp = strtotime($event['finish']);
697                                         $dtformat = "%Y%m%dT%H%M%S" . $UTC;
698                                         $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
699                                 }
700
701                                 if ($event['summary']) {
702                                         $tmp = $event['summary'];
703                                         $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
704                                         $tmp = addcslashes($tmp, ',;');
705                                         $o .= 'SUMMARY:' . $tmp . PHP_EOL;
706                                 }
707
708                                 if ($event['desc']) {
709                                         $tmp = $event['desc'];
710                                         $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
711                                         $tmp = addcslashes($tmp, ',;');
712                                         $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
713                                 }
714
715                                 if ($event['location']) {
716                                         $tmp = $event['location'];
717                                         $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
718                                         $tmp = addcslashes($tmp, ',;');
719                                         $o .= 'LOCATION:' . $tmp . PHP_EOL;
720                                 }
721
722                                 $o .= 'END:VEVENT' . PHP_EOL;
723                                 $o .= PHP_EOL;
724                         }
725
726                         $o .= 'END:VCALENDAR' . PHP_EOL;
727                         break;
728         }
729
730         return $o;
731 }
732
733 /**
734  * @brief Get all events for a user ID
735  *
736  *    The query for events is done permission sensitive
737  *    If the user is the owner of the calendar he/she
738  *    will get all of his/her available events.
739  *    If the user is only a visitor only the public events will
740  *    be available
741  *
742  * @param int $uid The user ID
743  * @param int $sql_extra Additional sql conditions for permission
744  *
745  * @return array Query results
746  */
747 function events_by_uid($uid = 0, $sql_extra = '') {
748         if ($uid == 0) {
749                 return;
750         }
751
752         // The permission condition if no condition was transmitted
753         if ($sql_extra == '') {
754                 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
755         }
756
757         // Does the user who requests happen to be the owner of the events
758         // requested? then show all of your events, otherwise only those that
759         // don't have limitations set in allow_cid and allow_gid
760         if (local_user() == $uid) {
761                 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
762                         FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
763                         intval($uid)
764                 );
765         } else {
766                 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
767                         FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
768                         intval($uid)
769                 );
770         }
771
772         if (dbm::is_result($r)) {
773                 return $r;
774         }
775 }
776
777 /**
778  *
779  * @param int $uid The user ID
780  * @param string $format Output format (ical/csv)
781  * @return array With the results
782  *      bool 'success' => True if the processing was successful
783  *      string 'format' => The output format
784  *      string 'extension' => The file extension of the output format
785  *      string 'content' => The formatted output content
786  *
787  * @todo Respect authenticated users with events_by_uid()
788  */
789 function event_export($uid, $format = 'ical') {
790
791         $process = false;
792
793         // We are allowed to show events
794         // get the timezone the user is in
795         $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
796         if (dbm::is_result($r)) {
797                 $timezone = $r[0]['timezone'];
798         }
799
800         // Get all events which are owned by a uid (respects permissions);
801         $events = events_by_uid($uid);
802
803         // We have the events that are available for the requestor
804         // now format the output according to the requested format
805         if (count($events)) {
806                 $res = event_format_export($events, $format, $timezone);
807         }
808
809         // If there are results the precess was successfull
810         if (x($res)) {
811                 $process = true;
812         }
813
814         // Get the file extension for the format
815         switch ($format) {
816                 case "ical":
817                         $file_ext = "ics";
818                         break;
819
820                 case "csv":
821                         $file_ext = "csv";
822                         break;
823
824                 default:
825                         $file_ext = "";
826         }
827
828         $arr = array(
829                 'success'   => $process,
830                 'format'    => $format,
831                 'extension' => $file_ext,
832                 'content'   => $res,
833         );
834
835         return $arr;
836 }
837
838 /**
839  * @brief Get the events widget
840  *
841  * @return string Formated html of the evens widget
842  */
843 function widget_events() {
844         $a = get_app();
845
846         $owner_uid = $a->data['user']['uid'];
847         // $a->data is only available if the profile page is visited. If the visited page is not part
848         // of the profile page it should be the personal /events page. So we can use $a->user
849         $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
850
851
852         // The permission testing is a little bit tricky because we have to respect many cases
853
854         // It's not the private events page (we don't get the $owner_uid for /events)
855         if (! local_user() && ! $owner_uid) {
856                 return;
857         }
858
859         /*
860          * Cal logged in user (test permission at foreign profile page)
861          * If the $owner uid is available we know it is part of one of the profile pages (like /cal)
862          * So we have to test if if it's the own profile page of the logged in user
863          * or a foreign one. For foreign profile pages we need to check if the feature
864          * for exporting the cal is enabled (otherwise the widget would appear for logged in users
865          * on foreigen profile pages even if the widget is disabled)
866          */
867         if (intval($owner_uid) && local_user() !== $owner_uid && ! feature_enabled($owner_uid, "export_calendar")) {
868                 return;
869         }
870
871         /*
872          * If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
873          * export feature isn't enabled
874          */
875         if (intval($owner_uid) && ! local_user() && ! feature_enabled($owner_uid, "export_calendar")) {
876                 return;
877         }
878
879         return replace_macros(get_markup_template("events_aside.tpl"), array(
880                 '$etitle' => t("Export"),
881                 '$export_ical' => t("Export calendar as ical"),
882                 '$export_csv' => t("Export calendar as csv"),
883                 '$user' => $user
884         ));
885 }