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