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