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