6 * The CardDAV plugin adds CardDAV functionality to the WebDAV server
10 * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
11 * @author Evert Pot (http://www.rooftopsolutions.nl/)
12 * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
14 class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin {
17 * Url to the addressbooks
19 const ADDRESSBOOK_ROOT = 'addressbooks';
22 * xml namespace for CardDAV elements
24 const NS_CARDDAV = 'urn:ietf:params:xml:ns:carddav';
27 * Add urls to this property to have them automatically exposed as
28 * 'directories' to the user.
32 public $directories = array();
37 * @var Sabre_DAV_Server
42 * Initializes the plugin
44 * @param Sabre_DAV_Server $server
47 public function initialize(Sabre_DAV_Server $server) {
50 $server->subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties'));
51 $server->subscribeEvent('afterGetProperties', array($this, 'afterGetProperties'));
52 $server->subscribeEvent('updateProperties', array($this, 'updateProperties'));
53 $server->subscribeEvent('report', array($this,'report'));
54 $server->subscribeEvent('onHTMLActionsPanel', array($this,'htmlActionsPanel'));
55 $server->subscribeEvent('onBrowserPostAction', array($this,'browserPostAction'));
56 $server->subscribeEvent('beforeWriteContent', array($this, 'beforeWriteContent'));
57 $server->subscribeEvent('beforeCreateFile', array($this, 'beforeCreateFile'));
60 $server->xmlNamespaces[self::NS_CARDDAV] = 'card';
62 /* Mapping Interfaces to {DAV:}resourcetype values */
63 $server->resourceTypeMapping['Sabre_CardDAV_IAddressBook'] = '{' . self::NS_CARDDAV . '}addressbook';
64 $server->resourceTypeMapping['Sabre_CardDAV_IDirectory'] = '{' . self::NS_CARDDAV . '}directory';
66 /* Adding properties that may never be changed */
67 $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-address-data';
68 $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}max-resource-size';
69 $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}addressbook-home-set';
70 $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-collation-set';
72 $server->propertyMap['{http://calendarserver.org/ns/}me-card'] = 'Sabre_DAV_Property_Href';
74 $this->server = $server;
79 * Returns a list of supported features.
81 * This is used in the DAV: header in the OPTIONS and PROPFIND requests.
85 public function getFeatures() {
87 return array('addressbook');
92 * Returns a list of reports this plugin supports.
94 * This will be used in the {DAV:}supported-report-set property.
95 * Note that you still need to subscribe to the 'report' event to actually
101 public function getSupportedReportSet($uri) {
103 $node = $this->server->tree->getNodeForPath($uri);
104 if ($node instanceof Sabre_CardDAV_IAddressBook || $node instanceof Sabre_CardDAV_ICard) {
106 '{' . self::NS_CARDDAV . '}addressbook-multiget',
107 '{' . self::NS_CARDDAV . '}addressbook-query',
116 * Adds all CardDAV-specific properties
118 * @param string $path
119 * @param Sabre_DAV_INode $node
120 * @param array $requestedProperties
121 * @param array $returnedProperties
124 public function beforeGetProperties($path, Sabre_DAV_INode $node, array &$requestedProperties, array &$returnedProperties) {
126 if ($node instanceof Sabre_DAVACL_IPrincipal) {
128 // calendar-home-set property
129 $addHome = '{' . self::NS_CARDDAV . '}addressbook-home-set';
130 if (in_array($addHome,$requestedProperties)) {
131 $principalId = $node->getName();
132 $addressbookHomePath = self::ADDRESSBOOK_ROOT . '/' . $principalId . '/';
133 unset($requestedProperties[array_search($addHome, $requestedProperties)]);
134 $returnedProperties[200][$addHome] = new Sabre_DAV_Property_Href($addressbookHomePath);
137 $directories = '{' . self::NS_CARDDAV . '}directory-gateway';
138 if ($this->directories && in_array($directories, $requestedProperties)) {
139 unset($requestedProperties[array_search($directories, $requestedProperties)]);
140 $returnedProperties[200][$directories] = new Sabre_DAV_Property_HrefList($this->directories);
145 if ($node instanceof Sabre_CardDAV_ICard) {
147 // The address-data property is not supposed to be a 'real'
148 // property, but in large chunks of the spec it does act as such.
149 // Therefore we simply expose it as a property.
150 $addressDataProp = '{' . self::NS_CARDDAV . '}address-data';
151 if (in_array($addressDataProp, $requestedProperties)) {
152 unset($requestedProperties[$addressDataProp]);
154 if (is_resource($val))
155 $val = stream_get_contents($val);
157 // Taking out \r to not screw up the xml output
158 $returnedProperties[200][$addressDataProp] = str_replace("\r","", $val);
163 if ($node instanceof Sabre_CardDAV_UserAddressBooks) {
165 $meCardProp = '{http://calendarserver.org/ns/}me-card';
166 if (in_array($meCardProp, $requestedProperties)) {
168 $props = $this->server->getProperties($node->getOwner(), array('{http://sabredav.org/ns}vcard-url'));
169 if (isset($props['{http://sabredav.org/ns}vcard-url'])) {
171 $returnedProperties[200][$meCardProp] = new Sabre_DAV_Property_Href(
172 $props['{http://sabredav.org/ns}vcard-url']
174 $pos = array_search($meCardProp, $requestedProperties);
175 unset($requestedProperties[$pos]);
186 * This event is triggered when a PROPPATCH method is executed
188 * @param array $mutations
189 * @param array $result
190 * @param Sabre_DAV_INode $node
193 public function updateProperties(&$mutations, &$result, $node) {
195 if (!$node instanceof Sabre_CardDAV_UserAddressBooks) {
199 $meCard = '{http://calendarserver.org/ns/}me-card';
201 // The only property we care about
202 if (!isset($mutations[$meCard]))
205 $value = $mutations[$meCard];
206 unset($mutations[$meCard]);
208 if ($value instanceof Sabre_DAV_Property_IHref) {
209 $value = $value->getHref();
210 $value = $this->server->calculateUri($value);
211 } elseif (!is_null($value)) {
212 $result[400][$meCard] = null;
216 $innerResult = $this->server->updateProperties(
219 '{http://sabredav.org/ns}vcard-url' => $value,
223 $closureResult = false;
224 foreach($innerResult as $status => $props) {
225 if (is_array($props) && array_key_exists('{http://sabredav.org/ns}vcard-url', $props)) {
226 $result[$status][$meCard] = null;
227 $closureResult = ($status>=200 && $status<300);
237 * This functions handles REPORT requests specific to CardDAV
239 * @param string $reportName
240 * @param DOMNode $dom
243 public function report($reportName,$dom) {
245 switch($reportName) {
246 case '{'.self::NS_CARDDAV.'}addressbook-multiget' :
247 $this->addressbookMultiGetReport($dom);
249 case '{'.self::NS_CARDDAV.'}addressbook-query' :
250 $this->addressBookQueryReport($dom);
261 * This function handles the addressbook-multiget REPORT.
263 * This report is used by the client to fetch the content of a series
264 * of urls. Effectively avoiding a lot of redundant requests.
266 * @param DOMNode $dom
269 public function addressbookMultiGetReport($dom) {
271 $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild));
273 $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href');
274 $propertyList = array();
276 foreach($hrefElems as $elem) {
278 $uri = $this->server->calculateUri($elem->nodeValue);
279 list($propertyList[]) = $this->server->getPropertiesForPath($uri,$properties);
283 $this->server->httpResponse->sendStatus(207);
284 $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
285 $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList));
290 * This method is triggered before a file gets updated with new content.
292 * This plugin uses this method to ensure that Card nodes receive valid
295 * @param string $path
296 * @param Sabre_DAV_IFile $node
297 * @param resource $data
300 public function beforeWriteContent($path, Sabre_DAV_IFile $node, &$data) {
302 if (!$node instanceof Sabre_CardDAV_ICard)
305 $this->validateVCard($data);
310 * This method is triggered before a new file is created.
312 * This plugin uses this method to ensure that Card nodes receive valid
315 * @param string $path
316 * @param resource $data
317 * @param Sabre_DAV_ICollection $parentNode
320 public function beforeCreateFile($path, &$data, Sabre_DAV_ICollection $parentNode) {
322 if (!$parentNode instanceof Sabre_CardDAV_IAddressBook)
325 $this->validateVCard($data);
330 * Checks if the submitted iCalendar data is in fact, valid.
332 * An exception is thrown if it's not.
334 * @param resource|string $data
337 protected function validateVCard(&$data) {
339 // If it's a stream, we convert it to a string first.
340 if (is_resource($data)) {
341 $data = stream_get_contents($data);
344 // Converting the data to unicode, if needed.
345 $data = Sabre_DAV_StringUtil::ensureUTF8($data);
349 $vobj = Sabre_VObject_Reader::read($data);
351 } catch (Sabre_VObject_ParseException $e) {
353 throw new Sabre_DAV_Exception_UnsupportedMediaType('This resource only supports valid vcard data. Parse error: ' . $e->getMessage());
357 if ($vobj->name !== 'VCARD') {
358 throw new Sabre_DAV_Exception_UnsupportedMediaType('This collection can only support vcard objects.');
365 * This function handles the addressbook-query REPORT
367 * This report is used by the client to filter an addressbook based on a
370 * @param DOMNode $dom
373 protected function addressbookQueryReport($dom) {
375 $query = new Sabre_CardDAV_AddressBookQueryParser($dom);
378 $depth = $this->server->getHTTPDepth(0);
381 $candidateNodes = array(
382 $this->server->tree->getNodeForPath($this->server->getRequestUri())
385 $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri());
388 $validNodes = array();
389 foreach($candidateNodes as $node) {
391 if (!$node instanceof Sabre_CardDAV_ICard)
394 $blob = $node->get();
395 if (is_resource($blob)) {
396 $blob = stream_get_contents($blob);
399 if (!$this->validateFilters($blob, $query->filters, $query->test)) {
403 $validNodes[] = $node;
405 if ($query->limit && $query->limit <= count($validNodes)) {
406 // We hit the maximum number of items, we can stop now.
413 foreach($validNodes as $validNode) {
416 $href = $this->server->getRequestUri();
418 $href = $this->server->getRequestUri() . '/' . $validNode->getName();
421 list($result[]) = $this->server->getPropertiesForPath($href, $query->requestedProperties, 0);
425 $this->server->httpResponse->sendStatus(207);
426 $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
427 $this->server->httpResponse->sendBody($this->server->generateMultiStatus($result));
432 * Validates if a vcard makes it throught a list of filters.
434 * @param string $vcardData
435 * @param array $filters
436 * @param string $test anyof or allof (which means OR or AND)
439 public function validateFilters($vcardData, array $filters, $test) {
441 $vcard = Sabre_VObject_Reader::read($vcardData);
443 foreach($filters as $filter) {
445 $isDefined = isset($vcard->{$filter['name']});
446 if ($filter['is-not-defined']) {
452 } elseif ((!$filter['param-filters'] && !$filter['text-matches']) || !$isDefined) {
454 // We only need to check for existence
455 $success = $isDefined;
459 $vProperties = $vcard->select($filter['name']);
462 if ($filter['param-filters']) {
463 $results[] = $this->validateParamFilters($vProperties, $filter['param-filters'], $filter['test']);
465 if ($filter['text-matches']) {
467 foreach($vProperties as $vProperty)
468 $texts[] = $vProperty->value;
470 $results[] = $this->validateTextMatches($texts, $filter['text-matches'], $filter['test']);
473 if (count($results)===1) {
474 $success = $results[0];
476 if ($filter['test'] === 'anyof') {
477 $success = $results[0] || $results[1];
479 $success = $results[0] && $results[1];
485 // There are two conditions where we can already determine whether
486 // or not this filter succeeds.
487 if ($test==='anyof' && $success) {
490 if ($test==='allof' && !$success) {
496 // If we got all the way here, it means we haven't been able to
497 // determine early if the test failed or not.
499 // This implies for 'anyof' that the test failed, and for 'allof' that
500 // we succeeded. Sounds weird, but makes sense.
501 return $test==='allof';
506 * Validates if a param-filter can be applied to a specific property.
508 * @todo currently we're only validating the first parameter of the passed
509 * property. Any subsequence parameters with the same name are
511 * @param array $vProperties
512 * @param array $filters
513 * @param string $test
516 protected function validateParamFilters(array $vProperties, array $filters, $test) {
518 foreach($filters as $filter) {
521 foreach($vProperties as $vProperty) {
522 $isDefined = isset($vProperty[$filter['name']]);
523 if ($isDefined) break;
526 if ($filter['is-not-defined']) {
533 // If there's no text-match, we can just check for existence
534 } elseif (!$filter['text-match'] || !$isDefined) {
536 $success = $isDefined;
541 foreach($vProperties as $vProperty) {
542 // If we got all the way here, we'll need to validate the
543 // text-match filter.
544 $success = Sabre_DAV_StringUtil::textMatch($vProperty[$filter['name']]->value, $filter['text-match']['value'], $filter['text-match']['collation'], $filter['text-match']['match-type']);
547 if ($filter['text-match']['negate-condition']) {
548 $success = !$success;
553 // There are two conditions where we can already determine whether
554 // or not this filter succeeds.
555 if ($test==='anyof' && $success) {
558 if ($test==='allof' && !$success) {
564 // If we got all the way here, it means we haven't been able to
565 // determine early if the test failed or not.
567 // This implies for 'anyof' that the test failed, and for 'allof' that
568 // we succeeded. Sounds weird, but makes sense.
569 return $test==='allof';
574 * Validates if a text-filter can be applied to a specific property.
576 * @param array $texts
577 * @param array $filters
578 * @param string $test
581 protected function validateTextMatches(array $texts, array $filters, $test) {
583 foreach($filters as $filter) {
586 foreach($texts as $haystack) {
587 $success = Sabre_DAV_StringUtil::textMatch($haystack, $filter['value'], $filter['collation'], $filter['match-type']);
589 // Breaking on the first match
592 if ($filter['negate-condition']) {
593 $success = !$success;
596 if ($success && $test==='anyof')
599 if (!$success && $test=='allof')
605 // If we got all the way here, it means we haven't been able to
606 // determine early if the test failed or not.
608 // This implies for 'anyof' that the test failed, and for 'allof' that
609 // we succeeded. Sounds weird, but makes sense.
610 return $test==='allof';
615 * This event is triggered after webdav-properties have been retrieved.
619 public function afterGetProperties($uri, &$properties) {
621 // If the request was made using the SOGO connector, we must rewrite
622 // the content-type property. By default SabreDAV will send back
623 // text/x-vcard; charset=utf-8, but for SOGO we must strip that last
625 if (!isset($properties[200]['{DAV:}getcontenttype']))
628 if (strpos($this->server->httpRequest->getHeader('User-Agent'),'Thunderbird')===false) {
632 if (strpos($properties[200]['{DAV:}getcontenttype'],'text/x-vcard')===0) {
633 $properties[200]['{DAV:}getcontenttype'] = 'text/x-vcard';
639 * This method is used to generate HTML output for the
640 * Sabre_DAV_Browser_Plugin. This allows us to generate an interface users
641 * can use to create new calendars.
643 * @param Sabre_DAV_INode $node
644 * @param string $output
647 public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) {
649 if (!$node instanceof Sabre_CardDAV_UserAddressBooks)
652 $output.= '<tr><td colspan="2"><form method="post" action="">
653 <h3>Create new address book</h3>
654 <input type="hidden" name="sabreAction" value="mkaddressbook" />
655 <label>Name (uri):</label> <input type="text" name="name" /><br />
656 <label>Display name:</label> <input type="text" name="{DAV:}displayname" /><br />
657 <input type="submit" value="create" />
666 * This method allows us to intercept the 'mkcalendar' sabreAction. This
667 * action enables the user to create new calendars from the browser plugin.
670 * @param string $action
671 * @param array $postVars
674 public function browserPostAction($uri, $action, array $postVars) {
676 if ($action!=='mkaddressbook')
679 $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:carddav}addressbook');
680 $properties = array();
681 if (isset($postVars['{DAV:}displayname'])) {
682 $properties['{DAV:}displayname'] = $postVars['{DAV:}displayname'];
684 $this->server->createCollection($uri . '/' . $postVars['name'],$resourceType,$properties);