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