8 * This backend is used to store calendar-data in a PDO database, such as
13 * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
14 * @author Evert Pot (http://www.rooftopsolutions.nl/)
15 * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
17 class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract {
20 * We need to specify a max date, because we need to stop *somewhere*
22 * On 32 bit system the maximum for a signed integer is 2147483647, so
23 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
24 * in 2038-01-19 to avoid problems when the date is converted
25 * to a unix timestamp.
27 const MAX_DATE = '2038-01-01';
37 * The table name that will be used for calendars
41 protected $calendarTableName;
44 * The table name that will be used for calendar objects
48 protected $calendarObjectTableName;
51 * List of CalDAV properties, and how they map to database fieldnames
53 * Add your own properties by simply adding on to this array
57 public $propertyMap = array(
58 '{DAV:}displayname' => 'displayname',
59 '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
60 '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
61 '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
62 '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
69 * @param string $calendarTableName
70 * @param string $calendarObjectTableName
72 public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') {
75 $this->calendarTableName = $calendarTableName;
76 $this->calendarObjectTableName = $calendarObjectTableName;
81 * Returns a list of calendars for a principal.
83 * Every project is an array with the following keys:
84 * * id, a unique id that will be used by other functions to modify the
85 * calendar. This can be the same as the uri or a database key.
86 * * uri, which the basename of the uri with which the calendar is
88 * * principaluri. The owner of the calendar. Almost always the same as
89 * principalUri passed to this method.
91 * Furthermore it can contain webdav properties in clark notation. A very
92 * common one is '{DAV:}displayname'.
94 * @param string $principalUri
97 public function getCalendarsForUser($principalUri) {
99 $fields = array_values($this->propertyMap);
103 $fields[] = 'components';
104 $fields[] = 'principaluri';
106 // Making fields a comma-delimited list
107 $fields = implode(', ', $fields);
108 $stmt = $this->pdo->prepare("SELECT " . $fields . " FROM ".$this->calendarTableName." WHERE principaluri = ? ORDER BY calendarorder ASC");
109 $stmt->execute(array($principalUri));
111 $calendars = array();
112 while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
114 $components = array();
115 if ($row['components']) {
116 $components = explode(',',$row['components']);
121 'uri' => $row['uri'],
122 'principaluri' => $row['principaluri'],
123 '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag']?$row['ctag']:'0',
124 '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components),
128 foreach($this->propertyMap as $xmlName=>$dbName) {
129 $calendar[$xmlName] = $row[$dbName];
132 $calendars[] = $calendar;
141 * Creates a new calendar for a principal.
143 * If the creation was a success, an id must be returned that can be used to reference
144 * this calendar in other methods, such as updateCalendar
146 * @param string $principalUri
147 * @param string $calendarUri
148 * @param array $properties
151 public function createCalendar($principalUri, $calendarUri, array $properties) {
159 ':principaluri' => $principalUri,
160 ':uri' => $calendarUri,
165 $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
166 $fieldNames[] = 'components';
167 if (!isset($properties[$sccs])) {
168 $values[':components'] = 'VEVENT,VTODO';
170 if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) {
171 throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet');
173 $values[':components'] = implode(',',$properties[$sccs]->getValue());
176 foreach($this->propertyMap as $xmlName=>$dbName) {
177 if (isset($properties[$xmlName])) {
179 $values[':' . $dbName] = $properties[$xmlName];
180 $fieldNames[] = $dbName;
184 $stmt = $this->pdo->prepare("INSERT INTO ".$this->calendarTableName." (".implode(', ', $fieldNames).") VALUES (".implode(', ',array_keys($values)).")");
185 $stmt->execute($values);
187 return $this->pdo->lastInsertId();
192 * Updates properties for a calendar.
194 * The mutations array uses the propertyName in clark-notation as key,
195 * and the array value for the property value. In the case a property
196 * should be deleted, the property value will be null.
198 * This method must be atomic. If one property cannot be changed, the
199 * entire operation must fail.
201 * If the operation was successful, true can be returned.
202 * If the operation failed, false can be returned.
204 * Deletion of a non-existent property is always successful.
206 * Lastly, it is optional to return detailed information about any
207 * failures. In this case an array should be returned with the following
212 * '{DAV:}displayname' => null,
215 * '{DAV:}owner' => null,
219 * In this example it was forbidden to update {DAV:}displayname.
220 * (403 Forbidden), which in turn also caused {DAV:}owner to fail
221 * (424 Failed Dependency) because the request needs to be atomic.
223 * @param string $calendarId
224 * @param array $mutations
227 public function updateCalendar($calendarId, array $mutations) {
229 $newValues = array();
231 200 => array(), // Ok
232 403 => array(), // Forbidden
233 424 => array(), // Failed Dependency
238 foreach($mutations as $propertyName=>$propertyValue) {
240 // We don't know about this property.
241 if (!isset($this->propertyMap[$propertyName])) {
243 $result[403][$propertyName] = null;
244 unset($mutations[$propertyName]);
248 $fieldName = $this->propertyMap[$propertyName];
249 $newValues[$fieldName] = $propertyValue;
253 // If there were any errors we need to fail the request
255 // Properties has the remaining properties
256 foreach($mutations as $propertyName=>$propertyValue) {
257 $result[424][$propertyName] = null;
260 // Removing unused statuscodes for cleanliness
261 foreach($result as $status=>$properties) {
262 if (is_array($properties) && count($properties)===0) unset($result[$status]);
271 // Now we're generating the sql query.
272 $valuesSql = array();
273 foreach($newValues as $fieldName=>$value) {
274 $valuesSql[] = $fieldName . ' = ?';
276 $valuesSql[] = 'ctag = ctag + 1';
278 $stmt = $this->pdo->prepare("UPDATE " . $this->calendarTableName . " SET " . implode(', ',$valuesSql) . " WHERE id = ?");
279 $newValues['id'] = $calendarId;
280 $stmt->execute(array_values($newValues));
287 * Delete a calendar and all it's objects
289 * @param string $calendarId
292 public function deleteCalendar($calendarId) {
294 $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?');
295 $stmt->execute(array($calendarId));
297 $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarTableName.' WHERE id = ?');
298 $stmt->execute(array($calendarId));
303 * Returns all calendar objects within a calendar.
305 * Every item contains an array with the following keys:
306 * * id - unique identifier which will be used for subsequent updates
307 * * calendardata - The iCalendar-compatible calendar data
308 * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string.
309 * * lastmodified - a timestamp of the last modification time
310 * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
312 * * calendarid - The calendarid as it was passed to this function.
313 * * size - The size of the calendar objects, in bytes.
315 * Note that the etag is optional, but it's highly encouraged to return for
318 * The calendardata is also optional. If it's not returned
319 * 'getCalendarObject' will be called later, which *is* expected to return
322 * If neither etag or size are specified, the calendardata will be
323 * used/fetched to determine these numbers. If both are specified the
324 * amount of times this is needed is reduced by a great degree.
326 * @param string $calendarId
329 public function getCalendarObjects($calendarId) {
331 $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?');
332 $stmt->execute(array($calendarId));
335 foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
338 'uri' => $row['uri'],
339 'lastmodified' => $row['lastmodified'],
340 'etag' => '"' . $row['etag'] . '"',
341 'calendarid' => $row['calendarid'],
342 'size' => (int)$row['size'],
351 * Returns information from a single calendar object, based on it's object
354 * The returned array must have the same keys as getCalendarObjects. The
355 * 'calendardata' object is required here though, while it's not required
356 * for getCalendarObjects.
358 * @param string $calendarId
359 * @param string $objectUri
362 public function getCalendarObject($calendarId,$objectUri) {
364 $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size, calendardata FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?');
365 $stmt->execute(array($calendarId, $objectUri));
366 $row = $stmt->fetch(\PDO::FETCH_ASSOC);
368 if(!$row) return null;
372 'uri' => $row['uri'],
373 'lastmodified' => $row['lastmodified'],
374 'etag' => '"' . $row['etag'] . '"',
375 'calendarid' => $row['calendarid'],
376 'size' => (int)$row['size'],
377 'calendardata' => $row['calendardata'],
384 * Creates a new calendar object.
386 * It is possible return an etag from this function, which will be used in
387 * the response to this PUT request. Note that the ETag must be surrounded
390 * However, you should only really return this ETag if you don't mangle the
391 * calendar-data. If the result of a subsequent GET to this object is not
392 * the exact same as this request body, you should omit the ETag.
394 * @param mixed $calendarId
395 * @param string $objectUri
396 * @param string $calendarData
397 * @return string|null
399 public function createCalendarObject($calendarId,$objectUri,$calendarData) {
401 $extraData = $this->getDenormalizedData($calendarData);
403 $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarObjectTableName.' (calendarid, uri, calendardata, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence) VALUES (?,?,?,?,?,?,?,?,?)');
404 $stmt->execute(array(
411 $extraData['componentType'],
412 $extraData['firstOccurence'],
413 $extraData['lastOccurence'],
415 $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?');
416 $stmt->execute(array($calendarId));
418 return '"' . $extraData['etag'] . '"';
423 * Updates an existing calendarobject, based on it's uri.
425 * It is possible return an etag from this function, which will be used in
426 * the response to this PUT request. Note that the ETag must be surrounded
429 * However, you should only really return this ETag if you don't mangle the
430 * calendar-data. If the result of a subsequent GET to this object is not
431 * the exact same as this request body, you should omit the ETag.
433 * @param mixed $calendarId
434 * @param string $objectUri
435 * @param string $calendarData
436 * @return string|null
438 public function updateCalendarObject($calendarId,$objectUri,$calendarData) {
440 $extraData = $this->getDenormalizedData($calendarData);
442 $stmt = $this->pdo->prepare('UPDATE '.$this->calendarObjectTableName.' SET calendardata = ?, lastmodified = ?, etag = ?, size = ?, componenttype = ?, firstoccurence = ?, lastoccurence = ? WHERE calendarid = ? AND uri = ?');
443 $stmt->execute(array($calendarData,time(), $extraData['etag'], $extraData['size'], $extraData['componentType'], $extraData['firstOccurence'], $extraData['lastOccurence'] ,$calendarId,$objectUri));
444 $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?');
445 $stmt->execute(array($calendarId));
447 return '"' . $extraData['etag'] . '"';
452 * Parses some information from calendar objects, used for optimized
455 * Returns an array with the following keys:
462 * @param string $calendarData
465 protected function getDenormalizedData($calendarData) {
467 $vObject = VObject\Reader::read($calendarData);
468 $componentType = null;
470 $firstOccurence = null;
471 $lastOccurence = null;
472 foreach($vObject->getComponents() as $component) {
473 if ($component->name!=='VTIMEZONE') {
474 $componentType = $component->name;
478 if (!$componentType) {
479 throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
481 if ($componentType === 'VEVENT') {
482 $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
483 // Finding the last occurence is a bit harder
484 if (!isset($component->RRULE)) {
485 if (isset($component->DTEND)) {
486 $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
487 } elseif (isset($component->DURATION)) {
488 $endDate = clone $component->DTSTART->getDateTime();
489 $endDate->add(VObject\DateTimeParser::parse($component->DURATION->value));
490 $lastOccurence = $endDate->getTimeStamp();
491 } elseif ($component->DTSTART->getDateType()===VObject\Property\DateTime::DATE) {
492 $endDate = clone $component->DTSTART->getDateTime();
493 $endDate->modify('+1 day');
494 $lastOccurence = $endDate->getTimeStamp();
496 $lastOccurence = $firstOccurence;
499 $it = new VObject\RecurrenceIterator($vObject, (string)$component->UID);
500 $maxDate = new DateTime(self::MAX_DATE);
501 if ($it->isInfinite()) {
502 $lastOccurence = $maxDate->getTimeStamp();
504 $end = $it->getDtEnd();
505 while($it->valid() && $end < $maxDate) {
506 $end = $it->getDtEnd();
510 $lastOccurence = $end->getTimeStamp();
517 'etag' => md5($calendarData),
518 'size' => strlen($calendarData),
519 'componentType' => $componentType,
520 'firstOccurence' => $firstOccurence,
521 'lastOccurence' => $lastOccurence,
527 * Deletes an existing calendar object.
529 * @param string $calendarId
530 * @param string $objectUri
533 public function deleteCalendarObject($calendarId,$objectUri) {
535 $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?');
536 $stmt->execute(array($calendarId,$objectUri));
537 $stmt = $this->pdo->prepare('UPDATE '. $this->calendarTableName .' SET ctag = ctag + 1 WHERE id = ?');
538 $stmt->execute(array($calendarId));
543 * Performs a calendar-query on the contents of this calendar.
545 * The calendar-query is defined in RFC4791 : CalDAV. Using the
546 * calendar-query it is possible for a client to request a specific set of
547 * object, based on contents of iCalendar properties, date-ranges and
548 * iCalendar component types (VTODO, VEVENT).
550 * This method should just return a list of (relative) urls that match this
553 * The list of filters are specified as an array. The exact array is
554 * documented by Sabre_CalDAV_CalendarQueryParser.
556 * Note that it is extremely likely that getCalendarObject for every path
557 * returned from this method will be called almost immediately after. You
558 * may want to anticipate this to speed up these requests.
560 * This method provides a default implementation, which parses *all* the
561 * iCalendar objects in the specified calendar.
563 * This default may well be good enough for personal use, and calendars
564 * that aren't very large. But if you anticipate high usage, big calendars
565 * or high loads, you are strongly adviced to optimize certain paths.
567 * The best way to do so is override this method and to optimize
568 * specifically for 'common filters'.
570 * Requests that are extremely common are:
571 * * requests for just VEVENTS
572 * * requests for just VTODO
573 * * requests with a time-range-filter on a VEVENT.
575 * ..and combinations of these requests. It may not be worth it to try to
576 * handle every possible situation and just rely on the (relatively
577 * easy to use) CalendarQueryValidator to handle the rest.
579 * Note that especially time-range-filters may be difficult to parse. A
580 * time-range filter specified on a VEVENT must for instance also handle
581 * recurrence rules correctly.
582 * A good example of how to interprete all these filters can also simply
583 * be found in Sabre_CalDAV_CalendarQueryFilter. This class is as correct
584 * as possible, so it gives you a good idea on what type of stuff you need
587 * This specific implementation (for the PDO) backend optimizes filters on
588 * specific components, and VEVENT time-ranges.
590 * @param string $calendarId
591 * @param array $filters
594 public function calendarQuery($calendarId, array $filters) {
597 $validator = new Sabre_CalDAV_CalendarQueryValidator();
599 $componentType = null;
600 $requirePostFilter = true;
603 // if no filters were specified, we don't need to filter after a query
604 if (!$filters['prop-filters'] && !$filters['comp-filters']) {
605 $requirePostFilter = false;
608 // Figuring out if there's a component filter
609 if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
610 $componentType = $filters['comp-filters'][0]['name'];
612 // Checking if we need post-filters
613 if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
614 $requirePostFilter = false;
616 // There was a time-range filter
617 if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
618 $timeRange = $filters['comp-filters'][0]['time-range'];
623 if ($requirePostFilter) {
624 $query = "SELECT uri, calendardata FROM ".$this->calendarObjectTableName." WHERE calendarid = :calendarid";
626 $query = "SELECT uri FROM ".$this->calendarObjectTableName." WHERE calendarid = :calendarid";
630 'calendarid' => $calendarId,
633 if ($componentType) {
634 $query.=" AND componenttype = :componenttype";
635 $values['componenttype'] = $componentType;
638 if ($timeRange && $timeRange['start']) {
639 $query.=" AND lastoccurence > :startdate";
640 $values['startdate'] = $timeRange['start']->getTimeStamp();
642 if ($timeRange && $timeRange['end']) {
643 $query.=" AND firstoccurence < :enddate";
644 $values['enddate'] = $timeRange['end']->getTimeStamp();
647 $stmt = $this->pdo->prepare($query);
648 $stmt->execute($values);
651 while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
652 if ($requirePostFilter) {
653 if (!$this->validateFilterForObject($row, $filters)) {
657 $result[] = $row['uri'];