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