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