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