]> git.mxchange.org Git - friendica.git/blob - src/Model/Event.php
get markup template
[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\Model\Contact;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Map;
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 = day_translate(
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 = day_translate(
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>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($event['uri']) . '</id>';
306                                 $object .= '<content>' . xmlify(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                         $event['id'] = DBA::lastInsertId();
325
326                         $item_arr = [];
327
328                         $item_arr['uid']           = $event['uid'];
329                         $item_arr['contact-id']    = $event['cid'];
330                         $item_arr['uri']           = $event['uri'];
331                         $item_arr['parent-uri']    = $event['uri'];
332                         $item_arr['guid']          = $event['guid'];
333                         $item_arr['plink']         = defaults($arr, 'plink', '');
334                         $item_arr['post-type']     = Item::PT_EVENT;
335                         $item_arr['wall']          = $event['cid'] ? 0 : 1;
336                         $item_arr['contact-id']    = $contact['id'];
337                         $item_arr['owner-name']    = $contact['name'];
338                         $item_arr['owner-link']    = $contact['url'];
339                         $item_arr['owner-avatar']  = $contact['thumb'];
340                         $item_arr['author-name']   = $contact['name'];
341                         $item_arr['author-link']   = $contact['url'];
342                         $item_arr['author-avatar'] = $contact['thumb'];
343                         $item_arr['title']         = '';
344                         $item_arr['allow_cid']     = $event['allow_cid'];
345                         $item_arr['allow_gid']     = $event['allow_gid'];
346                         $item_arr['deny_cid']      = $event['deny_cid'];
347                         $item_arr['deny_gid']      = $event['deny_gid'];
348                         $item_arr['private']       = $private;
349                         $item_arr['visible']       = 1;
350                         $item_arr['verb']          = ACTIVITY_POST;
351                         $item_arr['object-type']   = ACTIVITY_OBJ_EVENT;
352                         $item_arr['origin']        = $event['cid'] === 0 ? 1 : 0;
353                         $item_arr['body']          = self::getBBCode($event);
354                         $item_arr['event-id']      = $event['id'];
355
356                         $item_arr['object']  = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($event['uri']) . '</id>';
357                         $item_arr['object'] .= '<content>' . xmlify(self::getBBCode($event)) . '</content>';
358                         $item_arr['object'] .= '</object>' . "\n";
359
360                         $item_id = Item::insert($item_arr);
361
362                         Addon::callHooks("event_created", $event['id']);
363                 }
364
365                 return $item_id;
366         }
367
368         /**
369          * @brief Create an array with translation strings used for events.
370          *
371          * @return array Array with translations strings.
372          */
373         public static function getStrings()
374         {
375                 // First day of the week (0 = Sunday).
376                 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
377
378                 $i18n = [
379                         "firstDay" => $firstDay,
380                         "allday"   => L10n::t("all-day"),
381
382                         "Sun" => L10n::t("Sun"),
383                         "Mon" => L10n::t("Mon"),
384                         "Tue" => L10n::t("Tue"),
385                         "Wed" => L10n::t("Wed"),
386                         "Thu" => L10n::t("Thu"),
387                         "Fri" => L10n::t("Fri"),
388                         "Sat" => L10n::t("Sat"),
389
390                         "Sunday"    => L10n::t("Sunday"),
391                         "Monday"    => L10n::t("Monday"),
392                         "Tuesday"   => L10n::t("Tuesday"),
393                         "Wednesday" => L10n::t("Wednesday"),
394                         "Thursday"  => L10n::t("Thursday"),
395                         "Friday"    => L10n::t("Friday"),
396                         "Saturday"  => L10n::t("Saturday"),
397
398                         "Jan" => L10n::t("Jan"),
399                         "Feb" => L10n::t("Feb"),
400                         "Mar" => L10n::t("Mar"),
401                         "Apr" => L10n::t("Apr"),
402                         "May" => L10n::t("May"),
403                         "Jun" => L10n::t("Jun"),
404                         "Jul" => L10n::t("Jul"),
405                         "Aug" => L10n::t("Aug"),
406                         "Sep" => L10n::t("Sept"),
407                         "Oct" => L10n::t("Oct"),
408                         "Nov" => L10n::t("Nov"),
409                         "Dec" => L10n::t("Dec"),
410
411                         "January"   => L10n::t("January"),
412                         "February"  => L10n::t("February"),
413                         "March"     => L10n::t("March"),
414                         "April"     => L10n::t("April"),
415                         "May"       => L10n::t("May"),
416                         "June"      => L10n::t("June"),
417                         "July"      => L10n::t("July"),
418                         "August"    => L10n::t("August"),
419                         "September" => L10n::t("September"),
420                         "October"   => L10n::t("October"),
421                         "November"  => L10n::t("November"),
422                         "December"  => L10n::t("December"),
423
424                         "today" => L10n::t("today"),
425                         "month" => L10n::t("month"),
426                         "week"  => L10n::t("week"),
427                         "day"   => L10n::t("day"),
428
429                         "noevent" => L10n::t("No events to display"),
430
431                         "dtstart_label"  => L10n::t("Starts:"),
432                         "dtend_label"    => L10n::t("Finishes:"),
433                         "location_label" => L10n::t("Location:")
434                 ];
435
436                 return $i18n;
437         }
438
439         /**
440          * @brief Removes duplicated birthday events.
441          *
442          * @param array $dates Array of possibly duplicated events.
443          * @return array Cleaned events.
444          *
445          * @todo We should replace this with a separate update function if there is some time left.
446          */
447         private static function removeDuplicates(array $dates)
448         {
449                 $dates2 = [];
450
451                 foreach ($dates as $date) {
452                         if ($date['type'] == 'birthday') {
453                                 $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
454                         } else {
455                                 $dates2[] = $date;
456                         }
457                 }
458                 return array_values($dates2);
459         }
460
461         /**
462          * @brief Get an event by its event ID.
463          *
464          * @param int    $owner_uid The User ID of the owner of the event
465          * @param int    $event_id  The ID of the event in the event table
466          * @param string $sql_extra
467          * @return array Query result
468          */
469         public static function getListById($owner_uid, $event_id, $sql_extra = '')
470         {
471                 $return = [];
472
473                 // Ownly allow events if there is a valid owner_id.
474                 if ($owner_uid == 0) {
475                         return $return;
476                 }
477
478                 // Query for the event by event id
479                 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
480                         LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
481                         WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
482                         intval($owner_uid),
483                         intval($event_id)
484                 );
485
486                 if (DBA::isResult($r)) {
487                         $return = self::removeDuplicates($r);
488                 }
489
490                 return $return;
491         }
492
493         /**
494          * @brief Get all events in a specific time frame.
495          *
496          * @param int $owner_uid The User ID of the owner of the events.
497          * @param array $event_params An associative array with
498          *      int 'ignore' =>
499          *      string 'start' => Start time of the timeframe.
500          *      string 'finish' => Finish time of the timeframe.
501          *      string 'adjust_start' =>
502          *      string 'adjust_finish' =>
503          *
504          * @param string $sql_extra Additional sql conditions (e.g. permission request).
505          *
506          * @return array Query results.
507          */
508         public static function getListByDate($owner_uid, $event_params, $sql_extra = '')
509         {
510                 $return = [];
511
512                 // Only allow events if there is a valid owner_id.
513                 if ($owner_uid == 0) {
514                         return $return;
515                 }
516
517                 // Query for the event by date.
518                 // @todo Slow query (518 seconds to run), to be optimzed
519                 $r = q("SELECT `event`.*, `item`.`id` AS `itemid` FROM `event`
520                                 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
521                                 WHERE `event`.`uid` = %d AND event.ignore = %d
522                                 AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
523                                 OR  (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
524                                 $sql_extra ",
525                                 intval($owner_uid),
526                                 intval($event_params["ignore"]),
527                                 DBA::escape($event_params["start"]),
528                                 DBA::escape($event_params["start"]),
529                                 DBA::escape($event_params["finish"]),
530                                 DBA::escape($event_params["adjust_start"]),
531                                 DBA::escape($event_params["adjust_start"]),
532                                 DBA::escape($event_params["adjust_finish"])
533                 );
534
535                 if (DBA::isResult($r)) {
536                         $return = self::removeDuplicates($r);
537                 }
538
539                 return $return;
540         }
541
542         /**
543          * @brief Convert an array query results in an array which could be used by the events template.
544          *
545          * @param array $event_result Event query array.
546          * @return array Event array for the template.
547          */
548         public static function prepareListForTemplate(array $event_result)
549         {
550                 $event_list = [];
551
552                 $last_date = '';
553                 $fmt = L10n::t('l, F j');
554                 foreach ($event_result as $event) {
555                         $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
556                         if (!DBA::isResult($item)) {
557                                 // Using default values when no item had been found
558                                 $item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
559                         }
560
561                         $event = array_merge($event, $item);
562
563                         $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c')  : DateTimeFormat::utc($event['start'], 'c');
564                         $j     = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j')  : DateTimeFormat::utc($event['start'], 'j');
565                         $day   = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);
566                         $day   = day_translate($day);
567
568                         if ($event['nofinish']) {
569                                 $end = null;
570                         } else {
571                                 $end = $event['adjust'] ? DateTimeFormat::local($event['finish'], 'c') : DateTimeFormat::utc($event['finish'], 'c');
572                         }
573
574                         $is_first = ($day !== $last_date);
575
576                         $last_date = $day;
577
578                         // Show edit and drop actions only if the user is the owner of the event and the event
579                         // is a real event (no bithdays).
580                         $edit = null;
581                         $copy = null;
582                         $drop = null;
583                         if (local_user() && local_user() == $event['uid'] && $event['type'] == 'event') {
584                                 $edit = !$event['cid'] ? [System::baseUrl() . '/events/event/' . $event['id'], L10n::t('Edit event')     , '', ''] : null;
585                                 $copy = !$event['cid'] ? [System::baseUrl() . '/events/copy/' . $event['id'] , L10n::t('Duplicate event'), '', ''] : null;
586                                 $drop =                  [System::baseUrl() . '/events/drop/' . $event['id'] , L10n::t('Delete event')   , '', ''];
587                         }
588
589                         $title = strip_tags(html_entity_decode(BBCode::convert($event['summary']), ENT_QUOTES, 'UTF-8'));
590                         if (!$title) {
591                                 list($title, $_trash) = explode("<br", BBCode::convert($event['desc']), 2);
592                                 $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
593                         }
594
595                         $author_link = $event['author-link'];
596                         $plink       = $event['plink'];
597
598                         $event['author-link'] = Contact::magicLink($author_link);
599                         $event['plink']       = Contact::magicLink($author_link, $plink);
600
601                         $html = self::getHTML($event);
602                         $event['desc']     = BBCode::convert($event['desc']);
603                         $event['location'] = BBCode::convert($event['location']);
604                         $event_list[] = [
605                                 'id'       => $event['id'],
606                                 'start'    => $start,
607                                 'end'      => $end,
608                                 'allDay'   => false,
609                                 'title'    => $title,
610                                 'j'        => $j,
611                                 'd'        => $day,
612                                 'edit'     => $edit,
613                                 'drop'     => $drop,
614                                 'copy'     => $copy,
615                                 'is_first' => $is_first,
616                                 'item'     => $event,
617                                 'html'     => $html,
618                                 'plink'    => [$event['plink'], L10n::t('link to source'), '', ''],
619                         ];
620                 }
621
622                 return $event_list;
623         }
624
625         /**
626          * @brief Format event to export format (ical/csv).
627          *
628          * @param array  $events   Query result for events.
629          * @param string $format   The output format (ical/csv).
630          * @param string $timezone The timezone of the user (not implemented yet).
631          *
632          * @return string Content according to selected export format.
633          *
634          * @todo Implement timezone support
635          */
636         private static function formatListForExport(array $events, $format, $timezone)
637         {
638                 if (!count($events)) {
639                         return '';
640                 }
641
642                 switch ($format) {
643                         // Format the exported data as a CSV file.
644                         case "csv":
645                                 header("Content-type: text/csv");
646                                 $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
647
648                                 foreach ($events as $event) {
649                                         /// @todo The time / date entries don't include any information about the
650                                         /// timezone the event is scheduled in :-/
651                                         $tmp1 = strtotime($event['start']);
652                                         $tmp2 = strtotime($event['finish']);
653                                         $time_format = "%H:%M:%S";
654                                         $date_format = "%Y-%m-%d";
655
656                                         $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
657                                                 '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
658                                                 '", "' . strftime($date_format, $tmp2) .
659                                                 '", "' . strftime($time_format, $tmp2) .
660                                                 '", "' . $event['location'] . '"' . PHP_EOL;
661                                 }
662                                 break;
663
664                         // Format the exported data as a ics file.
665                         case "ical":
666                                 header("Content-type: text/ics");
667                                 $o = 'BEGIN:VCALENDAR' . PHP_EOL
668                                         . 'VERSION:2.0' . PHP_EOL
669                                         . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
670                                 ///  @todo include timezone informations in cases were the time is not in UTC
671                                 //  see http://tools.ietf.org/html/rfc2445#section-4.8.3
672                                 //              . 'BEGIN:VTIMEZONE' . PHP_EOL
673                                 //              . 'TZID:' . $timezone . PHP_EOL
674                                 //              . 'END:VTIMEZONE' . PHP_EOL;
675                                 //  TODO instead of PHP_EOL CRLF should be used for long entries
676                                 //       but test your solution against http://icalvalid.cloudapp.net/
677                                 //       also long lines SHOULD be split at 75 characters length
678                                 foreach ($events as $event) {
679                                         if ($event['adjust'] == 1) {
680                                                 $UTC = 'Z';
681                                         } else {
682                                                 $UTC = '';
683                                         }
684                                         $o .= 'BEGIN:VEVENT' . PHP_EOL;
685
686                                         if ($event['start']) {
687                                                 $tmp = strtotime($event['start']);
688                                                 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
689                                                 $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
690                                         }
691
692                                         if (!$event['nofinish']) {
693                                                 $tmp = strtotime($event['finish']);
694                                                 $dtformat = "%Y%m%dT%H%M%S" . $UTC;
695                                                 $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
696                                         }
697
698                                         if ($event['summary']) {
699                                                 $tmp = $event['summary'];
700                                                 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
701                                                 $tmp = addcslashes($tmp, ',;');
702                                                 $o .= 'SUMMARY:' . $tmp . PHP_EOL;
703                                         }
704
705                                         if ($event['desc']) {
706                                                 $tmp = $event['desc'];
707                                                 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
708                                                 $tmp = addcslashes($tmp, ',;');
709                                                 $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
710                                         }
711
712                                         if ($event['location']) {
713                                                 $tmp = $event['location'];
714                                                 $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
715                                                 $tmp = addcslashes($tmp, ',;');
716                                                 $o .= 'LOCATION:' . $tmp . PHP_EOL;
717                                         }
718
719                                         $o .= 'END:VEVENT' . PHP_EOL;
720                                         $o .= PHP_EOL;
721                                 }
722
723                                 $o .= 'END:VCALENDAR' . PHP_EOL;
724                                 break;
725                 }
726
727                 return $o;
728         }
729
730         /**
731          * @brief Get all events for a user ID.
732          *
733          *    The query for events is done permission sensitive.
734          *    If the user is the owner of the calendar they
735          *    will get all of their available events.
736          *    If the user is only a visitor only the public events will
737          *    be available.
738          *
739          * @param int $uid The user ID.
740          *
741          * @return array Query results.
742          */
743         private static function getListByUserId($uid = 0)
744         {
745                 $return = [];
746
747                 if ($uid == 0) {
748                         return $return;
749                 }
750
751                 $fields = ['start', 'finish', 'adjust', 'summary', 'desc', 'location', 'nofinish'];
752
753                 $conditions = ['uid' => $uid, 'cid' => 0];
754
755                 // Does the user who requests happen to be the owner of the events
756                 // requested? then show all of your events, otherwise only those that
757                 // don't have limitations set in allow_cid and allow_gid.
758                 if (local_user() != $uid) {
759                         $conditions += ['allow_cid' => '', 'allow_gid' => ''];
760                 }
761
762                 $events = DBA::select('event', $fields, $conditions);
763                 if (DBA::isResult($events)) {
764                         $return = DBA::toArray($events);
765                 }
766
767                 return $return;
768         }
769
770         /**
771          *
772          * @param int $uid The user ID.
773          * @param string $format Output format (ical/csv).
774          * @return array With the results:
775          *      bool 'success' => True if the processing was successful,<br>
776          *      string 'format' => The output format,<br>
777          *      string 'extension' => The file extension of the output format,<br>
778          *      string 'content' => The formatted output content.<br>
779          *
780          * @todo Respect authenticated users with events_by_uid().
781          */
782         public static function exportListByUserId($uid, $format = 'ical')
783         {
784                 $process = false;
785
786                 $user = DBA::selectFirst('user', ['timezone'], ['uid' => $uid]);
787                 if (DBA::isResult($user)) {
788                         $timezone = $user['timezone'];
789                 }
790
791                 // Get all events which are owned by a uid (respects permissions).
792                 $events = self::getListByUserId($uid);
793
794                 // We have the events that are available for the requestor.
795                 // Now format the output according to the requested format.
796                 $res = self::formatListForExport($events, $format, $timezone);
797
798                 // If there are results the precess was successfull.
799                 if (!empty($res)) {
800                         $process = true;
801                 }
802
803                 // Get the file extension for the format.
804                 switch ($format) {
805                         case "ical":
806                                 $file_ext = "ics";
807                                 break;
808
809                         case "csv":
810                                 $file_ext = "csv";
811                                 break;
812
813                         default:
814                                 $file_ext = "";
815                 }
816
817                 $return = [
818                         'success'   => $process,
819                         'format'    => $format,
820                         'extension' => $file_ext,
821                         'content'   => $res,
822                 ];
823
824                 return $return;
825         }
826
827         /**
828          * @brief Format an item array with event data to HTML.
829          *
830          * @param array $item Array with item and event data.
831          * @return string HTML output.
832          */
833         public static function getItemHTML(array $item) {
834                 $same_date = false;
835                 $finish    = false;
836
837                 // Set the different time formats.
838                 $dformat       = L10n::t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM.
839                 $dformat_short = L10n::t('D g:i A'); // Fri 8:01 AM.
840                 $tformat       = L10n::t('g:i A'); // 8:01 AM.
841
842                 // Convert the time to different formats.
843                 $dtstart_dt = day_translate(
844                         $item['event-adjust'] ?
845                                 DateTimeFormat::local($item['event-start'], $dformat)
846                                 : DateTimeFormat::utc($item['event-start'], $dformat)
847                 );
848                 $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
849                 // Format: Jan till Dec.
850                 $month_short = day_short_translate(
851                         $item['event-adjust'] ?
852                                 DateTimeFormat::local($item['event-start'], 'M')
853                                 : DateTimeFormat::utc($item['event-start'], 'M')
854                 );
855                 // Format: 1 till 31.
856                 $date_short = $item['event-adjust'] ?
857                         DateTimeFormat::local($item['event-start'], 'j')
858                         : DateTimeFormat::utc($item['event-start'], 'j');
859                 $start_time = $item['event-adjust'] ?
860                         DateTimeFormat::local($item['event-start'], $tformat)
861                         : DateTimeFormat::utc($item['event-start'], $tformat);
862                 $start_short = day_short_translate(
863                         $item['event-adjust'] ?
864                                 DateTimeFormat::local($item['event-start'], $dformat_short)
865                                 : DateTimeFormat::utc($item['event-start'], $dformat_short)
866                 );
867
868                 // If the option 'nofinisch' isn't set, we need to format the finish date/time.
869                 if (!$item['event-nofinish']) {
870                         $finish = true;
871                         $dtend_dt  = day_translate(
872                                 $item['event-adjust'] ?
873                                         DateTimeFormat::local($item['event-finish'], $dformat)
874                                         : DateTimeFormat::utc($item['event-finish'], $dformat)
875                         );
876                         $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
877                         $end_short = day_short_translate(
878                                 $item['event-adjust'] ?
879                                         DateTimeFormat::local($item['event-finish'], $dformat_short)
880                                         : DateTimeFormat::utc($item['event-finish'], $dformat_short)
881                         );
882                         $end_time = $item['event-adjust'] ?
883                                 DateTimeFormat::local($item['event-finish'], $tformat)
884                                 : DateTimeFormat::utc($item['event-finish'], $tformat);
885                         // Check if start and finish time is at the same day.
886                         if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
887                                 $same_date = true;
888                         }
889                 } else {
890                         $dtend_title = '';
891                         $dtend_dt = '';
892                         $end_time = '';
893                         $end_short = '';
894                 }
895
896                 // Format the event location.
897                 $location = self::locationToArray($item['event-location']);
898
899                 // Construct the profile link (magic-auth).
900                 $profile_link = Contact::magicLinkById($item['author-id']);
901
902                 $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl');
903                 $return = Renderer::replaceMacros($tpl, [
904                         '$id'             => $item['event-id'],
905                         '$title'          => prepare_text($item['event-summary']),
906                         '$dtstart_label'  => L10n::t('Starts:'),
907                         '$dtstart_title'  => $dtstart_title,
908                         '$dtstart_dt'     => $dtstart_dt,
909                         '$finish'         => $finish,
910                         '$dtend_label'    => L10n::t('Finishes:'),
911                         '$dtend_title'    => $dtend_title,
912                         '$dtend_dt'       => $dtend_dt,
913                         '$month_short'    => $month_short,
914                         '$date_short'     => $date_short,
915                         '$same_date'      => $same_date,
916                         '$start_time'     => $start_time,
917                         '$start_short'    => $start_short,
918                         '$end_time'       => $end_time,
919                         '$end_short'      => $end_short,
920                         '$author_name'    => $item['author-name'],
921                         '$author_link'    => $profile_link,
922                         '$author_avatar'  => $item['author-avatar'],
923                         '$description'    => prepare_text($item['event-desc']),
924                         '$location_label' => L10n::t('Location:'),
925                         '$show_map_label' => L10n::t('Show map'),
926                         '$hide_map_label' => L10n::t('Hide map'),
927                         '$map_btn_label'  => L10n::t('Show map'),
928                         '$location'       => $location
929                 ]);
930
931                 return $return;
932         }
933
934         /**
935          * @brief Format a string with map bbcode to an array with location data.
936          *
937          * Note: The string must only contain location data. A string with no bbcode will be
938          * handled as location name.
939          *
940          * @param string $s The string with the bbcode formatted location data.
941          *
942          * @return array The array with the location data.
943          *  'name' => The name of the location,<br>
944          * 'address' => The address of the location,<br>
945          * 'coordinates' => Latitude‎ and longitude‎ (e.g. '48.864716,2.349014').<br>
946          */
947         private static function locationToArray($s = '') {
948                 if ($s == '') {
949                         return [];
950                 }
951
952                 $location = ['name' => $s];
953
954                 // Map tag with location name - e.g. [map]Paris[/map].
955                 if (strpos($s, '[/map]') !== false) {
956                         $found = preg_match("/\[map\](.*?)\[\/map\]/ism", $s, $match);
957                         if (intval($found) > 0 && array_key_exists(1, $match)) {
958                                 $location['address'] =  $match[1];
959                                 // Remove the map bbcode from the location name.
960                                 $location['name'] = str_replace($match[0], "", $s);
961                         }
962                 // Map tag with coordinates - e.g. [map=48.864716,2.349014].
963                 } elseif (strpos($s, '[map=') !== false) {
964                         $found = preg_match("/\[map=(.*?)\]/ism", $s, $match);
965                         if (intval($found) > 0 && array_key_exists(1, $match)) {
966                                 $location['coordinates'] =  $match[1];
967                                 // Remove the map bbcode from the location name.
968                                 $location['name'] = str_replace($match[0], "", $s);
969                         }
970                 }
971
972                 $location['name'] = prepare_text($location['name']);
973
974                 // Construct the map HTML.
975                 if (isset($location['address'])) {
976                         $location['map'] = '<div class="map">' . Map::byLocation($location['address']) . '</div>';
977                 } elseif (isset($location['coordinates'])) {
978                         $location['map'] = '<div class="map">' . Map::byCoordinates(str_replace('/', ' ', $location['coordinates'])) . '</div>';
979                 }
980
981                 return $location;
982         }
983 }