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