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