]> git.mxchange.org Git - friendica.git/blob - include/event.php
a0509aa0fee048261f378e18bf0b1a66c0022415
[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\PConfig;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11
12 require_once 'include/bbcode.php';
13 require_once 'include/map.php';
14 require_once 'include/datetime.php';
15 require_once "include/conversation.php";
16
17 function format_event_html($ev, $simple = false) {
18         if (! ((is_array($ev)) && count($ev))) {
19                 return '';
20         }
21
22         $bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM.
23
24         $event_start = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
25                         $ev['start'] , $bd_format ))
26                         : day_translate(datetime_convert('UTC', 'UTC',
27                         $ev['start'] , $bd_format)));
28
29         $event_end = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
30                                 $ev['finish'] , $bd_format ))
31                                 : day_translate(datetime_convert('UTC', 'UTC',
32                                 $ev['finish'] , $bd_format )));
33
34         if ($simple) {
35                 $o = "<h3>" . bbcode($ev['summary']) . "</h3>";
36
37                 $o .= "<div>" . bbcode($ev['desc']) . "</div>";
38
39                 $o .= "<h4>" . t('Starts:') . "</h4><p>" . $event_start . "</p>";
40
41                 if (! $ev['nofinish']) {
42                         $o .= "<h4>" . t('Finishes:') . "</h4><p>" . $event_end  ."</p>";
43                 }
44
45                 if (strlen($ev['location'])) {
46                         $o .= "<h4>" . t('Location:') . "</h4><p>" . $ev['location'] . "</p>";
47                 }
48
49                 return $o;
50         }
51
52         $o = '<div class="vevent">' . "\r\n";
53
54         $o .= '<div class="summary event-summary">' . bbcode($ev['summary']) . '</div>' . "\r\n";
55
56         $o .= '<div class="event-start"><span class="event-label">' . t('Starts:') . '</span>&nbsp;<span class="dtstart" title="'
57                 . datetime_convert('UTC', 'UTC', $ev['start'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
58                 . '" >'.$event_start
59                 . '</span></div>' . "\r\n";
60
61         if (! $ev['nofinish']) {
62                 $o .= '<div class="event-end" ><span class="event-label">' . t('Finishes:') . '</span>&nbsp;<span class="dtend" title="'
63                         . datetime_convert('UTC', 'UTC', $ev['finish'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
64                         . '" >'.$event_end
65                         . '</span></div>' . "\r\n";
66         }
67
68         $o .= '<div class="description event-description">' . bbcode($ev['desc']) . '</div>' . "\r\n";
69
70         if (strlen($ev['location'])) {
71                 $o .= '<div class="event-location"><span class="event-label">' . t('Location:') . '</span>&nbsp;<span class="location">'
72                         . bbcode($ev['location'])
73                         . '</span></div>' . "\r\n";
74
75                 // Include a map of the location if the [map] BBCode is used.
76                 if (strpos($ev['location'], "[map") !== false) {
77                         $map = generate_named_map($ev['location']);
78                         if ($map !== $ev['location']) {
79                                 $o.= $map;
80                         }
81                 }
82         }
83
84         $o .= '</div>' . "\r\n";
85         return $o;
86 }
87
88 /**
89  * @brief Convert an array with event data to bbcode.
90  * 
91  * @param array $ev Array which conains the event data.
92  * @return string The event as a bbcode formatted string.
93  */
94 function format_event_bbcode($ev) {
95
96         $o = '';
97
98         if ($ev['summary']) {
99                 $o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';
100         }
101
102         if ($ev['desc']) {
103                 $o .= '[event-description]' . $ev['desc'] . '[/event-description]';
104         }
105
106         if ($ev['start']) {
107                 $o .= '[event-start]' . $ev['start'] . '[/event-start]';
108         }
109
110         if (($ev['finish']) && (! $ev['nofinish'])) {
111                 $o .= '[event-finish]' . $ev['finish'] . '[/event-finish]';
112         }
113
114         if ($ev['location']) {
115                 $o .= '[event-location]' . $ev['location'] . '[/event-location]';
116         }
117
118         if ($ev['adjust']) {
119                 $o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
120         }
121
122         return $o;
123 }
124
125 /**
126  * @brief Extract bbcode formatted event data from a string
127  *     and convert it to html.
128  * 
129  * @params: string $s The string which should be parsed for event data.
130  * @return string The html output.
131  */
132 function bbtovcal($s) {
133         $o = '';
134         $ev = bbtoevent($s);
135
136         if ($ev['desc']) {
137                 $o = format_event_html($ev);
138         }
139
140         return $o;
141 }
142
143 /**
144  * @brief Extract bbcode formatted event data from a string.
145  * 
146  * @params: string $s The string which should be parsed for event data.
147  * @return array The array with the event information.
148  */
149 function bbtoevent($s) {
150
151         $ev = array();
152
153         $match = '';
154         if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $s, $match)) {
155                 $ev['summary'] = $match[1];
156         }
157
158         $match = '';
159         if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $s, $match)) {
160                 $ev['desc'] = $match[1];
161         }
162
163         $match = '';
164         if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $s, $match)) {
165                 $ev['start'] = $match[1];
166         }
167
168         $match = '';
169         if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $s, $match)) {
170                 $ev['finish'] = $match[1];
171         }
172
173         $match = '';
174         if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $s, $match)) {
175                 $ev['location'] = $match[1];
176         }
177
178         $match = '';
179         if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $s, $match)) {
180                 $ev['adjust'] = $match[1];
181         }
182
183         $ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
184
185         return $ev;
186 }
187
188 function sort_by_date($a) {
189
190         usort($a,'ev_compare');
191         return $a;
192 }
193
194 function ev_compare($a,$b) {
195
196         $date_a = (($a['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $a['start']) : $a['start']);
197         $date_b = (($b['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $b['start']) : $b['start']);
198
199         if ($date_a === $date_b) {
200                 return strcasecmp($a['desc'], $b['desc']);
201         }
202
203         return strcmp($date_a, $date_b);
204 }
205
206 /**
207  * @brief Delete an event from the event table.
208  * 
209  * Note: This function does only delete the event from the event table not its
210  * related entry in the item table.
211  * 
212  * @param int $event_id Event ID.
213  * @return void
214  */
215 function event_delete($event_id) {
216         if ($event_id == 0) {
217                 return;
218         }
219
220         dba::delete('event', array('id' => $event_id));
221         logger("Deleted event ".$event_id, LOGGER_DEBUG);
222 }
223
224 /**
225  * @brief Store the event.
226  * 
227  * Store the event in the event table and create an event item in the item table.
228  * 
229  * @param array $arr Array with event data.
230  * @return int The event id.
231  */
232 function event_store($arr) {
233
234         require_once 'include/datetime.php';
235         require_once 'include/items.php';
236         require_once 'include/bbcode.php';
237
238         $a = get_app();
239
240         $arr['created'] = (($arr['created'])     ? $arr['created']         : datetime_convert());
241         $arr['edited']  = (($arr['edited'])      ? $arr['edited']          : datetime_convert());
242         $arr['type']    = (($arr['type'])        ? $arr['type']            : 'event' );
243         $arr['cid']     = ((intval($arr['cid'])) ? intval($arr['cid'])     : 0);
244         $arr['uri']     = (x($arr, 'uri')        ? $arr['uri']             : item_new_uri($a->get_hostname(), $arr['uid']));
245         $arr['private'] = ((x($arr, 'private'))  ? intval($arr['private']) : 0);
246         $arr['guid']    = get_guid(32);
247
248         if ($arr['cid']) {
249                 $c = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
250                         intval($arr['cid']),
251                         intval($arr['uid'])
252                 );
253         } else {
254                 $c = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
255                         intval($arr['uid'])
256                 );
257         }
258
259         if (DBM::is_result($c)) {
260                 $contact = $c[0];
261         }
262
263
264         // Existing event being modified.
265
266         if ($arr['id']) {
267
268                 // has the event actually changed?
269
270                 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
271                         intval($arr['id']),
272                         intval($arr['uid'])
273                 );
274                 if ((! DBM::is_result($r)) || ($r[0]['edited'] === $arr['edited'])) {
275
276                         // Nothing has changed. Grab the item id to return.
277
278                         $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
279                                 intval($arr['id']),
280                                 intval($arr['uid'])
281                         );
282                         return ((DBM::is_result($r)) ? $r[0]['id'] : 0);
283                 }
284
285                 // The event changed. Update it.
286
287                 $r = q("UPDATE `event` SET
288                         `edited` = '%s',
289                         `start` = '%s',
290                         `finish` = '%s',
291                         `summary` = '%s',
292                         `desc` = '%s',
293                         `location` = '%s',
294                         `type` = '%s',
295                         `adjust` = %d,
296                         `nofinish` = %d
297                         WHERE `id` = %d AND `uid` = %d",
298
299                         dbesc($arr['edited']),
300                         dbesc($arr['start']),
301                         dbesc($arr['finish']),
302                         dbesc($arr['summary']),
303                         dbesc($arr['desc']),
304                         dbesc($arr['location']),
305                         dbesc($arr['type']),
306                         intval($arr['adjust']),
307                         intval($arr['nofinish']),
308                         intval($arr['id']),
309                         intval($arr['uid'])
310                 );
311                 $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
312                         intval($arr['id']),
313                         intval($arr['uid'])
314                 );
315                 if (DBM::is_result($r)) {
316                         $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
317                         $object .= '<content>' . xmlify(format_event_bbcode($arr)) . '</content>';
318                         $object .= '</object>' . "\n";
319
320                         q("UPDATE `item` SET `body` = '%s', `object` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d",
321                                 dbesc(format_event_bbcode($arr)),
322                                 dbesc($object),
323                                 dbesc($arr['edited']),
324                                 intval($r[0]['id']),
325                                 intval($arr['uid'])
326                         );
327
328                         $item_id = $r[0]['id'];
329                 } else {
330                         $item_id = 0;
331                 }
332
333                 call_hooks("event_updated", $arr['id']);
334
335                 return $item_id;
336         } else {
337                 // New event. Store it.
338
339                 $r = q("INSERT INTO `event` (`uid`,`cid`,`guid`,`uri`,`created`,`edited`,`start`,`finish`,`summary`, `desc`,`location`,`type`,
340                         `adjust`,`nofinish`,`allow_cid`,`allow_gid`,`deny_cid`,`deny_gid`)
341                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
342                         intval($arr['uid']),
343                         intval($arr['cid']),
344                         dbesc($arr['guid']),
345                         dbesc($arr['uri']),
346                         dbesc($arr['created']),
347                         dbesc($arr['edited']),
348                         dbesc($arr['start']),
349                         dbesc($arr['finish']),
350                         dbesc($arr['summary']),
351                         dbesc($arr['desc']),
352                         dbesc($arr['location']),
353                         dbesc($arr['type']),
354                         intval($arr['adjust']),
355                         intval($arr['nofinish']),
356                         dbesc($arr['allow_cid']),
357                         dbesc($arr['allow_gid']),
358                         dbesc($arr['deny_cid']),
359                         dbesc($arr['deny_gid'])
360                 );
361
362                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
363                         dbesc($arr['uri']),
364                         intval($arr['uid'])
365                 );
366                 if (DBM::is_result($r)) {
367                         $event = $r[0];
368                 }
369
370                 $item_arr = array();
371
372                 $item_arr['uid']           = $arr['uid'];
373                 $item_arr['contact-id']    = $arr['cid'];
374                 $item_arr['uri']           = $arr['uri'];
375                 $item_arr['parent-uri']    = $arr['uri'];
376                 $item_arr['guid']          = $arr['guid'];
377                 $item_arr['type']          = 'activity';
378                 $item_arr['wall']          = (($arr['cid']) ? 0 : 1);
379                 $item_arr['contact-id']    = $contact['id'];
380                 $item_arr['owner-name']    = $contact['name'];
381                 $item_arr['owner-link']    = $contact['url'];
382                 $item_arr['owner-avatar']  = $contact['thumb'];
383                 $item_arr['author-name']   = $contact['name'];
384                 $item_arr['author-link']   = $contact['url'];
385                 $item_arr['author-avatar'] = $contact['thumb'];
386                 $item_arr['title']         = '';
387                 $item_arr['allow_cid']     = $arr['allow_cid'];
388                 $item_arr['allow_gid']     = $arr['allow_gid'];
389                 $item_arr['deny_cid']      = $arr['deny_cid'];
390                 $item_arr['deny_gid']      = $arr['deny_gid'];
391                 $item_arr['private']       = $arr['private'];
392                 $item_arr['last-child']    = 1;
393                 $item_arr['visible']       = 1;
394                 $item_arr['verb']          = ACTIVITY_POST;
395                 $item_arr['object-type']   = ACTIVITY_OBJ_EVENT;
396                 $item_arr['origin']        = ((intval($arr['cid']) == 0) ? 1 : 0);
397                 $item_arr['body']          = format_event_bbcode($event);
398
399
400                 $item_arr['object']  = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
401                 $item_arr['object'] .= '<content>' . xmlify(format_event_bbcode($event)) . '</content>';
402                 $item_arr['object'] .= '</object>' . "\n";
403
404                 $item_id = item_store($item_arr);
405
406                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
407                         intval($arr['uid'])
408                 );
409                 //if (DBM::is_result($r))
410                 //      $plink = System::baseUrl() . '/display/' . $r[0]['nickname'] . '/' . $item_id;
411
412
413                 if ($item_id) {
414                         //q("UPDATE `item` SET `plink` = '%s', `event-id` = %d  WHERE `uid` = %d AND `id` = %d",
415                         //      dbesc($plink),
416                         //      intval($event['id']),
417                         //      intval($arr['uid']),
418                         //      intval($item_id)
419                         //);
420                         q("UPDATE `item` SET `event-id` = %d  WHERE `uid` = %d AND `id` = %d",
421                                 intval($event['id']),
422                                 intval($arr['uid']),
423                                 intval($item_id)
424                         );
425                 }
426
427                 call_hooks("event_created", $event['id']);
428
429                 return $item_id;
430         }
431 }
432
433 /**
434  * @brief Create an array with translation strings used for events.
435  * 
436  * @return array Array with translations strings.
437  */
438 function get_event_strings() {
439
440         // First day of the week (0 = Sunday).
441         $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
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 }