]> git.mxchange.org Git - friendica.git/blob - include/event.php
8d47b5fba56838d1f841359f3375739b79e7cd2b
[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         q("DELETE FROM `event` WHERE `id` = %d", intval($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');
441         if ($firstDay === false) {
442                 $firstDay = 0;
443         }
444
445         $i18n = array(
446                         "firstDay" => $firstDay,
447                         "allday"   => t("all-day"),
448
449                         "Sun" => t("Sun"),
450                         "Mon" => t("Mon"),
451                         "Tue" => t("Tue"),
452                         "Wed" => t("Wed"),
453                         "Thu" => t("Thu"),
454                         "Fri" => t("Fri"),
455                         "Sat" => t("Sat"),
456
457                         "Sunday"    => t("Sunday"),
458                         "Monday"    => t("Monday"),
459                         "Tuesday"   => t("Tuesday"),
460                         "Wednesday" => t("Wednesday"),
461                         "Thursday"  => t("Thursday"),
462                         "Friday"    => t("Friday"),
463                         "Saturday"  => t("Saturday"),
464
465                         "Jan" => t("Jan"),
466                         "Feb" => t("Feb"),
467                         "Mar" => t("Mar"),
468                         "Apr" => t("Apr"),
469                         "May" => t("May"),
470                         "Jun" => t("Jun"),
471                         "Jul" => t("Jul"),
472                         "Aug" => t("Aug"),
473                         "Sep" => t("Sept"),
474                         "Oct" => t("Oct"),
475                         "Nov" => t("Nov"),
476                         "Dec" => t("Dec"),
477
478                         "January"   => t("January"),
479                         "February"  => t("February"),
480                         "March"     => t("March"),
481                         "April"     => t("April"),
482                         "May"       => t("May"),
483                         "June"      => t("June"),
484                         "July"      => t("July"),
485                         "August"    => t("August"),
486                         "September" => t("September"),
487                         "October"   => t("October"),
488                         "November"  => t("November"),
489                         "December"  => t("December"),
490
491                         "today" => t("today"),
492                         "month" => t("month"),
493                         "week"  => t("week"),
494                         "day"   => t("day"),
495
496                         "noevent" => t("No events to display"),
497
498                         "dtstart_label"  => t("Starts:"),
499                         "dtend_label"    => t("Finishes:"),
500                         "location_label" => t("Location:")
501                 );
502
503         return $i18n;
504 }
505
506 /**
507  * @brief Removes duplicated birthday events.
508  *
509  * @param array $dates Array of possibly duplicated events.
510  * @return array Cleaned events.
511  *
512  * @todo We should replace this with a separate update function if there is some time left.
513  */
514 function event_remove_duplicates($dates) {
515         $dates2 = array();
516
517         foreach ($dates as $date) {
518                 if ($date['type'] == 'birthday') {
519                         $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
520                 } else {
521                         $dates2[] = $date;
522                 }
523         }
524         return $dates2;
525 }
526
527 /**
528  * @brief Get an event by its event ID.
529  *
530  * @param type $owner_uid The User ID of the owner of the event
531  * @param type $event_params An assoziative array with
532  *      int 'event_id' => The ID of the event in the event table
533  * @param type $sql_extra
534  * @return array Query result
535  */
536 function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
537         // Ownly allow events if there is a valid owner_id.
538         if ($owner_uid == 0) {
539                 return;
540         }
541
542         // Query for the event by event id
543         $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
544                         `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
545                 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
546                 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
547                 intval($owner_uid),
548                 intval($event_params["event_id"])
549         );
550
551         if (DBM::is_result($r)) {
552                 return event_remove_duplicates($r);
553         }
554 }
555
556 /**
557  * @brief Get all events in a specific timeframe.
558  *
559  * @param int $owner_uid The User ID of the owner of the events.
560  * @param array $event_params An assoziative array with
561  *      int 'ignored' =><br>
562  *      string 'start' => Start time of the timeframe.<br>
563  *      string 'finish' => Finish time of the timeframe.<br>
564  *      string 'adjust_start' =><br>
565  *      string 'adjust_start' =>
566  *
567  * @param string $sql_extra Additional sql conditions (e.g. permission request).
568  * 
569  * @return array Query results.
570  */
571 function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
572         // Only allow events if there is a valid owner_id.
573         if ($owner_uid == 0) {
574                 return;
575         }
576
577         // Query for the event by date.
578         $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
579                                 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
580                         LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
581                         WHERE `event`.`uid` = %d AND event.ignore = %d
582                         AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
583                         OR  (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
584                         $sql_extra ",
585                         intval($owner_uid),
586                         intval($event_params["ignored"]),
587                         dbesc($event_params["start"]),
588                         dbesc($event_params["start"]),
589                         dbesc($event_params["finish"]),
590                         dbesc($event_params["adjust_start"]),
591                         dbesc($event_params["adjust_start"]),
592                         dbesc($event_params["adjust_finish"])
593         );
594
595         if (DBM::is_result($r)) {
596                 return event_remove_duplicates($r);
597         }
598 }
599
600 /**
601  * @brief Convert an array query results in an arry which could be used by the events template.
602  *
603  * @param array $arr Event query array.
604  * @return array Event array for the template.
605  */
606 function process_events($arr) {
607         $events=array();
608
609         $last_date = '';
610         $fmt = t('l, F j');
611         if (count($arr)) {
612                 foreach ($arr as $rr) {
613                         $j = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'j') : datetime_convert('UTC', 'UTC', $rr['start'], 'j'));
614                         $d = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], $fmt) : datetime_convert('UTC', 'UTC', $rr['start'], $fmt));
615                         $d = day_translate($d);
616
617                         $start = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'c') : datetime_convert('UTC', 'UTC', $rr['start'], 'c'));
618                         if ($rr['nofinish']) {
619                                 $end = null;
620                         } else {
621                                 $end = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['finish'], 'c') : datetime_convert('UTC', 'UTC', $rr['finish'], 'c'));
622                         }
623
624                         $is_first = ($d !== $last_date);
625
626                         $last_date = $d;
627
628                         // Show edit and drop actions only if the user is the owner of the event and the event
629                         // is a real event (no bithdays).
630                         if (local_user() && local_user() == $rr['uid'] && $rr['type'] == 'event') {
631                                 $edit = ((! $rr['cid']) ? array(System::baseUrl() . '/events/event/' . $rr['id'], t('Edit event'), '', '') : null);
632                                 $copy = ((! $rr['cid']) ? array(System::baseUrl() . '/events/copy/' . $rr['id'], t('Duplicate event'), '', '') : null);
633                                 $drop = array(System::baseUrl() . '/events/drop/' . $rr['id'], t('Delete event'), '', '');
634                         }
635
636                         $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
637                         if (! $title) {
638                                 list($title, $_trash) = explode("<br", bbcode($rr['desc']), 2);
639                                 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
640                         }
641
642                         $html = format_event_html($rr);
643                         $rr['desc'] = bbcode($rr['desc']);
644                         $rr['location'] = bbcode($rr['location']);
645                         $events[] = array(
646                                 'id'     => $rr['id'],
647                                 'start'  => $start,
648                                 'end'    => $end,
649                                 'allDay' => false,
650                                 'title'  => $title,
651
652                                 'j'        => $j,
653                                 'd'        => $d,
654                                 'edit'     => $edit,
655                                 'drop'     => $drop,
656                                 'copy'     => $copy,
657                                 'is_first' => $is_first,
658                                 'item'     => $rr,
659                                 'html'     => $html,
660                                 'plink'    => array($rr['plink'], t('link to source'), '', ''),
661                         );
662                 }
663         }
664
665         return $events;
666 }
667
668 /**
669  * @brief Format event to export format (ical/csv).
670  *
671  * @param array $events Query result for events.
672  * @param string $format The output format (ical/csv).
673  * @param string $timezone The timezone of the user (not implemented yet).
674  *
675  * @return string Content according to selected export format.
676  */
677 function event_format_export ($events, $format = 'ical', $timezone) {
678         if (! ((is_array($events)) && count($events))) {
679                 return;
680         }
681
682         switch ($format) {
683                 // Format the exported data as a CSV file.
684                 case "csv":
685                         header("Content-type: text/csv");
686                         $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
687
688                         foreach ($events as $event) {
689                                 /// @todo The time / date entries don't include any information about the
690                                 /// timezone the event is scheduled in :-/
691                                 $tmp1 = strtotime($event['start']);
692                                 $tmp2 = strtotime($event['finish']);
693                                 $time_format = "%H:%M:%S";
694                                 $date_format = "%Y-%m-%d";
695
696                                 $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
697                                         '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
698                                         '", "' . strftime($date_format, $tmp2) .
699                                         '", "' . strftime($time_format, $tmp2) .
700                                         '", "' . $event['location'] . '"' . PHP_EOL;
701                         }
702                         break;
703
704                 // Format the exported data as a ics file.
705                 case "ical":
706                         header("Content-type: text/ics");
707                         $o = 'BEGIN:VCALENDAR' . PHP_EOL
708                                 . 'VERSION:2.0' . PHP_EOL
709                                 . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
710                         ///  @todo include timezone informations in cases were the time is not in UTC
711                         //  see http://tools.ietf.org/html/rfc2445#section-4.8.3
712                         //              . 'BEGIN:VTIMEZONE' . PHP_EOL
713                         //              . 'TZID:' . $timezone . PHP_EOL
714                         //              . 'END:VTIMEZONE' . PHP_EOL;
715                         //  TODO instead of PHP_EOL CRLF should be used for long entries
716                         //       but test your solution against http://icalvalid.cloudapp.net/
717                         //       also long lines SHOULD be split at 75 characters length
718                         foreach ($events as $event) {
719                                 if ($event['adjust'] == 1) {
720                                         $UTC = 'Z';
721                                 } else {
722                                         $UTC = '';
723                                 }
724                                 $o .= 'BEGIN:VEVENT' . PHP_EOL;
725
726                                 if ($event['start']) {
727                                         $tmp = strtotime($event['start']);
728                                         $dtformat = "%Y%m%dT%H%M%S" . $UTC;
729                                         $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
730                                 }
731
732                                 if (!$event['nofinish']) {
733                                         $tmp = strtotime($event['finish']);
734                                         $dtformat = "%Y%m%dT%H%M%S" . $UTC;
735                                         $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
736                                 }
737
738                                 if ($event['summary']) {
739                                         $tmp = $event['summary'];
740                                         $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
741                                         $tmp = addcslashes($tmp, ',;');
742                                         $o .= 'SUMMARY:' . $tmp . PHP_EOL;
743                                 }
744
745                                 if ($event['desc']) {
746                                         $tmp = $event['desc'];
747                                         $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
748                                         $tmp = addcslashes($tmp, ',;');
749                                         $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
750                                 }
751
752                                 if ($event['location']) {
753                                         $tmp = $event['location'];
754                                         $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
755                                         $tmp = addcslashes($tmp, ',;');
756                                         $o .= 'LOCATION:' . $tmp . PHP_EOL;
757                                 }
758
759                                 $o .= 'END:VEVENT' . PHP_EOL;
760                                 $o .= PHP_EOL;
761                         }
762
763                         $o .= 'END:VCALENDAR' . PHP_EOL;
764                         break;
765         }
766
767         return $o;
768 }
769
770 /**
771  * @brief Get all events for a user ID.
772  * 
773  *    The query for events is done permission sensitive.
774  *    If the user is the owner of the calendar he/she
775  *    will get all of his/her available events.
776  *    If the user is only a visitor only the public events will
777  *    be available.
778  *
779  * @param int $uid The user ID.
780  * @param int $sql_extra Additional sql conditions for permission.
781  *
782  * @return array Query results.
783  */
784 function events_by_uid($uid = 0, $sql_extra = '') {
785         if ($uid == 0) {
786                 return;
787         }
788
789         // The permission condition if no condition was transmitted.
790         if ($sql_extra == '') {
791                 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
792         }
793
794         // Does the user who requests happen to be the owner of the events
795         // requested? then show all of your events, otherwise only those that
796         // don't have limitations set in allow_cid and allow_gid.
797         if (local_user() == $uid) {
798                 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
799                         FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
800                         intval($uid)
801                 );
802         } else {
803                 $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
804                         FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
805                         intval($uid)
806                 );
807         }
808
809         if (DBM::is_result($r)) {
810                 return $r;
811         }
812 }
813
814 /**
815  *
816  * @param int $uid The user ID.
817  * @param string $format Output format (ical/csv).
818  * @return array With the results:
819  *      bool 'success' => True if the processing was successful,<br>
820  *      string 'format' => The output format,<br>
821  *      string 'extension' => The file extension of the output format,<br>
822  *      string 'content' => The formatted output content.<br>
823  *
824  * @todo Respect authenticated users with events_by_uid().
825  */
826 function event_export($uid, $format = 'ical') {
827
828         $process = false;
829
830         // We are allowed to show events.
831         // Get the timezone the user is in.
832         $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
833         if (DBM::is_result($r)) {
834                 $timezone = $r[0]['timezone'];
835         }
836
837         // Get all events which are owned by a uid (respects permissions).
838         $events = events_by_uid($uid);
839
840         // We have the events that are available for the requestor.
841         // Now format the output according to the requested format.
842         if (count($events)) {
843                 $res = event_format_export($events, $format, $timezone);
844         }
845
846         // If there are results the precess was successfull.
847         if (x($res)) {
848                 $process = true;
849         }
850
851         // Get the file extension for the format.
852         switch ($format) {
853                 case "ical":
854                         $file_ext = "ics";
855                         break;
856
857                 case "csv":
858                         $file_ext = "csv";
859                         break;
860
861                 default:
862                         $file_ext = "";
863         }
864
865         $arr = array(
866                 'success'   => $process,
867                 'format'    => $format,
868                 'extension' => $file_ext,
869                 'content'   => $res,
870         );
871
872         return $arr;
873 }
874
875 /**
876  * @brief Get the events widget.
877  *
878  * @return string Formated html of the evens widget.
879  */
880 function widget_events() {
881         $a = get_app();
882
883         $owner_uid = $a->data['user']['uid'];
884         // $a->data is only available if the profile page is visited. If the visited page is not part
885         // of the profile page it should be the personal /events page. So we can use $a->user.
886         $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
887
888
889         // The permission testing is a little bit tricky because we have to respect many cases.
890
891         // It's not the private events page (we don't get the $owner_uid for /events).
892         if (! local_user() && ! $owner_uid) {
893                 return;
894         }
895
896         /*
897          * Cal logged in user (test permission at foreign profile page).
898          * If the $owner uid is available we know it is part of one of the profile pages (like /cal).
899          * So we have to test if if it's the own profile page of the logged in user
900          * or a foreign one. For foreign profile pages we need to check if the feature
901          * for exporting the cal is enabled (otherwise the widget would appear for logged in users
902          * on foreigen profile pages even if the widget is disabled).
903          */
904         if (intval($owner_uid) && local_user() !== $owner_uid && ! feature_enabled($owner_uid, "export_calendar")) {
905                 return;
906         }
907
908         /*
909          * If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
910          * export feature isn't enabled.
911          */
912         if (intval($owner_uid) && ! local_user() && ! feature_enabled($owner_uid, "export_calendar")) {
913                 return;
914         }
915
916         return replace_macros(get_markup_template("events_aside.tpl"), array(
917                 '$etitle' => t("Export"),
918                 '$export_ical' => t("Export calendar as ical"),
919                 '$export_csv' => t("Export calendar as csv"),
920                 '$user' => $user
921         ));
922 }
923
924 /**
925  * @brief Format an item array with event data to HTML.
926  * 
927  * @param arr $item Array with item and event data.
928  * @return string HTML output.
929  */
930 function format_event_item($item) {
931         $same_date = false;
932         $finish    = false;
933
934         // Set the different time formats.
935         $dformat       = t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
936         $dformat_short = t('D g:i A'); // Fri 8:01 AM.
937         $tformat       = t('g:i A'); // 8:01 AM.
938
939         // Convert the time to different formats.
940         $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)));
941         $dtstart_title = datetime_convert('UTC', 'UTC', $item['event-start'], (($item['event-adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s'));
942         // Format: Jan till Dec.
943         $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')));
944         // Format: 1 till 31.
945         $date_short = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], 'j') : datetime_convert('UTC', 'UTC', $item['event-start'], 'j'));
946         $start_time = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], $tformat) : datetime_convert('UTC', 'UTC', $item['event-start'], $tformat));
947         $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)));
948
949         // If the option 'nofinisch' isn't set, we need to format the finish date/time.
950         if (!$item['event-nofinish']) {
951                 $finish = true;
952                 $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)));
953                 $dtend_title = datetime_convert('UTC', 'UTC', $item['event-finish'], (($item['event-adjust'])   ? ATOM_TIME : 'Y-m-d\TH:i:s'));
954                 $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)));
955                 $end_time = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-finish'], $tformat) : datetime_convert('UTC', 'UTC', $item['event-finish'], $tformat));
956                 // Check if start and finish time is at the same day.
957                 if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
958                         $same_date = true;
959                 }
960         }
961
962         // Format the event location.
963         $evloc = event_location2array($item['event-location']);
964         $location = array();
965
966         if (isset($evloc['name'])) {
967                 $location['name'] = prepare_text($evloc['name']);
968         }
969         // Construct the map HTML.
970         if (isset($evloc['address'])) {
971                 $location['map'] = '<div class="map">' . generate_named_map($evloc['address']) . '</div>';
972         } elseif (isset($evloc['coordinates'])) {
973                 $location['map'] = '<div class="map">' . generate_map(str_replace('/', ' ', $evloc['coordinates'])) . '</div>';
974         }
975
976         // Construct the profile link (magic-auth).
977         $sp = false;
978         $profile_link = best_link_url($item, $sp);
979
980         if (!$sp) {
981                 $profile_link = zrl($profile_link);
982         }
983
984         $event = replace_macros(get_markup_template('event_stream_item.tpl'), array(
985                 '$id'             => $item['event-id'],
986                 '$title'          => prepare_text($item['event-summary']),
987                 '$dtstart_label'  => t('Starts:'),
988                 '$dtstart_title'  => $dtstart_title,
989                 '$dtstart_dt'     => $dtstart_dt,
990                 '$finish'         => $finish,
991                 '$dtend_label'    => t('Finishes:'),
992                 '$dtend_title'    => $dtend_title,
993                 '$dtend_dt'       => $dtend_dt,
994                 '$month_short'    => $month_short,
995                 '$date_short'     => $date_short,
996                 '$same_date'      => $same_date,
997                 '$start_time'     => $start_time,
998                 '$start_short'    => $start_short,
999                 '$end_time'       => $end_time,
1000                 '$end_short'      => $end_short,
1001                 '$author_name'    => $item['author-name'],
1002                 '$author_link'    => $profile_link,
1003                 '$author_avatar'  => $item['author-avatar'],
1004                 '$description'    => prepare_text($item['event-desc']),
1005                 '$location_label' => t('Location:'),
1006                 '$show_map_label' => t('Show map'),
1007                 '$hide_map_label' => t('Hide map'),
1008                 '$map_btn_label'  => t('Show map'),
1009                 '$location'       => $location
1010         ));
1011
1012         return $event;
1013 }
1014
1015 /**
1016  * @brief Format a string with map bbcode to an array with location data.
1017  * 
1018  * Note: The string must only contain location data. A string with no bbcode will be
1019  * handled as location name.
1020  * 
1021  * @param string $s The string with the bbcode formatted location data.
1022  * 
1023  * @return array The array with the location data.
1024  *  'name' => The name of the location,<br>
1025  * 'address' => The address of the location,<br>
1026  * 'coordinates' => Latitude‎ and longitude‎ (e.g. '48.864716,2.349014').<br>
1027  */
1028 function event_location2array($s = '') {
1029         if ($s == '') {
1030                 return;
1031         }
1032
1033         $location = array('name' => $s);
1034
1035         // Map tag with location name - e.g. [map]Paris[/map].
1036         if (strpos($s, '[/map]') !== false) {
1037                 $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
1038                 if (intval($found) > 0 && array_key_exists(1, $match)) {
1039                         $location['address'] =  $match[1];
1040                         // Remove the map bbcode from the location name.
1041                         $location['name'] = str_replace($match[0], "", $s);
1042                 }
1043         // Map tag with coordinates - e.g. [map=48.864716,2.349014].
1044         } elseif (strpos($s, '[map=') !== false) {
1045                 $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
1046                 if (intval($found) > 0 && array_key_exists(1, $match)) {
1047                         $location['coordinates'] =  $match[1];
1048                         // Remove the map bbcode from the location name.
1049                         $location['name'] = str_replace($match[0], "", $s);
1050                 }
1051         }
1052
1053         return $location;
1054 }