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