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