forked from jeroendesloovere/vcard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VCardParser.php
333 lines (304 loc) · 10.2 KB
/
VCardParser.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
330
331
332
333
<?php
namespace JeroenDesloovere\VCard;
/*
* This file is part of the VCard PHP Class from Jeroen Desloovere.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Iterator;
/**
* VCard PHP Class to parse .vcard files.
*
* This class is heavily based on the Zendvcard project (seemingly abandoned),
* which is licensed under the Apache 2.0 license.
* More information can be found at https://code.google.com/archive/p/zendvcard/
*/
class VCardParser implements Iterator
{
/**
* The raw VCard content.
*
* @var string
*/
protected $content;
/**
* The VCard data objects.
*
* @var array
*/
protected $vcardObjects;
/**
* The iterator position.
*
* @var int
*/
protected $position;
/**
* Helper function to parse a file directly.
*
* @param string $filename
* @return self
*/
public static function parseFromFile($filename)
{
if (file_exists($filename) && is_readable($filename)) {
return new self(file_get_contents($filename));
} else {
throw new \RuntimeException(sprintf("File %s is not readable, or doesn't exist.", $filename));
}
}
public function __construct($content)
{
$this->content = $content;
$this->vcardObjects = [];
$this->rewind();
$this->parse();
}
public function rewind()
{
$this->position = 0;
}
public function current()
{
if ($this->valid()) {
return $this->getCardAtIndex($this->position);
}
}
public function key()
{
return $this->position;
}
public function next()
{
$this->position++;
}
public function valid()
{
return !empty($this->vcardObjects[$this->position]);
}
/**
* Fetch all the imported VCards.
*
* @return array
* A list of VCard card data objects.
*/
public function getCards()
{
return $this->vcardObjects;
}
/**
* Fetch the imported VCard at the specified index.
*
* @throws OutOfBoundsException
*
* @param int $i
*
* @return stdClass
* The card data object.
*/
public function getCardAtIndex($i)
{
if (isset($this->vcardObjects[$i])) {
return $this->vcardObjects[$i];
}
throw new \OutOfBoundsException();
}
/**
* Start the parsing process.
*
* This method will populate the data object.
*/
protected function parse()
{
// Normalize new lines.
$this->content = str_replace(["\r\n", "\r"], "\n", $this->content);
// RFC2425 5.8.1. Line delimiting and folding
// Unfolding is accomplished by regarding CRLF immediately followed by
// a white space character (namely HTAB ASCII decimal 9 or. SPACE ASCII
// decimal 32) as equivalent to no characters at all (i.e., the CRLF
// and single white space character are removed).
$this->content = preg_replace("/\n(?:[ \t])/", "", $this->content);
$lines = explode("\n", $this->content);
// Parse the VCard, line by line.
foreach ($lines as $line) {
$line = trim($line);
if (strtoupper($line) == "BEGIN:VCARD") {
$cardData = new \stdClass();
} elseif (strtoupper($line) == "END:VCARD") {
$this->vcardObjects[] = $cardData;
} elseif (!empty($line)) {
// Strip grouping information. We don't use the group names. We
// simply use a list for entries that have multiple values.
// As per RFC, group names are alphanumerical, and end with a
// period (.).
$line = preg_replace('/^\w+\./', '', $line);
$type = '';
$value = '';
@list($type, $value) = explode(':', $line, 2);
$types = explode(';', $type);
$element = strtoupper($types[0]);
array_shift($types);
// Normalize types. A type can either be a type-param directly,
// or can be prefixed with "type=". E.g.: "INTERNET" or
// "type=INTERNET".
if (!empty($types)) {
$types = array_map(function($type) {
return preg_replace('/^type=/i', '', $type);
}, $types);
}
$i = 0;
$rawValue = false;
foreach ($types as $type) {
if (preg_match('/base64/', strtolower($type))) {
$value = base64_decode($value);
unset($types[$i]);
$rawValue = true;
} elseif (preg_match('/encoding=b/', strtolower($type))) {
$value = base64_decode($value);
unset($types[$i]);
$rawValue = true;
} elseif (preg_match('/quoted-printable/', strtolower($type))) {
$value = quoted_printable_decode($value);
unset($types[$i]);
$rawValue = true;
} elseif (strpos(strtolower($type), 'charset=') === 0) {
try {
$value = mb_convert_encoding($value, "UTF-8", substr($type, 8));
} catch (\Exception $e) {
}
unset($types[$i]);
}
$i++;
}
switch (strtoupper($element)) {
case 'FN':
$cardData->fullname = $value;
break;
case 'N':
foreach ($this->parseName($value) as $key => $val) {
$cardData->{$key} = $val;
}
break;
case 'BDAY':
$cardData->birthday = $this->parseBirthday($value);
break;
case 'ADR':
if (!isset($cardData->address)) {
$cardData->address = [];
}
$key = !empty($types) ? implode(';', $types) : 'WORK;POSTAL';
$cardData->address[$key][] = $this->parseAddress($value);
break;
case 'TEL':
if (!isset($cardData->phone)) {
$cardData->phone = [];
}
$key = !empty($types) ? implode(';', $types) : 'default';
$cardData->phone[$key][] = $value;
break;
case 'EMAIL':
if (!isset($cardData->email)) {
$cardData->email = [];
}
$key = !empty($types) ? implode(';', $types) : 'default';
$cardData->email[$key][] = $value;
break;
case 'REV':
$cardData->revision = $value;
break;
case 'VERSION':
$cardData->version = $value;
break;
case 'ORG':
$cardData->organization = $value;
break;
case 'URL':
if (!isset($cardData->url)) {
$cardData->url = [];
}
$key = !empty($types) ? implode(';', $types) : 'default';
$cardData->url[$key][] = $value;
break;
case 'TITLE':
$cardData->title = $value;
break;
case 'PHOTO':
if ($rawValue) {
$cardData->rawPhoto = $value;
} else {
$cardData->photo = $value;
}
break;
case 'LOGO':
if ($rawValue) {
$cardData->rawLogo = $value;
} else {
$cardData->logo = $value;
}
break;
case 'NOTE':
$cardData->note = $this->unescape($value);
break;
case 'CATEGORIES':
$cardData->categories = array_map('trim', explode(',', $value));
break;
}
}
}
}
protected function parseName($value)
{
@list(
$lastname,
$firstname,
$additional,
$prefix,
$suffix
) = explode(';', $value);
return (object) [
'lastname' => $lastname,
'firstname' => $firstname,
'additional' => $additional,
'prefix' => $prefix,
'suffix' => $suffix,
];
}
protected function parseBirthday($value)
{
return new \DateTime($value);
}
protected function parseAddress($value)
{
@list(
$name,
$extended,
$street,
$city,
$region,
$zip,
$country,
) = explode(';', $value);
return (object) [
'name' => $name,
'extended' => $extended,
'street' => $street,
'city' => $city,
'region' => $region,
'zip' => $zip,
'country' => $country,
];
}
/**
* Unescape newline characters according to RFC2425 section 5.8.4.
* This function will replace escaped line breaks with PHP_EOL.
*
* @link http://tools.ietf.org/html/rfc2425#section-5.8.4
* @param string $text
* @return string
*/
protected function unescape($text)
{
return str_replace("\\n", PHP_EOL, $text);
}
}