-
Notifications
You must be signed in to change notification settings - Fork 47
/
carddav.php
702 lines (629 loc) · 16.9 KB
/
carddav.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
<?php
/**
* CardDAV PHP
*
* Simple CardDAV query
* --------------------
* $carddav = new carddav_backend('https://davical.example.com/user/contacts/');
* $carddav->set_auth('username', 'password');
* echo $carddav->get();
*
*
* Simple vCard query
* ------------------
* $carddav = new carddav_backend('https://davical.example.com/user/contacts/');
* $carddav->set_auth('username', 'password');
* echo $carddav->get_vcard('0126FFB4-2EB74D0A-302EA17F');
*
*
* XML vCard query
* ------------------
* $carddav = new carddav_backend('https://davical.example.com/user/contacts/');
* $carddav->set_auth('username', 'password');
* echo $carddav->get_xml_vcard('0126FFB4-2EB74D0A-302EA17F');
*
*
* Check CardDAV server connection
* -------------------------------
* $carddav = new carddav_backend('https://davical.example.com/user/contacts/');
* $carddav->set_auth('username', 'password');
* var_dump($carddav->check_connection());
*
*
* CardDAV delete query
* --------------------
* $carddav = new carddav_backend('https://davical.example.com/user/contacts/');
* $carddav->set_auth('username', 'password');
* $carddav->delete('0126FFB4-2EB74D0A-302EA17F');
*
*
* CardDAV add query
* --------------------
* $vcard = 'BEGIN:VCARD
* VERSION:3.0
* UID:1f5ea45f-b28a-4b96-25as-ed4f10edf57b
* FN:Christian Putzke
* N:Christian;Putzke;;;
* EMAIL;TYPE=OTHER:[email protected]
* END:VCARD';
*
* $carddav = new carddav_backend('https://davical.example.com/user/contacts/');
* $carddav->set_auth('username', 'password');
* $vcard_id = $carddav->add($vcard);
*
*
* CardDAV update query
* --------------------
* $vcard = 'BEGIN:VCARD
* VERSION:3.0
* UID:1f5ea45f-b28a-4b96-25as-ed4f10edf57b
* FN:Christian Putzke
* N:Christian;Putzke;;;
* EMAIL;TYPE=OTHER:[email protected]
* END:VCARD';
*
* $carddav = new carddav_backend('https://davical.example.com/user/contacts/');
* $carddav->set_auth('username', 'password');
* $carddav->update($vcard, '0126FFB4-2EB74D0A-302EA17F');
*
*
* CardDAV debug
* -------------
* $carddav = new carddav_backend('https://davical.example.com/user/contacts/');
* $carddav->enable_debug();
* $carddav->set_auth('username', 'password');
* $carddav->get();
* var_dump($carddav->get_debug());
*
*
* CardDAV server list
* -------------------
* DAViCal: https://example.com/{resource|principal|username}/{collection}/
* Apple Addressbook Server: https://example.com/addressbooks/users/{resource|principal|username}/{collection}/
* memotoo: https://sync.memotoo.com/cardDAV/
* SabreDAV: https://example.com/addressbooks/{resource|principal|username}/{collection}/
* ownCloud: https://example.com/apps/contacts/carddav.php/addressbooks/{resource|principal|username}/{collection}/
* SOGo: https://example.com/SOGo/dav/{resource|principal|username}/Contacts/{collection}/
*
*
* @author Christian Putzke <[email protected]>
* @copyright Christian Putzke
* @link http://www.graviox.de/
* @link https://twitter.com/cputzke/
* @since 20.07.2011
* @version 0.6
* @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*
*/
class carddav_backend
{
/**
* CardDAV PHP Version
*
* @constant string
*/
const VERSION = '0.6';
/**
* User agent displayed in http requests
*
* @constant string
*/
const USERAGENT = 'CardDAV PHP/';
/**
* CardDAV server url
*
* @var string
*/
private $url = null;
/**
* CardDAV server url_parts
*
* @var array
*/
private $url_parts = null;
/**
* Authentication string
*
* @var string
*/
private $auth = null;
/**
* Authentication: username
*
* @var string
*/
private $username = null;
/**
* Authentication: password
*
* @var string
*/
private $password = null;
/**
* Characters used for vCard id generation
*
* @var array
*/
private $vcard_id_chars = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F');
/**
* CardDAV server connection (curl handle)
*
* @var resource
*/
private $curl;
/**
* Debug on or off
*
* @var boolean
*/
private $debug = false;
/**
* All available debug information
*
* @var array
*/
private $debug_information = array();
/**
* Exception codes
*/
const EXCEPTION_WRONG_HTTP_STATUS_CODE_GET = 1000;
const EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_VCARD = 1001;
const EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_XML_VCARD = 1002;
const EXCEPTION_WRONG_HTTP_STATUS_CODE_DELETE = 1003;
const EXCEPTION_WRONG_HTTP_STATUS_CODE_ADD = 1004;
const EXCEPTION_WRONG_HTTP_STATUS_CODE_UPDATE = 1005;
const EXCEPTION_MALFORMED_XML_RESPONSE = 1006;
const EXCEPTION_COULD_NOT_GENERATE_NEW_VCARD_ID = 1007;
/**
* Constructor
* Sets the CardDAV server url
*
* @param string $url CardDAV server url
*/
public function __construct($url = null)
{
if ($url !== null)
{
$this->set_url($url);
}
}
/**
* Sets debug information
*
* @param array $debug_information Debug information
* @return void
*/
public function set_debug(array $debug_information)
{
$this->debug_information[] = $debug_information;
}
/**
* Sets the CardDAV server url
*
* @param string $url CardDAV server url
* @return void
*/
public function set_url($url)
{
$this->url = $url;
if (substr($this->url, -1, 1) !== '/')
{
$this->url = $this->url . '/';
}
$this->url_parts = parse_url($this->url);
}
/**
* Sets authentication information
*
* @param string $username CardDAV server username
* @param string $password CardDAV server password
* @return void
*/
public function set_auth($username, $password)
{
$this->username = $username;
$this->password = $password;
$this->auth = $username . ':' . $password;
}
/**
* Gets all available debug information
*
* @return array $this->debug_information All available debug information
*/
public function get_debug()
{
return $this->debug_information;
}
/**
* Gets all vCards including additional information from the CardDAV server
*
* @param boolean $include_vcards Include vCards within the response (simplified only)
* @param boolean $raw Get response raw or simplified
* @return string Raw or simplified XML response
*/
public function get($include_vcards = true, $raw = false)
{
$result = $this->query($this->url, 'PROPFIND');
switch ($result['http_code'])
{
case 200:
case 207:
if ($raw === true)
{
return $result['response'];
}
else
{
return $this->simplify($result['response'], $include_vcards);
}
break;
default:
throw new Exception('Woops, something\'s gone wrong! The CardDAV server returned the http status code ' . $result['http_code'] . '.', self::EXCEPTION_WRONG_HTTP_STATUS_CODE_GET);
break;
}
}
/**
* Gets a clean vCard from the CardDAV server
*
* @param string $vcard_id vCard id on the CardDAV server
* @return string vCard (text/vcard)
*/
public function get_vcard($vcard_id)
{
$vcard_id = str_replace('.vcf', null, $vcard_id);
$result = $this->query($this->url . $vcard_id . '.vcf', 'GET');
switch ($result['http_code'])
{
case 200:
case 207:
return $result['response'];
break;
default:
throw new Exception('Woops, something\'s gone wrong! The CardDAV server returned the http status code ' . $result['http_code'] . '.', self::EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_VCARD);
break;
}
}
/**
* Gets a vCard + XML from the CardDAV Server
*
* @param string $vcard_id vCard id on the CardDAV Server
* @return string Raw or simplified vCard (text/xml)
*/
public function get_xml_vcard($vcard_id)
{
$vcard_id = str_replace('.vcf', null, $vcard_id);
$xml = new XMLWriter();
$xml->openMemory();
$xml->setIndent(4);
$xml->startDocument('1.0', 'utf-8');
$xml->startElement('C:addressbook-multiget');
$xml->writeAttribute('xmlns:D', 'DAV:');
$xml->writeAttribute('xmlns:C', 'urn:ietf:params:xml:ns:carddav');
$xml->startElement('D:prop');
$xml->writeElement('D:getetag');
$xml->writeElement('D:getlastmodified');
$xml->endElement();
$xml->writeElement('D:href', $this->url_parts['path'] . $vcard_id . '.vcf');
$xml->endElement();
$xml->endDocument();
$result = $this->query($this->url, 'REPORT', $xml->outputMemory(), 'text/xml');
switch ($result['http_code'])
{
case 200:
case 207:
return $this->simplify($result['response'], true);
break;
default:
throw new Exception('Woops, something\'s gone wrong! The CardDAV server returned the http status code ' . $result['http_code'] . '.', self::EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_XML_VCARD);
break;
}
}
/**
* Enables the debug mode
*
* @return void
*/
public function enable_debug()
{
$this->debug = true;
}
/**
* Checks if the CardDAV server is reachable
*
* @return boolean
*/
public function check_connection()
{
$result = $this->query($this->url, 'OPTIONS');
if ($result['http_code'] === 200)
{
return true;
}
else
{
return false;
}
}
/**
* Cleans the vCard
*
* @param string $vcard vCard
* @return string $vcard vCard
*/
private function clean_vcard($vcard)
{
$vcard = str_replace("\t", null, $vcard);
return $vcard;
}
/**
* Deletes an entry from the CardDAV server
*
* @param string $vcard_id vCard id on the CardDAV server
* @return boolean
*/
public function delete($vcard_id)
{
$result = $this->query($this->url . $vcard_id . '.vcf', 'DELETE');
switch ($result['http_code'])
{
case 204:
return true;
break;
default:
throw new Exception('Woops, something\'s gone wrong! The CardDAV server returned the http status code ' . $result['http_code'] . '.', self::EXCEPTION_WRONG_HTTP_STATUS_CODE_DELETE);
break;
}
}
/**
* Adds an entry to the CardDAV server
*
* @param string $vcard vCard
* @param string $vcard_id vCard id on the CardDAV server
* @return string The new vCard id
*/
public function add($vcard, $vcard_id = null)
{
if ($vcard_id === null)
{
$vcard_id = $this->generate_vcard_id();
}
$vcard = $this->clean_vcard($vcard);
$result = $this->query($this->url . $vcard_id . '.vcf', 'PUT', $vcard, 'text/vcard');
switch($result['http_code'])
{
case 201:
return $vcard_id;
break;
default:
throw new Exception('Woops, something\'s gone wrong! The CardDAV server returned the http status code ' . $result['http_code'] . '.', self::EXCEPTION_WRONG_HTTP_STATUS_CODE_ADD);
break;
}
}
/**
* Updates an entry to the CardDAV server
*
* @param string $vcard vCard
* @param string $vcard_id vCard id on the CardDAV server
* @return boolean
*/
public function update($vcard, $vcard_id)
{
try
{
return $this->add($vcard, $vcard_id);
}
catch (Exception $e)
{
throw new Exception($e->getMessage(), self::EXCEPTION_WRONG_HTTP_STATUS_CODE_UPDATE);
}
}
/**
* Simplify CardDAV XML response
*
* @param string $response CardDAV XML response
* @param boolean $include_vcards Include vCards or not
* @return string Simplified CardDAV XML response
*/
private function simplify($response, $include_vcards = true)
{
$response = $this->clean_response($response);
try
{
$xml = new SimpleXMLElement($response);
}
catch(Exception $e)
{
throw new Exception('The XML response seems to be malformed and can\'t be simplified!', self::EXCEPTION_MALFORMED_XML_RESPONSE, $e);
}
$simplified_xml = new XMLWriter();
$simplified_xml->openMemory();
$simplified_xml->setIndent(4);
$simplified_xml->startDocument('1.0', 'utf-8');
$simplified_xml->startElement('response');
if (!empty($xml->response))
{
foreach ($xml->response as $response)
{
if (preg_match('/vcard/', $response->propstat->prop->getcontenttype) || preg_match('/vcf/', $response->href))
{
$id = basename($response->href);
$id = str_replace('.vcf', null, $id);
if (!empty($id))
{
$simplified_xml->startElement('element');
$simplified_xml->writeElement('id', $id);
$simplified_xml->writeElement('etag', str_replace('"', null, $response->propstat->prop->getetag));
$simplified_xml->writeElement('last_modified', $response->propstat->prop->getlastmodified);
if ($include_vcards === true)
{
$simplified_xml->writeElement('vcard', $this->get_vcard($id));
}
$simplified_xml->endElement();
}
}
else if (preg_match('/unix-directory/', $response->propstat->prop->getcontenttype))
{
if (isset($response->propstat->prop->href))
{
$href = $response->propstat->prop->href;
}
else if (isset($response->href))
{
$href = $response->href;
}
else
{
$href = null;
}
$url = str_replace($this->url_parts['path'], null, $this->url) . $href;
$simplified_xml->startElement('addressbook_element');
$simplified_xml->writeElement('display_name', $response->propstat->prop->displayname);
$simplified_xml->writeElement('url', $url);
$simplified_xml->writeElement('last_modified', $response->propstat->prop->getlastmodified);
$simplified_xml->endElement();
}
}
}
$simplified_xml->endElement();
$simplified_xml->endDocument();
return $simplified_xml->outputMemory();
}
/**
* Cleans CardDAV XML response
*
* @param string $response CardDAV XML response
* @return string $response Cleaned CardDAV XML response
*/
private function clean_response($response)
{
$response = utf8_encode($response);
$response = str_replace('D:', null, $response);
$response = str_replace('d:', null, $response);
$response = str_replace('C:', null, $response);
$response = str_replace('c:', null, $response);
return $response;
}
/**
* Curl initialization
*
* @return void
*/
public function curl_init()
{
if (empty($this->curl))
{
$this->curl = curl_init();
curl_setopt($this->curl, CURLOPT_HEADER, true);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl, CURLOPT_USERAGENT, self::USERAGENT.self::VERSION);
if ($this->auth !== null)
{
curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($this->curl, CURLOPT_USERPWD, $this->auth);
}
}
}
/**
* Query the CardDAV server via curl and returns the response
*
* @param string $url CardDAV server URL
* @param string $method HTTP method like (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, COPY, MOVE)
* @param string $content Content for CardDAV queries
* @param string $content_type Set content type
* @return array Raw CardDAV Response and http status code
*/
private function query($url, $method, $content = null, $content_type = null)
{
$this->curl_init();
curl_setopt($this->curl, CURLOPT_URL, $url);
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $method);
if ($content !== null)
{
curl_setopt($this->curl, CURLOPT_POST, true);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $content);
}
else
{
curl_setopt($this->curl, CURLOPT_POST, false);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, null);
}
if ($content_type !== null)
{
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Content-type: '.$content_type));
}
else
{
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array());
}
$complete_response = curl_exec($this->curl);
$header_size = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE);
$http_code = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
$header = trim(substr($complete_response, 0, $header_size));
$response = substr($complete_response, $header_size);
$return = array(
'response' => $response,
'http_code' => $http_code
);
if ($this->debug === true)
{
$debug = $return;
$debug['url'] = $url;
$debug['method'] = $method;
$debug['content'] = $content;
$debug['content_type'] = $content_type;
$debug['header'] = $header;
$this->set_debug($debug);
}
return $return;
}
/**
* Returns a valid and unused vCard id
*
* @return string $vcard_id Valid vCard id
*/
private function generate_vcard_id()
{
$vcard_id = null;
for ($number = 0; $number <= 25; $number ++)
{
if ($number == 8 || $number == 17)
{
$vcard_id .= '-';
}
else
{
$vcard_id .= $this->vcard_id_chars[mt_rand(0, (count($this->vcard_id_chars) - 1))];
}
}
try
{
$carddav = new carddav_backend($this->url);
$carddav->set_auth($this->username, $this->password);
$result = $carddav->query($this->url . $vcard_id . '.vcf', 'GET');
if ($result['http_code'] !== 404)
{
$vcard_id = $this->generate_vcard_id();
}
return $vcard_id;
}
catch (Exception $e)
{
throw new Exception($e->getMessage(), self::EXCEPTION_COULD_NOT_GENERATE_NEW_VCARD_ID);
}
}
/**
* Destructor
* Close curl connection if it's open
*
* @return void
*/
public function __destruct()
{
if (!empty($this->curl))
{
curl_close($this->curl);
}
}
}