Bitrix-D7 22.6
 
Загрузка...
Поиск...
Не найдено
converter.php
1<?php
2
4
23use CCalendar;
24use DateTimeZone;
25use Exception;
26
28{
29 use Sync\Internals\HasContextTrait;
30
31 private const CALENDAR_TYPE = 'user';
32
36 public function __construct(Sync\Office365\Office365Context $context)
37 {
38 $this->context = $context;
39 }
40
48 public function convertEvent(EventDto $eventData, Section $section): Event
49 {
50 $start = $this->prepareDate($eventData->start, $eventData->originalStartTimeZone);
51 $reminders = $this->makeReminders(
52 $eventData->reminderMinutesBeforeStart,
53 $eventData->isReminderOn,
54 $start,
55 );
56
57 $event = (new Event())
58// ->setId($this->getId())
59 ->setName($this->prepareName($eventData->subject))
60 ->setOwner($section->getOwner())
61 ->setCreator($section->getOwner())
62 ->setEventHost($section->getOwner())
63 ->setLocation($this->prepareLocation($eventData->location))
64 ->setStart($start)
65 ->setEnd($this->prepareDate($eventData->end, $eventData->originalEndTimeZone))
66 ->setStartTimeZone($this->prepareDateTimezone($eventData->start, $eventData->originalStartTimeZone))
67 ->setEndTimeZone($this->prepareDateTimezone($eventData->end, $eventData->originalEndTimeZone))
68 ->setIsFullDay($eventData->isAllDay)
69 ->setAttendeesCollection($this->prepareAttendeeCollection($section->getOwner()->getId()))
70 ->setRemindCollection($reminders)
71 ->setSection($section)
72 ->setDescription($this->prepareBody($eventData->body, $section->getOwner()->getId()))
73 ->setMeetingDescription($this->prepareDefaultMeeting($section->getOwner()->getId()))
74// ->setTransparent($this->getTransparency())
75 ->setAccessibility(EventConverter::ACCESSIBILITY_IMPORT_MAP[$eventData->showAs] ?? null)
76 ->setDateModified($this->makeDateFromString($eventData->lastModifiedDateTime))
77 ->setDateCreate($this->makeDateFromString($eventData->createdDateTime))
78 ->setImportance($eventData->importance)
79// ->setIsPrivate($eventData->sensitivity ) // TODO: need converter
80// ->setVersion($this->getVersion())
81 ->setCalendarType(self::CALENDAR_TYPE)
82// ->setUid($this->getUid())
83 ->setIsActive(!$eventData->isCancelled && !$eventData->isDraft)
84 ->setIsDeleted($eventData->isCancelled)
85// ->setRecurrenceId($this->getRecurrenceId())
86// ->setDateCreate($this->getDateCreate())
87// ->setDateModified($this->getDateModified())
88// ->setOriginalDateFrom()
89// ->setExcludedDateCollection()
90 ->setRecurringRule($this->makeRecurringRule($eventData->recurrence))
91 ;
92 if (!empty($eventData->originalStart))
93 {
94 $originalDto = new Office365\Dto\DateTimeDto([
95 'dateTime' => $eventData->originalStart,
96 'timeZone' => $eventData->originalStartTimeZone,
97 ]);
98 $event->setOriginalDateFrom($this->prepareDate($originalDto, $eventData->originalStartTimeZone));
99 }
100
101 // dependence from specific of office all-day events
102 if ($event->isFullDayEvent())
103 {
104 $event->setEnd($event->getEnd()->add("-1 day"));
105 }
106 return $event;
107 }
108
114 public function convertSection(SectionDto $data): Section
115 {
116 return (new Section())
117 ->setName($data->name)
118 ->setColor($this->getOurColor($data->color, $data->hexColor))
119 ;
120 }
121
127 private function prepareLocation(Office365\Dto\LocationDto $location): ?Location
128 {
129 $parsedLocation = \Bitrix\Calendar\Rooms\Util::unParseTextLocation($location->displayName);
130
131 return new Location($parsedLocation['NEW']);
132 }
133
143 private function prepareDate(Office365\Dto\DateTimeDto $dateDto, string $originalTZ = null): Date
144 {
145 $tz = Util::isTimezoneValid($dateDto->timeZone ?? '')
146 ? $dateDto->timeZone
147 : $this->getDefaultTimezone();
148
149 $phpDateTime = new \DateTime($dateDto->dateTime, new DateTimeZone($tz));
150 $eventDateTime = DateTime::createFromPhp($phpDateTime);
151
152 if ($originalTZ)
153 {
154 $original = Util::prepareTimezone($originalTZ);
155 $eventDateTime->setTimeZone($original);
156 }
157
158 return new Date($eventDateTime);
159 }
160
164 private function getDefaultTimezone(): string
165 {
166 return 'UTC';
167 }
168
175 private function prepareDateTimezone(Office365\Dto\DateTimeDto $dateDto, string $originalTZ = null): \Bitrix\Calendar\Core\Base\DateTimeZone
176 {
177 if ($originalTZ)
178 {
179 $original = Util::prepareTimezone($originalTZ);
180
181 return new \Bitrix\Calendar\Core\Base\DateTimeZone($original);
182 }
183 $tz = Util::isTimezoneValid($dateDto->timeZone ?? '')
184 ? $dateDto->timeZone
185 : $this->getDefaultTimezone();
186
187 return new \Bitrix\Calendar\Core\Base\DateTimeZone(
188 new DateTimeZone($tz)
189 );
190 }
191
199 private function makeReminders(int $minutes, bool $isReminderOn, Date $start): RemindCollection
200 {
201 $collection = new RemindCollection();
202 $collection->setEventStart($start)->setSingle(true);
203 if ($isReminderOn)
204 {
205 if ($minutes < 0)
206 {
207 $hours = '+'. abs($minutes) / 60 . ' hour';
208 $specificTime = (clone $start)->add($hours);
209 $reminder = (new Remind())
210 ->setSpecificTime($specificTime)
211 ->setDaysBefore(0)
212 ;
213 }
214 else
215 {
216 $reminder = (new Remind())->setTimeBeforeEvent($minutes, 'minutes');
217 }
218 $reminder->setEventStart($start);
219 $collection->add($reminder);
220 }
221
222 return $collection;
223 }
224
231 private function makeRecurringRule(?Office365\Dto\RecurrenceDto $recurrenceDto = null): ?RecurringEventRules
232 {
233 if (!$recurrenceDto)
234 {
235 return null;
236 }
237 switch ($recurrenceDto->pattern->type)
238 {
239 case Helper::RECURRENCE_TYPES['daily']:
240 $result = new RecurringEventRules(
241 RecurringEventRules::FREQUENCY['daily'],
242 $recurrenceDto->pattern->interval
243 );
244
245 break;
246 case Helper::RECURRENCE_TYPES['weekly']:
247 $result = new RecurringEventRules(
248 RecurringEventRules::FREQUENCY['weekly'],
249 $recurrenceDto->pattern->interval
250 );
251 if ($recurrenceDto->pattern->daysOfWeek)
252 {
253 $byDay = array_map(function ($value)
254 {
255 return strtoupper(substr($value, 0, 2));
256 }, $recurrenceDto->pattern->daysOfWeek);
257 $result->setByDay($byDay);
258 }
259
260 break;
261 case Helper::RECURRENCE_TYPES['absoluteMonthly']:
262 $result = new RecurringEventRules(
263 RecurringEventRules::FREQUENCY['monthly'],
264 $recurrenceDto->pattern->interval
265 );
266
267 break;
268 case Helper::RECURRENCE_TYPES['absoluteYearly']:
269 $result = new RecurringEventRules(
270 RecurringEventRules::FREQUENCY['yearly'],
271 $recurrenceDto->pattern->interval
272 );
273
274 break;
275 default:
276 return null;
277 }
278
279 if (!empty($recurrenceDto->range->numberOfOccurrences))
280 {
281 $result->setCount($recurrenceDto->range->numberOfOccurrences);
282 }
283 if ($recurrenceDto->range->endDate >= $recurrenceDto->range->startDate)
284 {
285 $until = new \Bitrix\Main\Type\Date($recurrenceDto->range->endDate, 'Y-m-d');
286 $result->setUntil(new Date($until));
287 }
288 else
289 {
290 $result->setUntil($this->getFarFarAwayDate());
291 }
292
293 return $result;
294 }
295
301 private function getFarFarAwayDate(): Date
302 {
303 return new Date(Util::getDateObject('01.01.2038'));
304 }
305
314 private function makeDateFromString(string $time): Date
315 {
316 return new Date(DateTime::createFromPhp(new \DateTime($time)));
317 }
318
325 private function getOurColor(string $color, ?string $hexColor = null): ?string
326 {
327 return ColorConverter::fromOffice($color, $hexColor);
328 }
329
336 private function prepareBody(Office365\Dto\RichTextDto $body, int $userId): string
337 {
338 if ($body->contentType === 'html')
339 {
340 $text = CCalendar::ParseHTMLToBB($body->content);
341 }
342 else
343 {
344 $text = $body->content;
345 }
346
347 $text = html_entity_decode($text, ENT_QUOTES | ENT_XML1);
348 $text = html_entity_decode($text, ENT_QUOTES | ENT_XML1);
349 $languageId = CCalendar::getUserLanguageId($userId);
350
351 return (new Sync\Util\EventDescription())->prepareAfterImport($text, $languageId);
352 }
353
359 private function prepareName(?string $name): string
360 {
361 if (!$name)
362 {
363 IncludeModuleLangFile($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/calendar/classes/general/calendar_js.php");
364 $name = Loc::getMessage('EC_DEFAULT_ENTRY_NAME');
365 }
366
367 return $name;
368 }
369
375 private function prepareDefaultMeeting(int $userId): MeetingDescription
376 {
377 return (new MeetingDescription())
378 ->setHostName(CCalendar::GetUserName($userId))
379 ->setIsNotify(true)
380 ->setReInvite(false)
381 ->setAllowInvite(false)
382 ->setMeetingCreator($userId)
383 ->setHideGuests(true)
384 ->setLanguageId(CCalendar::getUserLanguageId($userId))
385 ;
386 }
387
393 private function prepareAttendeeCollection(int $userId): AttendeeCollection
394 {
395 return (new AttendeeCollection())
396 ->setAttendeesCodes(['U' . $userId])
397 ;
398 }
399}
static fromOffice(string $color, ?string $hexColor=null)
__construct(Sync\Office365\Office365Context $context)
Definition: converter.php:36
convertEvent(EventDto $eventData, Section $section)
Definition: converter.php:48
static getDateObject(string $date=null, $fullDay=true, $tz='UTC')
Definition: util.php:100
static prepareTimezone(?string $tz=null)
Definition: util.php:73
static isTimezoneValid(?string $timeZone)
Definition: util.php:64
static getMessage($code, $replace=null, $language=null)
Definition: loc.php:29
static createFromPhp(\DateTime $datetime)
Definition: datetime.php:232