6 * This backend is used to store calendar-data in a PDO database, such as
11 * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
12 * @author Evert Pot (http://www.rooftopsolutions.nl/)
13 * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
15 class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract {
18 * We need to specify a max date, because we need to stop *somewhere*
20 const MAX_DATE = '2040-01-01';
30 * The table name that will be used for calendars
34 protected $calendarTableName;
37 * The table name that will be used for calendar objects
41 protected $calendarObjectTableName;
44 * List of CalDAV properties, and how they map to database fieldnames
46 * Add your own properties by simply adding on to this array
50 public $propertyMap = array(
51 '{DAV:}displayname' => 'displayname',
52 '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
53 '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
54 '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
55 '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
62 * @param string $calendarTableName
63 * @param string $calendarObjectTableName
65 public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') {
68 $this->calendarTableName = $calendarTableName;
69 $this->calendarObjectTableName = $calendarObjectTableName;
74 * Returns a list of calendars for a principal.
76 * Every project is an array with the following keys:
77 * * id, a unique id that will be used by other functions to modify the
78 * calendar. This can be the same as the uri or a database key.
79 * * uri, which the basename of the uri with which the calendar is
81 * * principaluri. The owner of the calendar. Almost always the same as
82 * principalUri passed to this method.
84 * Furthermore it can contain webdav properties in clark notation. A very
85 * common one is '{DAV:}displayname'.
87 * @param string $principalUri
90 public function getCalendarsForUser($principalUri) {
92 $fields = array_values($this->propertyMap);
96 $fields[] = 'components';
97 $fields[] = 'principaluri';
99 // Making fields a comma-delimited list
100 $fields = implode(', ', $fields);
101 $stmt = $this->pdo->prepare("SELECT " . $fields . " FROM ".$this->calendarTableName." WHERE principaluri = ? ORDER BY calendarorder ASC");
102 $stmt->execute(array($principalUri));
104 $calendars = array();
105 while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
107 $components = array();
108 if ($row['components']) {
109 $components = explode(',',$row['components']);
114 'uri' => $row['uri'],
115 'principaluri' => $row['principaluri'],
116 '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag']?$row['ctag']:'0',
117 '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components),
121 foreach($this->propertyMap as $xmlName=>$dbName) {
122 $calendar[$xmlName] = $row[$dbName];
125 $calendars[] = $calendar;
134 * Creates a new calendar for a principal.
136 * If the creation was a success, an id must be returned that can be used to reference
137 * this calendar in other methods, such as updateCalendar
139 * @param string $principalUri
140 * @param string $calendarUri
141 * @param array $properties
144 public function createCalendar($principalUri, $calendarUri, array $properties) {
152 ':principaluri' => $principalUri,
153 ':uri' => $calendarUri,
158 $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
159 $fieldNames[] = 'components';
160 if (!isset($properties[$sccs])) {
161 $values[':components'] = 'VEVENT,VTODO';
163 if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) {
164 throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet');
166 $values[':components'] = implode(',',$properties[$sccs]->getValue());
169 foreach($this->propertyMap as $xmlName=>$dbName) {
170 if (isset($properties[$xmlName])) {
172 $values[':' . $dbName] = $properties[$xmlName];
173 $fieldNames[] = $dbName;
177 $stmt = $this->pdo->prepare("INSERT INTO ".$this->calendarTableName." (".implode(', ', $fieldNames).") VALUES (".implode(', ',array_keys($values)).")");
178 $stmt->execute($values);
180 return $this->pdo->lastInsertId();
185 * Updates properties for a calendar.
187 * The mutations array uses the propertyName in clark-notation as key,
188 * and the array value for the property value. In the case a property
189 * should be deleted, the property value will be null.
191 * This method must be atomic. If one property cannot be changed, the
192 * entire operation must fail.
194 * If the operation was successful, true can be returned.
195 * If the operation failed, false can be returned.
197 * Deletion of a non-existent property is always successful.
199 * Lastly, it is optional to return detailed information about any
200 * failures. In this case an array should be returned with the following
205 * '{DAV:}displayname' => null,
208 * '{DAV:}owner' => null,
212 * In this example it was forbidden to update {DAV:}displayname.
213 * (403 Forbidden), which in turn also caused {DAV:}owner to fail
214 * (424 Failed Dependency) because the request needs to be atomic.
216 * @param string $calendarId
217 * @param array $mutations
220 public function updateCalendar($calendarId, array $mutations) {
222 $newValues = array();
224 200 => array(), // Ok
225 403 => array(), // Forbidden
226 424 => array(), // Failed Dependency
231 foreach($mutations as $propertyName=>$propertyValue) {
233 // We don't know about this property.
234 if (!isset($this->propertyMap[$propertyName])) {
236 $result[403][$propertyName] = null;
237 unset($mutations[$propertyName]);
241 $fieldName = $this->propertyMap[$propertyName];
242 $newValues[$fieldName] = $propertyValue;
246 // If there were any errors we need to fail the request
248 // Properties has the remaining properties
249 foreach($mutations as $propertyName=>$propertyValue) {
250 $result[424][$propertyName] = null;
253 // Removing unused statuscodes for cleanliness
254 foreach($result as $status=>$properties) {
255 if (is_array($properties) && count($properties)===0) unset($result[$status]);
264 // Now we're generating the sql query.
265 $valuesSql = array();
266 foreach($newValues as $fieldName=>$value) {
267 $valuesSql[] = $fieldName . ' = ?';
269 $valuesSql[] = 'ctag = ctag + 1';
271 $stmt = $this->pdo->prepare("UPDATE " . $this->calendarTableName . " SET " . implode(', ',$valuesSql) . " WHERE id = ?");
272 $newValues['id'] = $calendarId;
273 $stmt->execute(array_values($newValues));
280 * Delete a calendar and all it's objects
282 * @param string $calendarId
285 public function deleteCalendar($calendarId) {
287 $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?');
288 $stmt->execute(array($calendarId));
290 $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarTableName.' WHERE id = ?');
291 $stmt->execute(array($calendarId));
296 * Returns all calendar objects within a calendar.
298 * Every item contains an array with the following keys:
299 * * id - unique identifier which will be used for subsequent updates
300 * * calendardata - The iCalendar-compatible calendar data
301 * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string.
302 * * lastmodified - a timestamp of the last modification time
303 * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
305 * * calendarid - The calendarid as it was passed to this function.
306 * * size - The size of the calendar objects, in bytes.
308 * Note that the etag is optional, but it's highly encouraged to return for
311 * The calendardata is also optional. If it's not returned
312 * 'getCalendarObject' will be called later, which *is* expected to return
315 * If neither etag or size are specified, the calendardata will be
316 * used/fetched to determine these numbers. If both are specified the
317 * amount of times this is needed is reduced by a great degree.
319 * @param string $calendarId
322 public function getCalendarObjects($calendarId) {
324 $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?');
325 $stmt->execute(array($calendarId));
328 foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
331 'uri' => $row['uri'],
332 'lastmodified' => $row['lastmodified'],
333 'etag' => '"' . $row['etag'] . '"',
334 'calendarid' => $row['calendarid'],
335 'size' => (int)$row['size'],
344 * Returns information from a single calendar object, based on it's object
347 * The returned array must have the same keys as getCalendarObjects. The
348 * 'calendardata' object is required here though, while it's not required
349 * for getCalendarObjects.
351 * @param string $calendarId
352 * @param string $objectUri
355 public function getCalendarObject($calendarId,$objectUri) {
357 $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size, calendardata FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?');
358 $stmt->execute(array($calendarId, $objectUri));
359 $row = $stmt->fetch(\PDO::FETCH_ASSOC);
361 if(!$row) return null;
365 'uri' => $row['uri'],
366 'lastmodified' => $row['lastmodified'],
367 'etag' => '"' . $row['etag'] . '"',
368 'calendarid' => $row['calendarid'],
369 'size' => (int)$row['size'],
370 'calendardata' => $row['calendardata'],
377 * Creates a new calendar object.
379 * It is possible return an etag from this function, which will be used in
380 * the response to this PUT request. Note that the ETag must be surrounded
383 * However, you should only really return this ETag if you don't mangle the
384 * calendar-data. If the result of a subsequent GET to this object is not
385 * the exact same as this request body, you should omit the ETag.
387 * @param mixed $calendarId
388 * @param string $objectUri
389 * @param string $calendarData
390 * @return string|null
392 public function createCalendarObject($calendarId,$objectUri,$calendarData) {
394 $extraData = $this->getDenormalizedData($calendarData);
396 $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarObjectTableName.' (calendarid, uri, calendardata, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence) VALUES (?,?,?,?,?,?,?,?,?)');
397 $stmt->execute(array(
404 $extraData['componentType'],
405 $extraData['firstOccurence'],
406 $extraData['lastOccurence'],
408 $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?');
409 $stmt->execute(array($calendarId));
411 return '"' . $extraData['etag'] . '"';
416 * Updates an existing calendarobject, based on it's uri.
418 * It is possible return an etag from this function, which will be used in
419 * the response to this PUT request. Note that the ETag must be surrounded
422 * However, you should only really return this ETag if you don't mangle the
423 * calendar-data. If the result of a subsequent GET to this object is not
424 * the exact same as this request body, you should omit the ETag.
426 * @param mixed $calendarId
427 * @param string $objectUri
428 * @param string $calendarData
429 * @return string|null
431 public function updateCalendarObject($calendarId,$objectUri,$calendarData) {
433 $extraData = $this->getDenormalizedData($calendarData);
435 $stmt = $this->pdo->prepare('UPDATE '.$this->calendarObjectTableName.' SET calendardata = ?, lastmodified = ?, etag = ?, size = ?, componenttype = ?, firstoccurence = ?, lastoccurence = ? WHERE calendarid = ? AND uri = ?');
436 $stmt->execute(array($calendarData,time(), $extraData['etag'], $extraData['size'], $extraData['componentType'], $extraData['firstOccurence'], $extraData['lastOccurence'] ,$calendarId,$objectUri));
437 $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?');
438 $stmt->execute(array($calendarId));
440 return '"' . $extraData['etag'] . '"';
445 * Parses some information from calendar objects, used for optimized
448 * Returns an array with the following keys:
455 * @param string $calendarData
458 protected function getDenormalizedData($calendarData) {
460 $vObject = Sabre_VObject_Reader::read($calendarData);
461 $componentType = null;
463 $firstOccurence = null;
464 $lastOccurence = null;
465 foreach($vObject->getComponents() as $component) {
466 if ($component->name!=='VTIMEZONE') {
467 $componentType = $component->name;
471 if (!$componentType) {
472 throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
474 if ($componentType === 'VEVENT') {
475 $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
476 // Finding the last occurence is a bit harder
477 if (!isset($component->RRULE)) {
478 if (isset($component->DTEND)) {
479 $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
480 } elseif (isset($component->DURATION)) {
481 $endDate = clone $component->DTSTART->getDateTime();
482 $endDate->add(Sabre_VObject_DateTimeParser::parse($component->DURATION->value));
483 $lastOccurence = $endDate->getTimeStamp();
484 } elseif ($component->DTSTART->getDateType()===Sabre_VObject_Property_DateTime::DATE) {
485 $endDate = clone $component->DTSTART->getDateTime();
486 $endDate->modify('+1 day');
487 $lastOccurence = $endDate->getTimeStamp();
489 $lastOccurence = $firstOccurence;
492 $it = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->UID);
493 $maxDate = new DateTime(self::MAX_DATE);
494 if ($it->isInfinite()) {
495 $lastOccurence = $maxDate->getTimeStamp();
497 $end = $it->getDtEnd();
498 while($it->valid() && $end < $maxDate) {
499 $end = $it->getDtEnd();
503 $lastOccurence = $end->getTimeStamp();
510 'etag' => md5($calendarData),
511 'size' => strlen($calendarData),
512 'componentType' => $componentType,
513 'firstOccurence' => $firstOccurence,
514 'lastOccurence' => $lastOccurence,
520 * Deletes an existing calendar object.
522 * @param string $calendarId
523 * @param string $objectUri
526 public function deleteCalendarObject($calendarId,$objectUri) {
528 $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?');
529 $stmt->execute(array($calendarId,$objectUri));
530 $stmt = $this->pdo->prepare('UPDATE '. $this->calendarTableName .' SET ctag = ctag + 1 WHERE id = ?');
531 $stmt->execute(array($calendarId));
536 * Performs a calendar-query on the contents of this calendar.
538 * The calendar-query is defined in RFC4791 : CalDAV. Using the
539 * calendar-query it is possible for a client to request a specific set of
540 * object, based on contents of iCalendar properties, date-ranges and
541 * iCalendar component types (VTODO, VEVENT).
543 * This method should just return a list of (relative) urls that match this
546 * The list of filters are specified as an array. The exact array is
547 * documented by Sabre_CalDAV_CalendarQueryParser.
549 * Note that it is extremely likely that getCalendarObject for every path
550 * returned from this method will be called almost immediately after. You
551 * may want to anticipate this to speed up these requests.
553 * This method provides a default implementation, which parses *all* the
554 * iCalendar objects in the specified calendar.
556 * This default may well be good enough for personal use, and calendars
557 * that aren't very large. But if you anticipate high usage, big calendars
558 * or high loads, you are strongly adviced to optimize certain paths.
560 * The best way to do so is override this method and to optimize
561 * specifically for 'common filters'.
563 * Requests that are extremely common are:
564 * * requests for just VEVENTS
565 * * requests for just VTODO
566 * * requests with a time-range-filter on a VEVENT.
568 * ..and combinations of these requests. It may not be worth it to try to
569 * handle every possible situation and just rely on the (relatively
570 * easy to use) CalendarQueryValidator to handle the rest.
572 * Note that especially time-range-filters may be difficult to parse. A
573 * time-range filter specified on a VEVENT must for instance also handle
574 * recurrence rules correctly.
575 * A good example of how to interprete all these filters can also simply
576 * be found in Sabre_CalDAV_CalendarQueryFilter. This class is as correct
577 * as possible, so it gives you a good idea on what type of stuff you need
580 * This specific implementation (for the PDO) backend optimizes filters on
581 * specific components, and VEVENT time-ranges.
583 * @param string $calendarId
584 * @param array $filters
587 public function calendarQuery($calendarId, array $filters) {
590 $validator = new Sabre_CalDAV_CalendarQueryValidator();
592 $componentType = null;
593 $requirePostFilter = true;
596 // if no filters were specified, we don't need to filter after a query
597 if (!$filters['prop-filters'] && !$filters['comp-filters']) {
598 $requirePostFilter = false;
601 // Figuring out if there's a component filter
602 if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
603 $componentType = $filters['comp-filters'][0]['name'];
605 // Checking if we need post-filters
606 if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
607 $requirePostFilter = false;
609 // There was a time-range filter
610 if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
611 $timeRange = $filters['comp-filters'][0]['time-range'];
616 if ($requirePostFilter) {
617 $query = "SELECT uri, calendardata FROM ".$this->calendarObjectTableName." WHERE calendarid = :calendarid";
619 $query = "SELECT uri FROM ".$this->calendarObjectTableName." WHERE calendarid = :calendarid";
623 'calendarid' => $calendarId,
626 if ($componentType) {
627 $query.=" AND componenttype = :componenttype";
628 $values['componenttype'] = $componentType;
631 if ($timeRange && $timeRange['start']) {
632 $query.=" AND lastoccurence > :startdate";
633 $values['startdate'] = $timeRange['start']->getTimeStamp();
635 if ($timeRange && $timeRange['end']) {
636 $query.=" AND firstoccurence < :enddate";
637 $values['enddate'] = $timeRange['end']->getTimeStamp();
640 $stmt = $this->pdo->prepare($query);
641 $stmt->execute($values);
644 while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
645 if ($requirePostFilter) {
646 if (!$this->validateFilterForObject($row, $filters)) {
650 $result[] = $row['uri'];