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