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