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