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