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