dolibarr 25.0.0-alpha
ical.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2006 Roman Ozana <ozana@omdesign.cz>
3 * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
4 * Copyright (C) 2013-2014 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024 Vincent de Grandpré <vincent@de-grandpre.quebec>
9 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
30require_once DOL_DOCUMENT_ROOT.'/core/lib/xcal.lib.php';
31require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
32
33
37class ICal
38{
42 public $file;
43
47 public $file_text;
48
52 public $cal;
53
57 public $event_count;
58
62 public $todo_count;
63
67 public $freebusy_count;
68
72 public $journal_count;
73
77 private $vtimezones = null;
78
82 public $last_key;
83
87 public $error;
88
89
93 public function __construct()
94 {
95 }
96
97 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
104 public function read_file($file)
105 {
106 // phpcs:enable
107 $this->file = $file;
108 $file_text = '';
109
110 //$tmpresult = getURLContent($file, 'GET', '', 1, [], ['http', 'https'], 2, 0); // To test with any URL
111 $localip = 0;
112 $sslverify = -1;
113 if (getDolGlobalString('AGENDA_EXT_CALENDAR_IP_MODE')) {
114 $localip = intval(getDolGlobalString('AGENDA_EXT_CALENDAR_IP_MODE'));
115 }
116 if (getDolGlobalString('AGENDA_EXT_CALENDAR_SSLVERIFY_MODE')) {
117 $sslverify = intval(getDolGlobalString('AGENDA_EXT_CALENDAR_SSLVERIFY_MODE'));
118 }
119 // See documentation of getURLContent function for $localip and $sslverify possible values
120 $tmpresult = getURLContent($file, 'GET', '', 1, [], ['http', 'https'], $localip, $sslverify);
121 if ($tmpresult['http_code'] != 200) {
122 $file_text = null;
123 $this->error = 'Error: '.$tmpresult['http_code'].' '.dol_trunc(trim((string) preg_replace('/\s+/', ' ', dol_string_nohtmltag((string) $tmpresult['content']))), 200);
124 } else {
125 // RFC 5545 requires UTF-8, but some calendars are in another charset (declared by the HTTP header, or not declared)
126 $content = $this->convertToUtf8((string) $tmpresult['content'], (string) ($tmpresult['content_type'] ?? ''));
127 // Unfold long lines (RFC 5545: a CRLF followed by one space or one tab is a line continuation)
128 $file_text = preg_replace("/[\r\n]{1,}[ \t]/", "", $content);
129 }
130 //var_dump($tmpresult);
131
132 return $file_text; // return all text
133 }
134
144 public function convertToUtf8($text, $contenttype = '')
145 {
146 if (!function_exists('mb_check_encoding')) {
147 return $text;
148 }
149 if (strncmp($text, "\xFF\xFE", 2) == 0 || strncmp($text, "\xFE\xFF", 2) == 0) {
150 return mb_convert_encoding(substr($text, 2), 'UTF-8', (strncmp($text, "\xFF\xFE", 2) == 0 ? 'UTF-16LE' : 'UTF-16BE'));
151 }
152 if (mb_check_encoding($text, 'UTF-8')) {
153 return $text;
154 }
155 $charset = 'Windows-1252';
156 $reg = array();
157 if (preg_match('/charset="?([A-Za-z0-9_.:-]+)"?/i', $contenttype, $reg)) {
158 $found = false;
159 foreach (mb_list_encodings() as $encoding) {
160 if (strtolower($encoding) == strtolower($reg[1]) && strtoupper($encoding) != 'UTF-8') {
161 $charset = $encoding;
162 $found = true;
163 break;
164 }
165 }
166 if (!$found && function_exists('iconv')) {
167 // Charset not known by mbstring (Windows-1250...): we try iconv
168 $converted = @iconv($reg[1], 'UTF-8//IGNORE', $text);
169 if ($converted !== false) {
170 return $converted;
171 }
172 }
173 }
174 return mb_convert_encoding($text, 'UTF-8', $charset);
175 }
176
185 {
186 $result = array();
187 foreach (array('VTODO', 'VJOURNAL') as $component) {
188 if (empty($this->cal[$component]) || !is_array($this->cal[$component])) {
189 continue;
190 }
191 foreach ($this->cal[$component] as $item) {
192 if (!is_array($item) || (isset($item['STATUS']) && strtoupper(trim((string) $item['STATUS'])) == 'CANCELLED')) {
193 continue;
194 }
195 $event = $item;
196 unset($event['DUE'], $event['DUE;VALUE=DATE']);
197 if ($component == 'VTODO') {
198 // The end of a to do is its due date. Without start, the start is the due date.
199 if (isset($item['DUE;VALUE=DATE'])) {
200 $event['DTEND;VALUE=DATE'] = $item['DUE;VALUE=DATE'];
201 if (!isset($event['DTSTART']) && !isset($event['DTSTART;VALUE=DATE'])) {
202 $event['DTSTART;VALUE=DATE'] = $item['DUE;VALUE=DATE'];
203 $event['DTEND;VALUE=DATE'] = gmdate('Ymd', gmmktime(0, 0, 0, (int) substr($item['DUE;VALUE=DATE'], 4, 2), (int) substr($item['DUE;VALUE=DATE'], 6, 2), (int) substr($item['DUE;VALUE=DATE'], 0, 4)) + 86400);
204 }
205 } elseif (isset($item['DUE'])) {
206 $event['DTEND'] = $item['DUE'];
207 if (!isset($event['DTSTART']) && !isset($event['DTSTART;VALUE=DATE'])) {
208 $event['DTSTART'] = $item['DUE'];
209 }
210 }
211 }
212 if (!isset($event['DTSTART']) && !isset($event['DTSTART;VALUE=DATE'])) {
213 continue;
214 }
215 $done = ($component == 'VTODO' && ((isset($item['STATUS']) && strtoupper(trim((string) $item['STATUS'])) == 'COMPLETED') || isset($item['COMPLETED'])));
216 $symbol = ($component == 'VJOURNAL' ? "\u{270E} " : ($done ? "\u{2611} " : "\u{2610} "));
217 $title = (isset($item['SUMMARY']) && $item['SUMMARY'] !== '') ? (string) $item['SUMMARY'] : trim(strtok((string) ($item['DESCRIPTION'] ?? ''), "\n"));
218 $event['SUMMARY'] = $symbol.$title;
219 $result[] = $event;
220 }
221 }
222 return $result;
223 }
224
225 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
231 public function get_event_count()
232 {
233 // phpcs:enable
234 return $this->event_count;
235 }
236
237 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
243 public function get_todo_count()
244 {
245 // phpcs:enable
246 return $this->todo_count;
247 }
248
255 private function isIcalText($text)
256 {
257 return (bool) preg_match('/^[\xEF\xBB\xBF\s]*BEGIN:VCALENDAR/i', $text);
258 }
259
268 public function parse($uri, $usecachefile = '', $delaycache = 3600)
269 {
270 $this->cal = array(); // new empty array
271
272 $this->event_count = -1;
273 $this->file_text = '';
274
275 $stalecachetext = ''; // Content of an expired cache file, used if the download fails
276 $datefile = 0;
277
278 // Save file into a cache
279 if ($usecachefile) {
280 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
281 $datefile = dol_filemtime($usecachefile);
282 $now = dol_now('gmt');
283 //print $datefile.' '.$now.' ...';
284 if ($datefile && $datefile > ($now - $delaycache)) {
285 // We reuse the cache file
286 $this->file_text = file_get_contents($usecachefile);
287 if (!$this->isIcalText($this->file_text)) {
288 $this->file_text = ''; // Not an iCal file (for example a HTML page cached by an old version), so we download it again
289 }
290 } elseif ($datefile) {
291 // The cache is too old: we download it again, but we keep the old content to use it if the download fails
292 $oldtext = (string) file_get_contents($usecachefile);
293 if ($this->isIcalText($oldtext)) {
294 $stalecachetext = $oldtext;
295 }
296 }
297 }
298
299 // read FILE text
300 if (empty($this->file_text)) {
301 // A failure is remembered a few minutes, to not download again and wait for the timeout at each display of the page
302 $failfile = ($usecachefile ? $usecachefile.'.fail' : '');
303 if ($failfile && dol_filemtime($failfile) > (dol_now('gmt') - min($delaycache, 300))) {
304 $this->error = (string) file_get_contents($failfile);
305 $this->file_text = null;
306 } else {
307 $this->file_text = $this->read_file($uri);
308 if (!is_null($this->file_text) && !$this->isIcalText($this->file_text)) {
309 // We got something that is not an iCal file (an error page in HTML, a login page...). We do not keep it.
310 $this->error = 'Error: the server did not return an iCal file (received: '.dol_trunc(trim((string) preg_replace('/\s+/', ' ', dol_string_nohtmltag($this->file_text))), 100).')';
311 $this->file_text = null;
312 }
313 if ($failfile) {
314 if (is_null($this->file_text)) {
315 file_put_contents($failfile, $this->error, LOCK_EX);
316 dolChmod($failfile);
317 } else {
318 dol_delete_file($failfile);
319 }
320 }
321 }
322
323 if ($usecachefile && !is_null($this->file_text)) {
324 // Save the file content into cache file
325 // Write into a temporary file then rename it, so a concurrent reader never gets a partial file
326 $tmpcachefile = $usecachefile.'.'.getmypid().'.tmp';
327 if (file_put_contents($tmpcachefile, $this->file_text, LOCK_EX) !== false) {
328 dolChmod($tmpcachefile);
329 rename($tmpcachefile, $usecachefile);
330 }
331 }
332 }
333
334 if (is_null($this->file_text) && $stalecachetext !== '') {
335 // The download failed: we use the last copy we have (the cache file is not rewritten, so we will try again later)
336 $this->file_text = $stalecachetext;
337 $this->error .= ' (the copy downloaded on '.dol_print_date((int) $datefile, 'dayhour', 'gmt').' UTC is used)';
338 }
339
340 $file_text_array = preg_split("[\n]", ltrim((string) $this->file_text, "\xEF\xBB\xBF \t\r\n")); // Ignore a BOM and the blank lines before BEGIN:VCALENDAR
341
342 // is this text vcalendar standard text ? on line 1 is BEGIN:VCALENDAR
343 if (!stristr($file_text_array[0], 'BEGIN:VCALENDAR')) {
344 return 'error not VCALENDAR';
345 }
346
347 $insidealarm = 0;
348 $tmpkey = '';
349 $tmpvalue = '';
350 $type = '';
351 foreach ($file_text_array as $text) {
352 $text = trim($text); // trim one line
353 if (!empty($text)) {
354 // get Key and Value VCALENDAR:Begin -> Key = VCALENDAR, Value = begin
355 list($key, $value) = $this->retun_key_value($text);
356 //var_dump($text.' -> '.$key.' - '.$value);
357
358 switch ($text) { // search special string
359 case "BEGIN:VTODO":
360 $this->todo_count += 1; // new to do begin
361 $type = "VTODO";
362 break;
363
364 case "BEGIN:VEVENT":
365 $this->event_count += 1; // new event begin
366 $type = "VEVENT";
367 break;
368
369 case "BEGIN:VFREEBUSY":
370 $this->freebusy_count += 1; // new event begin
371 $type = "VFREEBUSY";
372 break;
373
374 case "BEGIN:VJOURNAL":
375 $this->journal_count += 1; // new journal begin
376 $type = "VJOURNAL";
377 break;
378
379 case "BEGIN:VCALENDAR": // all other special string
380 case "BEGIN:DAYLIGHT":
381 case "BEGIN:VTIMEZONE":
382 case "BEGIN:STANDARD":
383 $type = $value; // save array under value key
384 break;
385
386 case "END:VTODO": // end special text - goto VCALENDAR key
387 case "END:VEVENT":
388 case "END:VFREEBUSY":
389 case "END:VJOURNAL":
390 case "END:VCALENDAR":
391 case "END:DAYLIGHT":
392 case "END:VTIMEZONE":
393 case "END:STANDARD":
394 $type = "VCALENDAR";
395 break;
396
397 // Manage VALARM that are inside a VEVENT to avoid fields of VALARM to overwrites fields of VEVENT
398 case "BEGIN:VALARM":
399 $insidealarm = 1;
400 break;
401 case "END:VALARM":
402 $insidealarm = 0;
403 break;
404
405 default: // no special string (SUMMARY, DESCRIPTION, ...)
406 if ($tmpvalue) {
407 $tmpvalue .= $text;
408 if (!preg_match('/=$/', $text)) { // No more lines
409 $key = $tmpkey;
410 $value = quotedPrintDecode(preg_replace('/^ENCODING=QUOTED-PRINTABLE:/i', '', $tmpvalue));
411 $tmpkey = '';
412 $tmpvalue = '';
413 }
414 } elseif (preg_match('/^ENCODING=QUOTED-PRINTABLE:/i', $value)) {
415 if (preg_match('/=$/', $value)) {
416 $tmpkey = $key;
417 $tmpvalue .= preg_replace('/=$/', "", $value); // We must wait to have next line to have complete message
418 } else {
419 $value = quotedPrintDecode(preg_replace('/^ENCODING=QUOTED-PRINTABLE:/i', '', $tmpvalue.$value));
420 }
421 } //$value=quotedPrintDecode($tmpvalue.$value);
422 if (!$insidealarm && !$tmpkey) {
423 $this->add_to_array($type, $key, $value); // add to array
424 }
425 break;
426 }
427 }
428 }
429
430 $events = $this->get_event_list();
431 if (!empty($events)) {
432 // The same instance of an event written several times (same UID and same start, or same UID and RECURRENCE-ID): we keep the most recent version
433 // (SEQUENCE, then LAST-MODIFIED or DTSTAMP, then the last one of the file). Events with the same UID but another start are other events:
434 // some exporters reuse the same UID for the events of several years.
435 $keptevents = [];
436 foreach ($events as $evkey => $event) {
437 if (empty($event['UID'])) {
438 continue;
439 }
440 $eventstart = ($event['DTSTART'] ?? ($event['DTSTART;VALUE=DATE'] ?? ''));
441 // A modified occurrence is identified by its UID and its RECURRENCE-ID (its start can differ), another event by its UID and its start
442 $duplicatekey = $event['UID'].'|'.(empty($event['RECURRENCE-ID']) ? json_encode($eventstart) : 'RECURRENCE-ID='.$event['RECURRENCE-ID']);
443 $rank = [(int) ($event['SEQUENCE'] ?? 0), (int) ($event['LAST-MODIFIED'] ?? ($event['DTSTAMP'] ?? 0))];
444 if (isset($keptevents[$duplicatekey])) {
445 if ($rank >= $keptevents[$duplicatekey]['rank']) {
446 unset($events[$keptevents[$duplicatekey]['key']]);
447 $keptevents[$duplicatekey] = ['key' => $evkey, 'rank' => $rank];
448 } else {
449 unset($events[$evkey]);
450 }
451 } else {
452 $keptevents[$duplicatekey] = ['key' => $evkey, 'rank' => $rank];
453 }
454 }
455 // An occurrence of a recurring event that was modified or cancelled is an event with the same UID and a RECURRENCE-ID.
456 // We add its day to the excluded days (EXDATE) of the main event, so the original occurrence is not shown.
457 // The modified occurrence stays an event of its own.
458 $mainkeys = [];
459 foreach ($events as $evkey => $event) {
460 if (empty($event['RECURRENCE-ID']) && !empty($event['UID'])) {
461 $mainkeys[$event['UID']] = $evkey;
462 }
463 }
464 foreach ($events as $evkeyoverride => $event) {
465 if (!empty($event['RECURRENCE-ID']) && !empty($event['UID']) && isset($mainkeys[$event['UID']])) {
466 $mainkey = $mainkeys[$event['UID']];
467 if (($event['X-RECURRENCE-RANGE'] ?? '') == 'THISANDFUTURE' && !empty($events[$mainkey]['RRULE']) && is_array($events[$mainkey]['RRULE'])) {
468 // This occurrence and the following ones are modified: the series of the main event stops the day before, and the modified
469 // event continues the series (same rule, with its own start and properties).
470 $rule = $events[$mainkey]['RRULE'];
471 $daystamp = gmmktime(0, 0, 0, (int) substr($event['RECURRENCE-ID'], 4, 2), (int) substr($event['RECURRENCE-ID'], 6, 2), (int) substr($event['RECURRENCE-ID'], 0, 4));
472 $newrule = $rule;
473 unset($newrule['UNTIL']);
474 if (!empty($rule['COUNT'])) {
475 // Remaining number of occurrences for the modified event
476 $mainstart = $this->getWallStart($events[$mainkey]);
477 unset($newrule['COUNT']);
478 if ($mainstart !== null && $this->isRRuleSupported($rule)) {
479 $remaining = (int) $rule['COUNT'] - count($this->expandRRule($rule, $mainstart, $daystamp));
480 if ($remaining > 0) {
481 $newrule['COUNT'] = (string) $remaining;
482 }
483 }
484 }
485 if (!empty($rule['UNTIL'])) {
486 $newrule['UNTIL'] = $rule['UNTIL'];
487 }
488 unset($events[$mainkey]['RRULE']['COUNT']);
489 $events[$mainkey]['RRULE']['UNTIL'] = gmdate('Ymd', $daystamp - 86400).'T235959Z';
490 if (empty($events[$evkeyoverride]['RRULE'])) {
491 $events[$evkeyoverride]['RRULE'] = $newrule;
492 }
493 unset($events[$evkeyoverride]['RECURRENCE-ID'], $events[$evkeyoverride]['X-RECURRENCE-RANGE']);
494 continue;
495 }
496 $exdates = (isset($events[$mainkey]['EXDATE']) && is_array($events[$mainkey]['EXDATE'])) ? $events[$mainkey]['EXDATE'] : [];
497 $exdates[] = $event['RECURRENCE-ID'];
498 $events[$mainkey]['EXDATE'] = $exdates;
499 }
500 }
501 // An event can have a DURATION instead of a DTEND: we define the end from the duration.
502 foreach ($events as $evkey => $event) {
503 if (empty($event['DURATION']) || !is_string($event['DURATION']) || isset($event['DTEND']) || isset($event['DTEND;VALUE=DATE'])) {
504 continue;
505 }
506 $seconds = $this->ical_duration_to_seconds($event['DURATION']);
507 if ($seconds === null) {
508 continue;
509 }
510 if (!empty($event['DTSTART;VALUE=DATE']) && is_string($event['DTSTART;VALUE=DATE'])) {
511 // All day event: the end is the day after the last day, so a duration of 1 day is DTEND = next day
512 $start = gmmktime(0, 0, 0, (int) substr($event['DTSTART;VALUE=DATE'], 4, 2), (int) substr($event['DTSTART;VALUE=DATE'], 6, 2), (int) substr($event['DTSTART;VALUE=DATE'], 0, 4));
513 $events[$evkey]['DTEND;VALUE=DATE'] = gmdate('Ymd', $start + max(1, (int) ceil($seconds / 86400)) * 86400);
514 } elseif (isset($event['DTSTART']) && is_array($event['DTSTART']) && isset($event['DTSTART']['unixtime'])) {
515 $events[$evkey]['DTEND'] = array('TZID' => ($event['DTSTART']['TZID'] ?? ''), 'unixtime' => (int) $event['DTSTART']['unixtime'] + $seconds);
516 } elseif (!empty($event['DTSTART']) && !is_array($event['DTSTART'])) {
517 $events[$evkey]['DTEND'] = (int) $event['DTSTART'] + $seconds;
518 }
519 }
520 // Events (or occurrences) with STATUS:CANCELLED are not returned
521 foreach ($events as $evkey => $event) {
522 if (isset($event['STATUS']) && is_string($event['STATUS']) && strtoupper(trim($event['STATUS'])) == 'CANCELLED') {
523 unset($events[$evkey]);
524 }
525 }
526 $this->cal['VEVENT'] = $events;
527 }
528
529 //var_dump($this->cal);
530 return $this->cal;
531 }
532
533 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
542 public function add_to_array($type, $key, $value)
543 {
544 // phpcs:enable
545
546 //print 'type='.$type.' key='.$key.' value='.$value.'<br>'."\n";
547
548 // RDATE (dates added to a recurrence). Values are kept as written (a PERIOD "start/end" is reduced to its start), accumulated over all the RDATE lines of the event.
549 if ($type == 'VEVENT' && !empty($key) && strtoupper(explode(';', $key, 2)[0]) == 'RDATE') {
550 $rdates = (isset($this->cal[$type][$this->event_count]['RDATE']) && is_array($this->cal[$type][$this->event_count]['RDATE'])) ? $this->cal[$type][$this->event_count]['RDATE'] : [];
551 foreach (explode(',', $value) as $rdate) {
552 $rdate = trim(explode('/', $rdate)[0]);
553 if (preg_match('/^[0-9]{8}(T[0-9]{6}Z?)?$/', $rdate)) {
554 $rdates[] = $rdate;
555 }
556 }
557 $this->cal[$type][$this->event_count]['RDATE'] = $rdates;
558 $this->last_key = 'RDATE';
559 return;
560 }
561
562 // EXDATE (dates excluded from a recurrence). Only the days are kept, accumulated over all the EXDATE lines of the event.
563 if ($type == 'VEVENT' && !empty($key) && strtoupper(explode(';', $key, 2)[0]) == 'EXDATE') {
564 $exdates = (isset($this->cal[$type][$this->event_count]['EXDATE']) && is_array($this->cal[$type][$this->event_count]['EXDATE'])) ? $this->cal[$type][$this->event_count]['EXDATE'] : [];
565 foreach (explode(',', $value) as $exdate) {
566 if (preg_match('/^\s*([0-9]{8})/', $exdate, $reg)) {
567 $exdates[] = $reg[1];
568 }
569 }
570 $this->cal[$type][$this->event_count]['EXDATE'] = $exdates;
571 $this->last_key = 'EXDATE';
572 return;
573 }
574
575 $iscontinuation = false;
576 if (empty($key)) {
577 $iscontinuation = true;
578 $key = $this->last_key;
579 switch ($type) {
580 case 'VEVENT':
581 // @phan-suppress-next-line PhanTypeMismatchDimFetch
582 $value = $this->cal[$type][$this->event_count][$key].$value;
583 break;
584 case 'VFREEBUSY':
585 // @phan-suppress-next-line PhanTypeMismatchDimFetch
586 $value = $this->cal[$type][$this->freebusy_count][$key].$value;
587 break;
588 case 'VTODO':
589 // @phan-suppress-next-line PhanTypeMismatchDimFetch
590 $value = $this->cal[$type][$this->todo_count][$key].$value;
591 break;
592 case 'VJOURNAL':
593 // @phan-suppress-next-line PhanTypeMismatchDimFetch
594 $value = $this->cal[$type][$this->journal_count][$key].$value;
595 break;
596 }
597 }
598
599 if (!$iscontinuation && $type == 'VEVENT' && preg_match('/^(ATTENDEE|ORGANIZER)(;|$)/i', $key, $reg)) {
600 // Organizer or attendee: "Name <email>" (the name is the parameter CN, the value is mailto:email). There can be several attendees.
601 $name = (preg_match('/;CN=("[^"]*"|[^;]*)/i', $key, $regcn) ? trim($regcn[1], '"') : '');
602 $email = (string) preg_replace('/^mailto:/i', '', trim($value));
603 $person = (($name !== '' && $name != $email) ? $name.' <'.$email.'>' : $email);
604 if (strtoupper($reg[1]) == 'ATTENDEE') {
605 $attendees = (isset($this->cal[$type][$this->event_count]['ATTENDEE']) && is_array($this->cal[$type][$this->event_count]['ATTENDEE'])) ? $this->cal[$type][$this->event_count]['ATTENDEE'] : [];
606 $attendees[] = $person;
607 $this->cal[$type][$this->event_count]['ATTENDEE'] = $attendees;
608 $this->last_key = 'ATTENDEE';
609 return;
610 }
611 $key = 'ORGANIZER';
612 $value = $person;
613 }
614
615 if (!$iscontinuation) {
616 // RECURRENCE-ID;RANGE=THISANDFUTURE: this occurrence and all the following ones are modified (the parameter is removed with the other ones below)
617 if ($type == 'VEVENT' && preg_match('/^RECURRENCE-ID;.*RANGE=THISANDFUTURE/i', $key)) {
618 $this->cal[$type][$this->event_count]['X-RECURRENCE-RANGE'] = 'THISANDFUTURE';
619 }
620 // Value in a legacy encoding (vCalendar 1.0 style: ENCODING=QUOTED-PRINTABLE and/or CHARSET=ISO-8859-1 as parameters of the property)
621 if (strpos($key, ';') !== false && !stristr($key, "DTSTART") && !stristr($key, "DTEND")) {
622 if (preg_match('/;ENCODING=(QUOTED-PRINTABLE|Q)(;|$)/i', $key)) {
623 $value = quotedPrintDecode($value);
624 }
625 if ($value !== '' && function_exists('mb_check_encoding') && !mb_check_encoding($value, 'UTF-8')) {
626 $value = $this->convertToUtf8($value, (preg_match('/;CHARSET=([^;]+)/i', $key, $reg) ? 'charset='.trim($reg[1], '"') : ''));
627 }
628 }
629 // Remove the parameters of a property (SUMMARY;LANGUAGE=fr -> SUMMARY), except for dates that are managed below
630 if (strpos($key, ';') !== false && !stristr($key, "DTSTART") && !stristr($key, "DTEND") && !stristr($key, "DUE")) {
631 $key = explode(';', $key, 2)[0];
632 }
633 // Decode escaped characters of TEXT values
634 if (in_array($key, ['SUMMARY', 'DESCRIPTION', 'LOCATION', 'COMMENT', 'CATEGORIES'])) {
635 $value = strtr($value, ['\\\\' => '\\', '\\,' => ',', '\\;' => ';', '\\n' => "\n", '\\N' => "\n"]);
636 }
637 }
638
639 if (($key == "DTSTAMP") || ($key == "LAST-MODIFIED") || ($key == "CREATED")) {
640 $value = $this->ical_date_to_unix($value);
641 }
642 //if ($key == "RRULE" ) $value = $this->ical_rrule($value);
643
644 if (preg_match('/^(DTSTART|DTEND|DUE)(;|$)/i', $key, $reg)) {
645 $params = $this->getKeyParams($key);
646 if (isset($params['VALUE']) && strtoupper($params['VALUE']) == 'DATE') {
647 // All day date. The key is always 'DTSTART;VALUE=DATE' or 'DTEND;VALUE=DATE'
648 $key = strtoupper($reg[1]).';VALUE=DATE';
649 } else {
650 // Date and time (the parameter VALUE=DATE-TIME, if any, is the default type and is ignored)
651 list($key, $value) = $this->ical_dt_date($key, $value);
652 }
653 }
654
655 switch ($type) {
656 case "VTODO":
657 // @phan-suppress-next-line PhanTypeMismatchReturn
658 $this->cal[$type][$this->todo_count][$key] = $value;
659 break;
660
661 case "VJOURNAL":
662 // @phan-suppress-next-line PhanTypeMismatchReturn
663 $this->cal[$type][$this->journal_count][$key] = $value;
664 break;
665
666 case "VEVENT":
667 if (strtoupper(explode(';', $key, 2)[0]) == 'RECURRENCE-ID') {
668 // Occurrence of a recurring event that is replaced by this event. We keep only the day (as written in the file).
669 $key = 'RECURRENCE-ID';
670 if (preg_match('/^\s*([0-9]{8})/', $value, $reg)) {
671 $value = $reg[1];
672 }
673 }
674 // @phan-suppress-next-line PhanTypeMismatchReturn
675 $this->cal[$type][$this->event_count][$key] = ($key == 'RRULE' ? $this->ical_rrule($value) : $value); // RRULE of an event is decoded into an array
676 break;
677
678 case "VFREEBUSY":
679 // @phan-suppress-next-line PhanTypeMismatchReturn
680 $this->cal[$type][$this->freebusy_count][$key] = $value;
681 break;
682
683 default:
684 // @phan-suppress-next-line PhanTypeMismatchProperty
685 $this->cal[$type][$key] = $value;
686 break;
687 }
688 $this->last_key = $key;
689 }
690
691 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
698 public function retun_key_value($text)
699 {
700 // phpcs:enable
701 /*
702 preg_match("/([^:]+)[:]([\w\W]+)/", $text, $matches);
703
704 if (empty($matches))
705 {
706 return array(false,$text);
707 }
708 else
709 {
710 $matches = array_splice($matches, 1, 2);
711 return $matches;
712 }*/
713 return explode(':', $text, 2);
714 }
715
716 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
723 public function ical_rrule($value)
724 {
725 // phpcs:enable
726 $result = array();
727 $rrule = explode(';', $value);
728 foreach ($rrule as $line) {
729 $rcontent = explode('=', $line, 2);
730 if (count($rcontent) == 2) {
731 $result[strtoupper($rcontent[0])] = $rcontent[1];
732 }
733 }
734 return $result;
735 }
736
743 private function parseByDay($value)
744 {
745 $daysofweek = array('SU' => 0, 'MO' => 1, 'TU' => 2, 'WE' => 3, 'TH' => 4, 'FR' => 5, 'SA' => 6);
746 $result = array();
747 foreach (explode(',', strtoupper($value)) as $item) {
748 $reg = array();
749 if (!preg_match('/^([+-]?[0-9]{1,2})?(SU|MO|TU|WE|TH|FR|SA)$/', trim($item), $reg)) {
750 return null;
751 }
752 $ordinal = ($reg[1] === '' ? 0 : (int) $reg[1]);
753 if (abs($ordinal) > 5) {
754 return null;
755 }
756 $result[] = array($ordinal, $daysofweek[$reg[2]]);
757 }
758 return $result;
759 }
760
768 public function isRRuleSupported($rrule)
769 {
770 $freq = ($rrule['FREQ'] ?? '');
771 if (!in_array($freq, array('MINUTELY', 'HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'))) {
772 return false;
773 }
774 $byparts = array();
775 foreach (array_keys($rrule) as $key) {
776 if (strpos($key, 'BY') === 0) {
777 if (!in_array($key, array('BYDAY', 'BYMONTHDAY', 'BYMONTH', 'BYYEARDAY', 'BYWEEKNO', 'BYSETPOS', 'BYHOUR', 'BYMINUTE', 'BYSECOND'))) {
778 return false;
779 }
780 $byparts[$key] = $key;
781 }
782 }
783 if (isset($rrule['WKST']) && !in_array(strtoupper($rrule['WKST']), array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'))) {
784 return false;
785 }
786 $isshort = in_array($freq, array('MINUTELY', 'HOURLY'));
787
788 if (isset($rrule['BYDAY'])) {
789 $byday = $this->parseByDay($rrule['BYDAY']);
790 if ($byday === null) {
791 return false;
792 }
793 foreach ($byday as $item) {
794 if ($item[0] != 0 && !in_array($freq, array('MONTHLY', 'YEARLY'))) {
795 return false; // An ordinal (2MO, -1FR) has a meaning only for a monthly or yearly rule
796 }
797 if ($item[0] != 0 && $freq == 'YEARLY' && empty($rrule['BYMONTH'])) {
798 return false;
799 }
800 }
801 }
802 $limits = array('BYMONTHDAY' => array(31, false), 'BYMONTH' => array(12, true), 'BYYEARDAY' => array(366, false), 'BYWEEKNO' => array(53, false), 'BYSETPOS' => array(366, false), 'BYHOUR' => array(23, true), 'BYMINUTE' => array(59, true), 'BYSECOND' => array(59, true));
803 foreach ($limits as $key => $limit) {
804 if (isset($rrule[$key])) {
805 foreach (explode(',', $rrule[$key]) as $item) {
806 $value = (int) $item;
807 if (!preg_match('/^-?[0-9]{1,3}$/', trim($item)) || abs($value) > $limit[0] || ($limit[1] && $value < 0) || (!in_array($key, array('BYHOUR', 'BYMINUTE', 'BYSECOND')) && $value == 0)) {
808 return false;
809 }
810 }
811 }
812 }
813 if (isset($byparts['BYSETPOS']) && count($byparts) < 2) {
814 return false; // BYSETPOS selects among the occurrences made by the other BYxxx parts
815 }
816 if ($isshort && (isset($byparts['BYMINUTE']) || isset($byparts['BYSECOND']))) {
817 return false;
818 }
819 if ($isshort && (isset($byparts['BYYEARDAY']) || isset($byparts['BYWEEKNO']) || isset($byparts['BYSETPOS']))) {
820 return false;
821 }
822 if (isset($byparts['BYWEEKNO']) && ($freq != 'YEARLY' || isset($byparts['BYMONTH']) || isset($byparts['BYMONTHDAY']) || isset($byparts['BYYEARDAY']))) {
823 return false;
824 }
825 if (isset($byparts['BYYEARDAY']) && ($freq != 'YEARLY' || isset($byparts['BYMONTH']) || isset($byparts['BYMONTHDAY']) || isset($byparts['BYDAY']))) {
826 return false;
827 }
828 if (isset($byparts['BYMONTHDAY']) && $freq == 'WEEKLY') {
829 return false;
830 }
831 if ($freq == 'YEARLY' && empty($rrule['BYMONTH']) && !isset($byparts['BYWEEKNO']) && !isset($byparts['BYYEARDAY']) && (isset($byparts['BYDAY']) || isset($byparts['BYMONTHDAY']))) {
832 return false;
833 }
834 return true;
835 }
836
847 private function getDaysOfMonth($year, $month, $byday, $bymonthday, $defaultday)
848 {
849 $nbdays = (int) gmdate('t', gmmktime(0, 0, 0, $month, 1, $year));
850 $fromdayofmonth = array();
851 foreach ($bymonthday as $monthday) {
852 $day = ($monthday > 0 ? $monthday : $nbdays + $monthday + 1);
853 if ($day >= 1 && $day <= $nbdays) {
854 $fromdayofmonth[$day] = $day;
855 }
856 }
857 $fromdayofweek = array();
858 foreach ($byday as $item) {
859 $matches = array();
860 for ($day = 1; $day <= $nbdays; $day++) {
861 if ((int) gmdate('w', gmmktime(0, 0, 0, $month, $day, $year)) == $item[1]) {
862 $matches[] = $day;
863 }
864 }
865 if ($item[0] == 0) {
866 foreach ($matches as $day) {
867 $fromdayofweek[$day] = $day;
868 }
869 } else {
870 $index = ($item[0] > 0 ? $item[0] - 1 : count($matches) + $item[0]);
871 if (isset($matches[$index])) {
872 $fromdayofweek[$matches[$index]] = $matches[$index];
873 }
874 }
875 }
876 if (!empty($bymonthday) && !empty($byday)) {
877 $days = array_intersect($fromdayofmonth, $fromdayofweek);
878 } elseif (!empty($bymonthday)) {
879 $days = $fromdayofmonth;
880 } elseif (!empty($byday)) {
881 $days = $fromdayofweek;
882 } else {
883 $days = ($defaultday <= $nbdays ? array($defaultday => $defaultday) : array());
884 }
885 sort($days);
886 $result = array();
887 foreach ($days as $day) {
888 $result[] = gmmktime(0, 0, 0, $month, $day, $year);
889 }
890 return $result;
891 }
892
900 private function getFirstWeekOfYear($year, $wkst)
901 {
902 $jan1 = gmmktime(0, 0, 0, 1, 1, $year);
903 $offset = (((int) gmdate('w', $jan1)) - $wkst + 7) % 7;
904 $start = $jan1 - $offset * 86400;
905 if ((7 - $offset) < 4) {
906 $start += 7 * 86400;
907 }
908 return $start;
909 }
910
917 private function getWallStart($event)
918 {
919 if (isset($event['DTSTART;VALUE=DATE']) && is_string($event['DTSTART;VALUE=DATE'])) {
920 return gmmktime(0, 0, 0, (int) substr($event['DTSTART;VALUE=DATE'], 4, 2), (int) substr($event['DTSTART;VALUE=DATE'], 6, 2), (int) substr($event['DTSTART;VALUE=DATE'], 0, 4));
921 }
922 if (isset($event['DTSTART']) && is_array($event['DTSTART']) && isset($event['DTSTART']['unixtime'])) {
923 return (int) $event['DTSTART']['unixtime'];
924 }
925 if (isset($event['DTSTART']) && !is_array($event['DTSTART'])) {
926 return (int) $event['DTSTART'];
927 }
928 return null;
929 }
930
944 public function expandRRule($rrule, $dtstart, $to, $until = 0, $from = 0)
945 {
946 $result = $this->expandRRuleOccurrences($rrule, $dtstart, $to, $until, $from);
947 if (!in_array($dtstart, $result) && $dtstart < $to && (!$until || $dtstart <= $until)) {
948 $result[] = $dtstart;
949 sort($result);
950 $maxcount = (int) ($rrule['COUNT'] ?? 0);
951 if ($maxcount) {
952 $result = array_slice($result, 0, $maxcount);
953 }
954 }
955 return $result;
956 }
957
969 private function expandRRuleOccurrences($rrule, $dtstart, $to, $until = 0, $from = 0)
970 {
971 $daysofweek = array('SU' => 0, 'MO' => 1, 'TU' => 2, 'WE' => 3, 'TH' => 4, 'FR' => 5, 'SA' => 6);
972 $freq = ($rrule['FREQ'] ?? '');
973 $interval = max(1, (int) ($rrule['INTERVAL'] ?? 1));
974 $maxcount = (int) ($rrule['COUNT'] ?? 0);
975 $wkst = $daysofweek[strtoupper($rrule['WKST'] ?? 'MO')] ?? 1;
976 $byday = (isset($rrule['BYDAY']) ? (array) $this->parseByDay($rrule['BYDAY']) : array());
977 $bymonthday = (isset($rrule['BYMONTHDAY']) ? array_map('intval', explode(',', $rrule['BYMONTHDAY'])) : array());
978 $bymonth = (isset($rrule['BYMONTH']) ? array_map('intval', explode(',', $rrule['BYMONTH'])) : array());
979 $byyearday = (isset($rrule['BYYEARDAY']) ? array_map('intval', explode(',', $rrule['BYYEARDAY'])) : array());
980 $byweekno = (isset($rrule['BYWEEKNO']) ? array_map('intval', explode(',', $rrule['BYWEEKNO'])) : array());
981 $bysetpos = (isset($rrule['BYSETPOS']) ? array_map('intval', explode(',', $rrule['BYSETPOS'])) : array());
982 $byhour = (isset($rrule['BYHOUR']) ? array_map('intval', explode(',', $rrule['BYHOUR'])) : array());
983 $byminute = (isset($rrule['BYMINUTE']) ? array_map('intval', explode(',', $rrule['BYMINUTE'])) : array());
984 $bysecond = (isset($rrule['BYSECOND']) ? array_map('intval', explode(',', $rrule['BYSECOND'])) : array());
985
986 $timeofday = (($dtstart % 86400) + 86400) % 86400;
987 $firstday = $dtstart - $timeofday;
988 $year0 = (int) gmdate('Y', $firstday);
989 $month0 = (int) gmdate('n', $firstday);
990 $day0 = (int) gmdate('j', $firstday);
991 $dayofweek0 = (int) gmdate('w', $firstday);
992 $hour0 = intdiv($timeofday, 3600);
993 $minute0 = intdiv($timeofday % 3600, 60);
994 $second0 = $timeofday % 60;
995 // Times of the day of an occurrence, for the rules that can have several by day (BYHOUR, BYMINUTE, BYSECOND)
996 $times = array();
997 foreach ((empty($byhour) ? array($hour0) : $byhour) as $hour) {
998 foreach ((empty($byminute) ? array($minute0) : $byminute) as $minute) {
999 foreach ((empty($bysecond) ? array($second0) : $bysecond) as $second) {
1000 $times[] = $hour * 3600 + $minute * 60 + $second;
1001 }
1002 }
1003 }
1004 $times = array_values(array_unique($times));
1005 sort($times);
1006 $skip = ($maxcount == 0 && $from > $dtstart);
1007
1008 $result = array();
1009 $count = 0;
1010 for ($i = 0; $i < 20000; $i++) {
1011 $candidates = array();
1012 if ($freq == 'MINUTELY' || $freq == 'HOURLY') {
1013 $step = ($freq == 'HOURLY' ? 3600 : 60) * $interval;
1014 $index = $i + ($skip ? max(0, intdiv($from - $dtstart, $step) - 1) : 0);
1015 $time = $dtstart + $index * $step;
1016 $periodstart = $time;
1017 $day = $time - ((($time % 86400) + 86400) % 86400);
1018 $ok = (empty($bymonth) || in_array((int) gmdate('n', $day), $bymonth));
1019 if ($ok && !empty($bymonthday)) {
1020 $nbdays = (int) gmdate('t', $day);
1021 $dayofmonth = (int) gmdate('j', $day);
1022 $ok = (in_array($dayofmonth, $bymonthday) || in_array($dayofmonth - $nbdays - 1, $bymonthday));
1023 }
1024 if ($ok && !empty($byday)) {
1025 $ok = false;
1026 foreach ($byday as $item) {
1027 if ($item[1] == (int) gmdate('w', $day)) {
1028 $ok = true;
1029 }
1030 }
1031 }
1032 if ($ok && !empty($byhour)) {
1033 $ok = in_array((int) gmdate('G', $time), $byhour);
1034 }
1035 if ($ok) {
1036 $candidates[] = $time;
1037 }
1038 } else {
1039 $days = array();
1040 if ($freq == 'DAILY') {
1041 $index = $i + ($skip ? max(0, intdiv($from - $firstday, $interval * 86400) - 1) : 0);
1042 $day = $firstday + $index * $interval * 86400;
1043 $periodstart = $day;
1044 $ok = (empty($bymonth) || in_array((int) gmdate('n', $day), $bymonth));
1045 if ($ok && !empty($bymonthday)) {
1046 $nbdays = (int) gmdate('t', $day);
1047 $dayofmonth = (int) gmdate('j', $day);
1048 $ok = (in_array($dayofmonth, $bymonthday) || in_array($dayofmonth - $nbdays - 1, $bymonthday));
1049 }
1050 if ($ok && !empty($byday)) {
1051 $ok = false;
1052 foreach ($byday as $item) {
1053 if ($item[1] == (int) gmdate('w', $day)) {
1054 $ok = true;
1055 }
1056 }
1057 }
1058 if ($ok) {
1059 $days[] = $day;
1060 }
1061 } elseif ($freq == 'WEEKLY') {
1062 $weekstart0 = $firstday - ((($dayofweek0 - $wkst + 7) % 7) * 86400);
1063 $index = $i + ($skip ? max(0, intdiv($from - $weekstart0, $interval * 7 * 86400) - 1) : 0);
1064 $periodstart = $weekstart0 + $index * $interval * 7 * 86400;
1065 $weekdays = array();
1066 foreach ($byday as $item) {
1067 $weekdays[] = $item[1];
1068 }
1069 if (empty($weekdays)) {
1070 $weekdays[] = $dayofweek0;
1071 }
1072 foreach ($weekdays as $weekday) {
1073 $day = $periodstart + ((($weekday - $wkst + 7) % 7) * 86400);
1074 if (empty($bymonth) || in_array((int) gmdate('n', $day), $bymonth)) {
1075 $days[] = $day;
1076 }
1077 }
1078 } elseif ($freq == 'MONTHLY') {
1079 $monthindex = $month0 - 1 + $i * $interval;
1080 if ($skip) {
1081 $monthsfrom = ((int) gmdate('Y', $from) - $year0) * 12 + ((int) gmdate('n', $from)) - $month0;
1082 $monthindex += max(0, intdiv($monthsfrom, $interval) - 1) * $interval;
1083 }
1084 $year = $year0 + intdiv($monthindex, 12);
1085 $month = $monthindex % 12 + 1;
1086 $periodstart = gmmktime(0, 0, 0, $month, 1, $year);
1087 if (empty($bymonth) || in_array($month, $bymonth)) {
1088 $days = $this->getDaysOfMonth($year, $month, $byday, $bymonthday, $day0);
1089 }
1090 } else {
1091 $index = $i + ($skip ? max(0, intdiv((int) gmdate('Y', $from) - $year0, $interval) - 1) : 0);
1092 $year = $year0 + $index * $interval;
1093 $periodstart = gmmktime(0, 0, 0, 1, 1, $year);
1094 $nbdaysofyear = (int) gmdate('z', gmmktime(0, 0, 0, 12, 31, $year)) + 1;
1095 if (!empty($byweekno)) {
1096 $firstweek = $this->getFirstWeekOfYear($year, $wkst);
1097 $nbweeks = intdiv($this->getFirstWeekOfYear($year + 1, $wkst) - $firstweek, 7 * 86400);
1098 $weekdays = array();
1099 foreach ($byday as $item) {
1100 $weekdays[] = $item[1];
1101 }
1102 if (empty($weekdays)) {
1103 $weekdays[] = $dayofweek0;
1104 }
1105 foreach ($byweekno as $weekno) {
1106 $number = ($weekno > 0 ? $weekno : $nbweeks + $weekno + 1);
1107 if ($number < 1 || $number > $nbweeks) {
1108 continue;
1109 }
1110 foreach ($weekdays as $weekday) {
1111 $days[] = $firstweek + ($number - 1) * 7 * 86400 + ((($weekday - $wkst + 7) % 7) * 86400);
1112 }
1113 }
1114 } elseif (!empty($byyearday)) {
1115 foreach ($byyearday as $yearday) {
1116 $number = ($yearday > 0 ? $yearday : $nbdaysofyear + $yearday + 1);
1117 if ($number >= 1 && $number <= $nbdaysofyear) {
1118 $days[] = $periodstart + ($number - 1) * 86400;
1119 }
1120 }
1121 } else {
1122 $months = (empty($bymonth) ? array($month0) : $bymonth);
1123 sort($months);
1124 foreach ($months as $month) {
1125 $days = array_merge($days, $this->getDaysOfMonth($year, $month, $byday, $bymonthday, $day0));
1126 }
1127 }
1128 }
1129 foreach ($days as $day) {
1130 foreach ($times as $timevalue) {
1131 $candidates[] = $day + $timevalue;
1132 }
1133 }
1134 }
1135 if ($periodstart >= $to) {
1136 break;
1137 }
1138
1139 $candidates = array_values(array_unique($candidates));
1140 sort($candidates);
1141 if (!empty($bysetpos)) {
1142 $selected = array();
1143 foreach ($bysetpos as $position) {
1144 $position = ($position > 0 ? $position - 1 : count($candidates) + $position);
1145 if (isset($candidates[$position])) {
1146 $selected[$candidates[$position]] = $candidates[$position];
1147 }
1148 }
1149 sort($selected);
1150 $candidates = $selected;
1151 }
1152
1153 foreach ($candidates as $start) {
1154 if ($start < $dtstart) {
1155 continue;
1156 }
1157 if ($start >= $to || ($until && $start > $until)) {
1158 return $result;
1159 }
1160 $result[] = $start;
1161 $count++;
1162 if ($maxcount && $count >= $maxcount) {
1163 return $result;
1164 }
1165 }
1166 }
1167 return $result;
1168 }
1169
1170 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1177 public function ical_duration_to_seconds($duration)
1178 {
1179 // phpcs:enable
1180 $reg = array();
1181 if (!preg_match('/^([+-])?P(?:([0-9]+)W)?(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/', strtoupper(trim($duration)), $reg) || $reg[0] == 'P' || substr($reg[0], -1) == 'T') {
1182 return null;
1183 }
1184 $seconds = ((int) ($reg[2] ?? 0)) * 7 * 86400 + ((int) ($reg[3] ?? 0)) * 86400 + ((int) ($reg[4] ?? 0)) * 3600 + ((int) ($reg[5] ?? 0)) * 60 + ((int) ($reg[6] ?? 0));
1185 return (($reg[1] ?? '') == '-' ? -$seconds : $seconds);
1186 }
1187
1188 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1197 public function ical_date_to_unix($ical_date, $floating = false, $timezone = '')
1198 {
1199 // phpcs:enable
1200 $ical_date = str_replace('T', '', $ical_date);
1201 $ical_date = str_replace('Z', '', $ical_date);
1202
1203 $ntime = 0;
1204 // TIME LIMITED EVENT
1205 $date = array();
1206 if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})([0-9]{0,2})/', $ical_date, $date)) {
1207 $ntime = dol_mktime((int) $date[4], (int) $date[5], (int) $date[6], (int) $date[2], (int) $date[3], (int) $date[1], ($floating ? ($timezone ? 'tz,'.$timezone : 'tzuserrel') : true));
1208 }
1209
1210 //if (empty($date[4])) print 'Error bad date: '.$ical_date.' - date1='.$date[1];
1211 //print dol_print_date($ntime,'dayhour');exit;
1212 return $ntime; // ntime is a GTM time
1213 }
1214
1220 private function getCalendarProperties()
1221 {
1222 return (isset($this->cal['VCALENDAR']) && is_array($this->cal['VCALENDAR'])) ? $this->cal['VCALENDAR'] : array();
1223 }
1224
1231 public function getCalendarTimezone()
1232 {
1233 $calendar = $this->getCalendarProperties();
1234 $timezone = (isset($calendar['X-WR-TIMEZONE']) && is_string($calendar['X-WR-TIMEZONE'])) ? trim($calendar['X-WR-TIMEZONE'], " \t\"") : '';
1235 if ($timezone === '' || !in_array($timezone, timezone_identifiers_list())) {
1236 return '';
1237 }
1238 return $timezone;
1239 }
1240
1248 public function getPhpTimezone($tzid)
1249 {
1250 $tzid = trim($tzid, " \t\"");
1251 if ($tzid === '') {
1252 return '';
1253 }
1254 $identifiers = timezone_identifiers_list();
1255 foreach ($identifiers as $identifier) {
1256 if (strcasecmp($identifier, $tzid) == 0) {
1257 return $identifier;
1258 }
1259 }
1260 // Most common Windows names (written by Outlook and Exchange)
1261 $windows = array(
1262 'romance standard time' => 'Europe/Paris', 'w. europe standard time' => 'Europe/Berlin', 'central europe standard time' => 'Europe/Budapest',
1263 'central european standard time' => 'Europe/Warsaw', 'gmt standard time' => 'Europe/London', 'greenwich standard time' => 'Atlantic/Reykjavik',
1264 'e. europe standard time' => 'Europe/Chisinau', 'fle standard time' => 'Europe/Kiev', 'gtb standard time' => 'Europe/Bucharest', 'russian standard time' => 'Europe/Moscow',
1265 'turkey standard time' => 'Europe/Istanbul', 'eastern standard time' => 'America/New_York', 'central standard time' => 'America/Chicago',
1266 'mountain standard time' => 'America/Denver', 'pacific standard time' => 'America/Los_Angeles', 'us mountain standard time' => 'America/Phoenix',
1267 'atlantic standard time' => 'America/Halifax', 'e. south america standard time' => 'America/Sao_Paulo', 'argentina standard time' => 'America/Buenos_Aires',
1268 'china standard time' => 'Asia/Shanghai', 'tokyo standard time' => 'Asia/Tokyo', 'korea standard time' => 'Asia/Seoul', 'india standard time' => 'Asia/Kolkata',
1269 'singapore standard time' => 'Asia/Singapore', 'arabian standard time' => 'Asia/Dubai', 'aus eastern standard time' => 'Australia/Sydney',
1270 'new zealand standard time' => 'Pacific/Auckland', 'south africa standard time' => 'Africa/Johannesburg', 'egypt standard time' => 'Africa/Cairo',
1271 'utc' => 'UTC', 'w. central africa standard time' => 'Africa/Lagos', 'morocco standard time' => 'Africa/Casablanca'
1272 );
1273 $key = strtolower($tzid);
1274 if (isset($windows[$key])) {
1275 return $windows[$key];
1276 }
1277
1278 // Unknown name: the file can say which time zone it is (X-LIC-LOCATION of its VTIMEZONE)
1279 $vtimezones = $this->getVtimezones();
1280 return (isset($vtimezones[$tzid]) ? $vtimezones[$tzid]['location'] : '');
1281 }
1282
1290 private function getVtimezones()
1291 {
1292 if ($this->vtimezones !== null) {
1293 return $this->vtimezones;
1294 }
1295 $this->vtimezones = [];
1296
1297 $text = (string) preg_replace('/\r?\n[ \t]/', '', (string) $this->file_text); // Unfold the lines
1298 if (!preg_match_all('/^BEGIN:VTIMEZONE\s*$(.*?)^END:VTIMEZONE\s*$/ims', $text, $blocks)) {
1299 return $this->vtimezones;
1300 }
1301 $identifiers = timezone_identifiers_list();
1302 foreach ($blocks[1] as $block) {
1303 if (!preg_match('/^TZID[^:\r\n]*:\s*"?([^"\r\n]+?)"?\s*$/im', $block, $reg)) {
1304 continue;
1305 }
1306 $tzid = $reg[1];
1307 $location = '';
1308 if (preg_match('/^X-LIC-LOCATION[^:\r\n]*:\s*([^\r\n]+?)\s*$/im', $block, $reg)) {
1309 foreach ($identifiers as $identifier) {
1310 if (strcasecmp($identifier, $reg[1]) == 0) {
1311 $location = $identifier;
1312 break;
1313 }
1314 }
1315 }
1316 $changes = [];
1317 if (preg_match_all('/^BEGIN:(STANDARD|DAYLIGHT)\s*$(.*?)^END:\1\s*$/ims', $block, $parts)) {
1318 foreach ($parts[2] as $part) {
1319 $props = [];
1320 $offsets = [];
1321 $rdates = [];
1322 foreach (preg_split('/\r?\n/', $part) as $line) {
1323 if (!preg_match('/^([A-Z-]+)[^:]*:(.*)$/i', trim($line), $reg)) {
1324 continue;
1325 }
1326 $name = strtoupper($reg[1]);
1327 if ($name == 'RDATE') {
1328 foreach (explode(',', $reg[2]) as $rdate) {
1329 if (preg_match('/^\s*(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/', $rdate, $d)) {
1330 $rdates[] = (int) gmmktime((int) $d[4], (int) $d[5], (int) $d[6], (int) $d[2], (int) $d[3], (int) $d[1]);
1331 }
1332 }
1333 } elseif ($name == 'TZOFFSETFROM') {
1334 $offsets['before'] = $this->parseUtcOffset($reg[2]);
1335 } elseif ($name == 'TZOFFSETTO') {
1336 $offsets['after'] = $this->parseUtcOffset($reg[2]);
1337 } else {
1338 $props[$name] = trim($reg[2]);
1339 }
1340 }
1341 if (empty($props['DTSTART']) || !preg_match('/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/', $props['DTSTART'], $d)
1342 || !isset($offsets['before']) || !isset($offsets['after'])) {
1343 continue;
1344 }
1345 $rrule = !empty($props['RRULE']) ? $this->ical_rrule($props['RRULE']) : [];
1346 $changes[] = [
1347 'start' => (int) gmmktime((int) $d[4], (int) $d[5], (int) $d[6], (int) $d[2], (int) $d[3], (int) $d[1]),
1348 'before' => $offsets['before'],
1349 'after' => $offsets['after'],
1350 'rrule' => ($rrule && $this->isRRuleSupported($rrule)) ? $rrule : [],
1351 'rdates' => $rdates,
1352 ];
1353 }
1354 }
1355 $this->vtimezones[$tzid] = ['location' => $location, 'changes' => $changes];
1356 }
1357 return $this->vtimezones;
1358 }
1359
1366 private function parseUtcOffset($offset)
1367 {
1368 if (!preg_match('/^([+-])(\d{2})(\d{2})(\d{2})?$/', trim($offset), $reg)) {
1369 return null;
1370 }
1371 return ($reg[1] == '-' ? -1 : 1) * ((int) $reg[2] * 3600 + (int) $reg[3] * 60 + (int) ($reg[4] ?? 0));
1372 }
1373
1381 private function getVtimezoneOffset($localtime, $tzid)
1382 {
1383 $vtimezones = $this->getVtimezones();
1384 if (empty($vtimezones[$tzid]['changes'])) {
1385 return null;
1386 }
1387 $offset = null;
1388 $lastchange = null;
1389 $firstchange = null;
1390 $offsetbefore = null;
1391 foreach ($vtimezones[$tzid]['changes'] as $change) {
1392 $starts = [$change['start']];
1393 if ($change['rrule']) {
1394 $starts = $this->expandRRule($change['rrule'], $change['start'], $localtime + 2 * 86400, 0, $localtime - 400 * 86400);
1395 }
1396 foreach ($change['rdates'] as $rdate) {
1397 $starts[] = $rdate;
1398 }
1399 foreach ($starts as $start) {
1400 // A local time in the gap (spring forward) keeps the offset before, and a repeated local time (fall back) uses the first one
1401 $effective = $start + max(0, $change['after'] - $change['before']);
1402 if ($firstchange === null || $start < $firstchange) {
1403 $firstchange = $start;
1404 $offsetbefore = $change['before'];
1405 }
1406 if ($effective <= $localtime && ($lastchange === null || $start > $lastchange)) {
1407 $lastchange = $start;
1408 $offset = $change['after'];
1409 }
1410 }
1411 }
1412 if ($offset === null && $offsetbefore !== null) {
1413 $offset = $offsetbefore;
1414 }
1415 return $offset;
1416 }
1417
1424 public function isTzidKnown($tzid)
1425 {
1426 if ($this->getPhpTimezone($tzid) !== '') {
1427 return true;
1428 }
1429 $vtimezones = $this->getVtimezones();
1430 return !empty($vtimezones[trim($tzid, " \t\"")]['changes']);
1431 }
1432
1440 public function tzidToTimestamp($localtime, $tzid)
1441 {
1442 $timezone = $this->getPhpTimezone($tzid);
1443 if ($timezone === '') {
1444 // Not a name known by PHP: we use the rules of the time zone written in the file
1445 $offset = $this->getVtimezoneOffset($localtime, trim($tzid, " \t\""));
1446 return ($offset === null ? null : $localtime - $offset);
1447 }
1448 return dol_mktime((int) gmdate('G', $localtime), (int) gmdate('i', $localtime), (int) gmdate('s', $localtime), (int) gmdate('n', $localtime), (int) gmdate('j', $localtime), (int) gmdate('Y', $localtime), 'tz,'.$timezone);
1449 }
1450
1451 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1459 public function ical_dt_date($key, $value)
1460 {
1461 // phpcs:enable
1462 $return_value = array();
1463
1464 // Analyse the parameters of the key (TZID...)
1465 $params = $this->getKeyParams($key);
1466 $key = strtoupper(explode(';', $key, 2)[0]);
1467
1468 if (empty($params['TZID'])) { // not TZID in key
1469 // A date time without Z (like 19970714T133000) is a "floating" time (RFC 5545): it is a local time, not a GMT time
1470 $floating = (strpos($value, 'T') !== false && strtoupper(substr(trim($value), -1)) != 'Z');
1471 $value = ($value === '' ? '' : $this->ical_date_to_unix($value, $floating, ($floating ? $this->getCalendarTimezone() : '')));
1472 return array($key, $value);
1473 }
1474
1475 $value = str_replace('T', '', $value);
1476
1477 $return_value['TZID'] = trim($params['TZID'], '"'); // RFC 5545 allows quoted parameter values (TZID="Europe/Berlin")
1478 $return_value['unixtime'] = ($value === '' ? '' : $this->ical_date_to_unix($value)); // Local time as GMT timestamp; TZ correction is done by caller (AGENDA_EXT_BUGGEDFILEx)
1479
1480 return array($key, $return_value);
1481 }
1482
1489 public function hasStartDate($event)
1490 {
1491 if (isset($event['DTSTART;VALUE=DATE'])) {
1492 return $event['DTSTART;VALUE=DATE'] !== '';
1493 }
1494
1495 if (!array_key_exists('DTSTART', $event)) {
1496 return false;
1497 }
1498
1499 if (is_array($event['DTSTART'])) {
1500 return isset($event['DTSTART']['unixtime']) && $event['DTSTART']['unixtime'] !== '';
1501 }
1502
1503 return $event['DTSTART'] !== '' && $event['DTSTART'] !== null;
1504 }
1505
1512 public function getKeyParams($key)
1513 {
1514 $params = array();
1515 $parts = explode(';', $key);
1516 array_shift($parts);
1517 foreach ($parts as $part) {
1518 $item = explode('=', $part, 2);
1519 if (isset($item[1]) && $item[0] !== '') {
1520 $params[strtoupper(trim($item[0]))] = trim($item[1]);
1521 }
1522 }
1523 return $params;
1524 }
1525
1526 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1532 public function get_sort_event_list()
1533 {
1534 // phpcs:enable
1535 $temp = $this->get_event_list();
1536 if (!empty($temp)) {
1537 usort($temp, array($this, "ical_dtstart_compare")); // false-positive @phpstan-ignore-line
1538 return $temp;
1539 } else {
1540 return false;
1541 }
1542 }
1543
1544 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1552 public function ical_dtstart_compare($a, $b)
1553 {
1554 // phpcs:enable
1555 return strnatcasecmp($a['DTSTART']['unixtime'], $b['DTSTART']['unixtime']);
1556 }
1557
1558 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1564 public function get_event_list()
1565 {
1566 // phpcs:enable
1567 return (empty($this->cal['VEVENT']) ? array() : $this->cal['VEVENT']);
1568 }
1569
1570 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1576 public function get_freebusy_list()
1577 {
1578 // phpcs:enable
1579 return (empty($this->cal['VFREEBUSY']) ? array() : $this->cal['VFREEBUSY']);
1580 }
1581
1582 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1588 public function get_todo_list()
1589 {
1590 // phpcs:enable
1591 return $this->cal['VTODO'];
1592 }
1593
1594 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1600 public function get_calender_data()
1601 {
1602 // phpcs:enable
1603 return $this->cal['VCALENDAR'];
1604 }
1605
1606 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1612 public function get_all_data()
1613 {
1614 // phpcs:enable
1615 return $this->cal;
1616 }
1617}
Class to read/parse ICal calendars.
get_all_data()
Return array with all data.
get_event_list()
Return eventlist array (not sorted eventlist array)
isIcalText($text)
Return if a text looks like an iCal file (it starts, after a BOM and blank lines, with BEGIN:VCALENDA...
parse($uri, $usecachefile='', $delaycache=3600)
Translate Calendar.
getDaysOfMonth($year, $month, $byday, $bymonthday, $defaultday)
Return the days (midnight, as GMT timestamps) of a month that match BYDAY and BYMONTHDAY.
parseByDay($value)
Decode a BYDAY value ("MO,TU", "2MO", "-1FR"...)
ical_dt_date($key, $value)
Return unix date from iCal date format.
getTodoAndJournalAsEvents()
Return the to do (VTODO) and the journal entries (VJOURNAL) as events, so they can be shown in an age...
ical_rrule($value)
Parse RRULE return array.
retun_key_value($text)
Parse text "XXXX:value text some with : " and return array($key = "XXXX", $value="value");.
convertToUtf8($text, $contenttype='')
Convert a text to UTF-8.
get_todo_count()
Returns the number of to do.
getVtimezones()
Return the time zones (VTIMEZONE) declared in the file, by TZID.
getVtimezoneOffset($localtime, $tzid)
Return the offset from UTC (in seconds) of a local date and time of a time zone declared in the file ...
ical_dtstart_compare($a, $b)
Compare two unix timestamp.
get_event_count()
Returns the number of calendar events.
__construct()
Constructor.
add_to_array($type, $key, $value)
Add to $this->ical array one value and key.
isTzidKnown($tzid)
Tell if the dates of a TZID can be converted by tzidToTimestamp(): name known by PHP,...
getKeyParams($key)
Return the parameters of a property key (for 'DTSTART;VALUE=DATE-TIME;TZID=Europe/Paris',...
read_file($file)
Read text file, icalender text file.
hasStartDate($event)
Check whether a parsed calendar component has a usable start date.
expandRRuleOccurrences($rrule, $dtstart, $to, $until=0, $from=0)
Return the starts of the occurrences of a recurrence rule (see isRRuleSupported()).
getPhpTimezone($tzid)
Return the name of the PHP time zone that matches the TZID of a date.
get_sort_event_list()
Return sorted eventlist as array or false if calendar is empty.
getCalendarTimezone()
Return the time zone of the calendar, declared by the property X-WR-TIMEZONE (not standard but writte...
getCalendarProperties()
Return the properties of the calendar itself (VCALENDAR: PRODID, X-WR-TIMEZONE...).
get_freebusy_list()
Return freebusy array (not sort eventlist array)
ical_duration_to_seconds($duration)
Return the number of seconds of an iCal duration (RFC 5545: P1W, P1D, PT1H30M, -PT15M,...
tzidToTimestamp($localtime, $tzid)
Convert a local date and time of a time zone (TZID) into a real time, taking into account the dayligh...
get_todo_list()
Return to do array (not sorted todo array)
ical_date_to_unix($ical_date, $floating=false, $timezone='')
Return Unix time from ical date time format (YYYYMMDD[T]HHMMSS[Z] or YYYYMMDD[T]HHMMSS)
parseUtcOffset($offset)
Convert an offset of a time zone written by iCal ('+0100', '-053000') into seconds.
get_calender_data()
Return base calendar data.
getWallStart($event)
Return the start of an event as GMT timestamp of the date and time written in the file.
isRRuleSupported($rrule)
Return if a recurrence rule can be expanded by expandRRule(): FREQ MINUTELY, HOURLY,...
getFirstWeekOfYear($year, $wkst)
Return the start (as GMT timestamp of the date and time written in the file) of the first week of a y...
expandRRule($rrule, $dtstart, $to, $until=0, $from=0)
Return the starts of the occurrences of a recurrence rule (see isRRuleSupported()),...
dol_filemtime($pathoffile)
Return time of a file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1, $timeoutconnect=0, $timeoutresponse=0, $otherCurlOptions=array(), $morelogsuffix='')
Function to get a content from an URL (use proxy if proxy defined).
quotedPrintDecode($str)
Decode vcal format.
Definition xcal.lib.php:699