forked from n3oklan/ical-easy-reader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iCalEasyReader.php
329 lines (291 loc) · 9 KB
/
iCalEasyReader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
<?php
/**
* iCalEasyReader is an easy to understood class, loads a "ics" format string and returns an array with the traditional iCal fields
*
* @category Parser
* @author Matias Perrone <matias.perrone at gmail dot com>
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @version 3.1.7
* @return array|false
*/
class iCalEasyReader
{
protected $ical = null;
/**
* Loads the calendar, and returns an array with the fields.
*
* @param string $data the ical in the string format
* @param boolean $ignoreNonStandardFields default true. Set to true to ignore "X-" fields.
* @return array|false Returns an array or false if an error occurs
*/
public function &load(string $data, bool $ignoreNonStandardFields = true)
{
$this->ical = false;
$lines = $this->getLines($data);
// First and last items
$this->getFirstAndLastLines($lines, $first, $last);
// If not malformed => process
if (!is_null($first) and !is_null($last)) {
$lines = array_values(array_slice($lines, $first + 1, ($last - $first - 1), true));
$this->processCalendar($lines, $ignoreNonStandardFields);
}
return $this->ical;
}
protected function &concatLineContinuations(string &$data, string $lineTermination = "\r\n")
{
$data = preg_replace("/{$lineTermination}( |\t)/m", '', $data);
return $data;
}
protected function convertCaracters(string &$data)
{
$chars = $this->mb_str_split($data);
for ($ipos = 1; $ipos < count($chars); $ipos++) {
$clean = false;
switch ($chars[$ipos - 1]) {
case '^':
switch ($chars[$ipos]) {
case 'n':
$chars[$ipos - 1] = "\n";
$clean = true;
break;
case '\'':
$chars[$ipos - 1] = '"';
$clean = true;
break;
case '^':
break;
}
break;
case '\\':
switch ($chars[$ipos]) {
case 'n':
$chars[$ipos - 1] = "\n";
$clean = true;
break;
case 't':
$chars[$ipos - 1] = "\t";
$clean = true;
break;
case ',':
case ';':
$chars[$ipos - 1] = $chars[$ipos];
$clean = true;
break;
}
break;
}
if ($clean) {
$chars[$ipos] = '';
$ipos++;
}
}
$data = implode($chars);
return $data;
}
protected function &getLines(string &$data, int $lineTerminatorSelected = 0)
{
$data = str_replace("\r\n", "\n", $data);
$possibleLineTerminators = ["\n", "\r"];
$lineTerminator = $possibleLineTerminators[$lineTerminatorSelected];
$this->concatLineContinuations($data, $lineTerminator);
$lines = mb_split($lineTerminator, $data);
// Taking into consideration non standard endlines
if (count($lines) === 1 and $lineTerminatorSelected < (count($possibleLineTerminators) - 1)) {
$lineTerminatorSelected++;
unset($lines);
$lines = $this->getLines($data, $lineTerminatorSelected);
}
// Delete empty ones
$lines = array_values(array_filter($lines));
return $lines;
}
protected function addType(&$value, $item)
{
$type = explode('=', $item);
if (count($type) > 1 and $type[0] == 'VALUE')
$value['TYPE'] = $type[1];
else
$value[$type[0]] = $type[1];
array_walk($value, [$this, 'convertCaracters']);
return $value;
}
protected function addItem(array &$current, string &$line)
{
$item = $this->split(':', $line, 2);
if (!array_key_exists(1, $item)) {
trigger_error("Unexpected Line error. Possible Corruption. Line " . strlen($line) . ":" . PHP_EOL . $line . PHP_EOL, E_USER_NOTICE);
return;
}
$key = $item[0];
$value = $item[1] ?? null;
$subitem = $this->split(';', $key, 2);
if (count($subitem) > 1) {
$key = $subitem[0];
$value = ['VALUE' => $value];
if (count($this->split(';', $subitem[1])) > 1)
$value += $this->processMultivalue($subitem[1]);
else
$this->addType($value, $subitem[1]);
}
// Multi value
if (is_string($value)) {
$this->processMultivalue($value);
if (is_array($value)) {
array_walk($value, [$this, 'convertCaracters']);
} else {
$this->convertCaracters($value);
}
}
if (!array_key_exists($key, $current)) {
$current[$key] = $value;
} elseif (!is_array($current[$key]) or !array_key_exists(0, $current[$key])) {
$current[$key] = [$current[$key], $value];
} else {
$current[$key][] = $value;
}
}
protected function processMultivalue(&$value)
{
$z = $this->split(';', $value);
if (count($z) > 1) {
$value = [];
foreach ($z as &$v) {
$t = $this->split('=', $v);
$value[$t[0]] = $t[count($t) - 1];
}
}
unset($z);
return $value;
}
protected function ignoreLine($line, bool $ignoreNonStandardField)
{
$isNonStandard = substr($line, 0, 2) == 'X-';
$ignore = ($isNonStandard and $ignoreNonStandardField) or trim($line) == '';
return $ignore;
}
protected function processCalendar(array &$lines, bool $ignoreNonStandardFields)
{
$regex_opt = 'mid';
$this->ical = [];
$level = 0;
$current = [&$this->ical];
// Join line continuations first
foreach ($lines as $line) {
// There are cases like "ATTENDEE" that may take several lines.
if ($this->ignoreLine($line, $ignoreNonStandardFields)) {
continue;
}
$pattern = '^(BEGIN|END)\:(.+)$'; // (VALARM|VTODO|VJOURNAL|VEVENT|VFREEBUSY|VCALENDAR|DAYLIGHT|VTIMEZONE|STANDARD|VAVAILABILITY)
mb_ereg_search_init($line);
// $section
// 0 => BEGIN:VEVENT
// 1 => BEGIN
// 2 => VEVENT
$section = mb_ereg_search_regs($pattern, $regex_opt);
if (!$section) {
$this->addItem($current[$level], $line);
} else {
// END
if ($section[1] === 'END') {
$level--;
}
// BEGIN
if ($section[1] === 'BEGIN') {
$name = $section[2];
// If section not exists => Create
if (!isset($current[$level][$name])) {
$current[$level][$name] = [];
}
// Get index of the new item
$last = count($current[$level][$name]);
// Initialize new item
$current[$level][$name][$last] = [];
// Set the new current section
$current[$level + 1] = &$current[$level][$name][$last];
// Increase current level
$level++;
}
}
}
}
/**
* Since the PHP function of "mb_str_split" does not work on PHP versions prior to to PHP 7.4.0,
* (see https://www.php.net/mb_str_split), I incorporated [email protected]'s PolyFill function
* and wrapped it inside an if(!function_exists) application. This resolved the "Call to undefined function"
* error for PHP versions prior to PHP 7.4.0. -- Douglas "BearlyDoug" Hazard
*/
protected function mb_str_split($string, $split_length = 1, $encoding = null)
{
if (function_exists('mb_str_split')) {
return mb_str_split($string);
}
if (null !== $string && !\is_scalar($string) && !(\is_object($string) && \method_exists($string, '__toString'))) {
trigger_error('mb_str_split(): expects parameter 1 to be string, ' . \gettype($string) . ' given', E_USER_WARNING);
return null;
}
if (null !== $split_length && !\is_bool($split_length) && !\is_numeric($split_length)) {
trigger_error('mb_str_split(): expects parameter 2 to be int, ' . \gettype($split_length) . ' given', E_USER_WARNING);
return null;
}
$split_length = (int) $split_length;
if (1 > $split_length) {
trigger_error('mb_str_split(): The length of each segment must be greater than zero', E_USER_WARNING);
return false;
}
if (null === $encoding) {
$encoding = mb_internal_encoding();
} else {
$encoding = (string) $encoding;
}
if (!in_array($encoding, mb_list_encodings(), true)) {
static $aliases;
if ($aliases === null) {
$aliases = [];
foreach (mb_list_encodings() as $encoding) {
$encoding_aliases = mb_encoding_aliases($encoding);
if ($encoding_aliases) {
foreach ($encoding_aliases as $alias) {
$aliases[] = $alias;
}
}
}
}
if (!in_array($encoding, $aliases, true)) {
trigger_error('mb_str_split(): Unknown encoding "' . $encoding . '"', E_USER_WARNING);
return null;
}
}
$result = [];
$length = mb_strlen($string, $encoding);
for ($i = 0; $i < $length; $i += $split_length) {
$result[] = mb_substr($string, $i, $split_length, $encoding);
}
return $result;
}
protected function getFirstAndLastLines(array &$lines, int &$first = null, int &$last = null)
{
$regex_opt = 'mid';
$first = 0;
$last = count($lines) - 1;
$beginExists = mb_ereg_match('^BEGIN:VCALENDAR', $lines[$first] ?? '', $regex_opt);
$endExists = mb_ereg_match('^END:VCALENDAR', $lines[$last] ?? '', $regex_opt);
// If the first line is not the begin or the last is the end of calendar, look for the end and/or the beginning.
if (!$beginExists or !$endExists) {
$first = $beginExists ? $first : null;
$last = $endExists ? $last : null;
foreach ($lines as $i => &$line) {
if (is_null($first) and mb_ereg_match('^BEGIN:VCALENDAR', $line, $regex_opt)) {
$first = $i;
}
if (is_null($last) and mb_ereg_match('^END:VCALENDAR', $line, $regex_opt)) {
$last = $i;
break;
}
}
}
}
protected function split(string $separator, string $value, int $limit = -1): array
{
return mb_split("(?<!\\\\){$separator}", $value, $limit);
}
}