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