]> git.mxchange.org Git - friendica-addons.git/blob - dav/SabreDAV/lib/Sabre/CalDAV/Backend/PDO.php
Merge pull request #57 from CatoTH/master
[friendica-addons.git] / dav / SabreDAV / lib / Sabre / CalDAV / Backend / PDO.php
1 <?php
2
3 /**
4  * PDO CalDAV backend
5  *
6  * This backend is used to store calendar-data in a PDO database, such as
7  * sqlite or MySQL
8  *
9  * @package Sabre
10  * @subpackage CalDAV
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
14  */
15 class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract {
16
17     /**
18      * We need to specify a max date, because we need to stop *somewhere*
19      */
20     const MAX_DATE = '2040-01-01';
21
22     /**
23      * pdo
24      *
25      * @var PDO
26      */
27     protected $pdo;
28
29     /**
30      * The table name that will be used for calendars
31      *
32      * @var string
33      */
34     protected $calendarTableName;
35
36     /**
37      * The table name that will be used for calendar objects
38      *
39      * @var string
40      */
41     protected $calendarObjectTableName;
42
43     /**
44      * List of CalDAV properties, and how they map to database fieldnames
45      *
46      * Add your own properties by simply adding on to this array
47      *
48      * @var array
49      */
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',
56     );
57
58     /**
59      * Creates the backend
60      *
61      * @param PDO $pdo
62      * @param string $calendarTableName
63      * @param string $calendarObjectTableName
64      */
65     public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') {
66
67         $this->pdo = $pdo;
68         $this->calendarTableName = $calendarTableName;
69         $this->calendarObjectTableName = $calendarObjectTableName;
70
71     }
72
73     /**
74      * Returns a list of calendars for a principal.
75      *
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
80      *    accessed.
81      *  * principaluri. The owner of the calendar. Almost always the same as
82      *    principalUri passed to this method.
83      *
84      * Furthermore it can contain webdav properties in clark notation. A very
85      * common one is '{DAV:}displayname'.
86      *
87      * @param string $principalUri
88      * @return array
89      */
90     public function getCalendarsForUser($principalUri) {
91
92         $fields = array_values($this->propertyMap);
93         $fields[] = 'id';
94         $fields[] = 'uri';
95         $fields[] = 'ctag';
96         $fields[] = 'components';
97         $fields[] = 'principaluri';
98
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));
103
104         $calendars = array();
105         while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
106
107             $components = array();
108             if ($row['components']) {
109                 $components = explode(',',$row['components']);
110             }
111
112             $calendar = array(
113                 'id' => $row['id'],
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),
118             );
119
120
121             foreach($this->propertyMap as $xmlName=>$dbName) {
122                 $calendar[$xmlName] = $row[$dbName];
123             }
124
125             $calendars[] = $calendar;
126
127         }
128
129         return $calendars;
130
131     }
132
133     /**
134      * Creates a new calendar for a principal.
135      *
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
138      *
139      * @param string $principalUri
140      * @param string $calendarUri
141      * @param array $properties
142      * @return string
143      */
144     public function createCalendar($principalUri, $calendarUri, array $properties) {
145
146         $fieldNames = array(
147             'principaluri',
148             'uri',
149             'ctag',
150         );
151         $values = array(
152             ':principaluri' => $principalUri,
153             ':uri'          => $calendarUri,
154             ':ctag'         => 1,
155         );
156
157         // Default value
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';
162         } else {
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');
165             }
166             $values[':components'] = implode(',',$properties[$sccs]->getValue());
167         }
168
169         foreach($this->propertyMap as $xmlName=>$dbName) {
170             if (isset($properties[$xmlName])) {
171
172                 $values[':' . $dbName] = $properties[$xmlName];
173                 $fieldNames[] = $dbName;
174             }
175         }
176
177         $stmt = $this->pdo->prepare("INSERT INTO ".$this->calendarTableName." (".implode(', ', $fieldNames).") VALUES (".implode(', ',array_keys($values)).")");
178         $stmt->execute($values);
179
180         return $this->pdo->lastInsertId();
181
182     }
183
184     /**
185      * Updates properties for a calendar.
186      *
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.
190      *
191      * This method must be atomic. If one property cannot be changed, the
192      * entire operation must fail.
193      *
194      * If the operation was successful, true can be returned.
195      * If the operation failed, false can be returned.
196      *
197      * Deletion of a non-existent property is always successful.
198      *
199      * Lastly, it is optional to return detailed information about any
200      * failures. In this case an array should be returned with the following
201      * structure:
202      *
203      * array(
204      *   403 => array(
205      *      '{DAV:}displayname' => null,
206      *   ),
207      *   424 => array(
208      *      '{DAV:}owner' => null,
209      *   )
210      * )
211      *
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.
215      *
216      * @param string $calendarId
217      * @param array $mutations
218      * @return bool|array
219      */
220     public function updateCalendar($calendarId, array $mutations) {
221
222         $newValues = array();
223         $result = array(
224             200 => array(), // Ok
225             403 => array(), // Forbidden
226             424 => array(), // Failed Dependency
227         );
228
229         $hasError = false;
230
231         foreach($mutations as $propertyName=>$propertyValue) {
232
233             // We don't know about this property.
234             if (!isset($this->propertyMap[$propertyName])) {
235                 $hasError = true;
236                 $result[403][$propertyName] = null;
237                 unset($mutations[$propertyName]);
238                 continue;
239             }
240
241             $fieldName = $this->propertyMap[$propertyName];
242             $newValues[$fieldName] = $propertyValue;
243
244         }
245
246         // If there were any errors we need to fail the request
247         if ($hasError) {
248             // Properties has the remaining properties
249             foreach($mutations as $propertyName=>$propertyValue) {
250                 $result[424][$propertyName] = null;
251             }
252
253             // Removing unused statuscodes for cleanliness
254             foreach($result as $status=>$properties) {
255                 if (is_array($properties) && count($properties)===0) unset($result[$status]);
256             }
257
258             return $result;
259
260         }
261
262         // Success
263
264         // Now we're generating the sql query.
265         $valuesSql = array();
266         foreach($newValues as $fieldName=>$value) {
267             $valuesSql[] = $fieldName . ' = ?';
268         }
269         $valuesSql[] = 'ctag = ctag + 1';
270
271         $stmt = $this->pdo->prepare("UPDATE " . $this->calendarTableName . " SET " . implode(', ',$valuesSql) . " WHERE id = ?");
272         $newValues['id'] = $calendarId;
273         $stmt->execute(array_values($newValues));
274
275         return true;
276
277     }
278
279     /**
280      * Delete a calendar and all it's objects
281      *
282      * @param string $calendarId
283      * @return void
284      */
285     public function deleteCalendar($calendarId) {
286
287         $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?');
288         $stmt->execute(array($calendarId));
289
290         $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarTableName.' WHERE id = ?');
291         $stmt->execute(array($calendarId));
292
293     }
294
295     /**
296      * Returns all calendar objects within a calendar.
297      *
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.:
304      *   '  "abcdef"')
305      *   * calendarid - The calendarid as it was passed to this function.
306      *   * size - The size of the calendar objects, in bytes.
307      *
308      * Note that the etag is optional, but it's highly encouraged to return for
309      * speed reasons.
310      *
311      * The calendardata is also optional. If it's not returned
312      * 'getCalendarObject' will be called later, which *is* expected to return
313      * calendardata.
314      *
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.
318      *
319      * @param string $calendarId
320      * @return array
321      */
322     public function getCalendarObjects($calendarId) {
323
324         $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?');
325         $stmt->execute(array($calendarId));
326
327         $result = array();
328         foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
329             $result[] = array(
330                 'id'           => $row['id'],
331                 'uri'          => $row['uri'],
332                 'lastmodified' => $row['lastmodified'],
333                 'etag'         => '"' . $row['etag'] . '"',
334                 'calendarid'   => $row['calendarid'],
335                 'size'         => (int)$row['size'],
336             );
337         }
338
339         return $result;
340
341     }
342
343     /**
344      * Returns information from a single calendar object, based on it's object
345      * uri.
346      *
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.
350      *
351      * @param string $calendarId
352      * @param string $objectUri
353      * @return array
354      */
355     public function getCalendarObject($calendarId,$objectUri) {
356
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);
360
361         if(!$row) return null;
362
363         return array(
364             'id'           => $row['id'],
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'],
371          );
372
373     }
374
375
376     /**
377      * Creates a new calendar object.
378      *
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
381      * by double-quotes.
382      *
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.
386      *
387      * @param mixed $calendarId
388      * @param string $objectUri
389      * @param string $calendarData
390      * @return string|null
391      */
392     public function createCalendarObject($calendarId,$objectUri,$calendarData) {
393
394         $extraData = $this->getDenormalizedData($calendarData);
395
396         $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarObjectTableName.' (calendarid, uri, calendardata, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence) VALUES (?,?,?,?,?,?,?,?,?)');
397         $stmt->execute(array(
398             $calendarId,
399             $objectUri,
400             $calendarData,
401             time(),
402             $extraData['etag'],
403             $extraData['size'],
404             $extraData['componentType'],
405             $extraData['firstOccurence'],
406             $extraData['lastOccurence'],
407         ));
408         $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?');
409         $stmt->execute(array($calendarId));
410
411         return '"' . $extraData['etag'] . '"';
412
413     }
414
415     /**
416      * Updates an existing calendarobject, based on it's uri.
417      *
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
420      * by double-quotes.
421      *
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.
425      *
426      * @param mixed $calendarId
427      * @param string $objectUri
428      * @param string $calendarData
429      * @return string|null
430      */
431     public function updateCalendarObject($calendarId,$objectUri,$calendarData) {
432
433         $extraData = $this->getDenormalizedData($calendarData);
434
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));
439
440         return '"' . $extraData['etag'] . '"';
441
442     }
443
444     /**
445      * Parses some information from calendar objects, used for optimized
446      * calendar-queries.
447      *
448      * Returns an array with the following keys:
449      *   * etag
450      *   * size
451      *   * componentType
452      *   * firstOccurence
453      *   * lastOccurence
454      *
455      * @param string $calendarData
456      * @return array
457      */
458     protected function getDenormalizedData($calendarData) {
459
460         $vObject = Sabre_VObject_Reader::read($calendarData);
461         $componentType = null;
462         $component = null;
463         $firstOccurence = null;
464         $lastOccurence = null;
465         foreach($vObject->getComponents() as $component) {
466             if ($component->name!=='VTIMEZONE') {
467                 $componentType = $component->name;
468                 break;
469             }
470         }
471         if (!$componentType) {
472             throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
473         }
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();
488                 } else {
489                     $lastOccurence = $firstOccurence;
490                 }
491             } else {
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();
496                 } else {
497                     $end = $it->getDtEnd();
498                     while($it->valid() && $end < $maxDate) {
499                         $end = $it->getDtEnd();
500                         $it->next();
501
502                     }
503                     $lastOccurence = $end->getTimeStamp();
504                 }
505
506             }
507         }
508
509         return array(
510             'etag' => md5($calendarData),
511             'size' => strlen($calendarData),
512             'componentType' => $componentType,
513             'firstOccurence' => $firstOccurence,
514             'lastOccurence'  => $lastOccurence,
515         );
516
517     }
518
519     /**
520      * Deletes an existing calendar object.
521      *
522      * @param string $calendarId
523      * @param string $objectUri
524      * @return void
525      */
526     public function deleteCalendarObject($calendarId,$objectUri) {
527
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));
532
533     }
534
535     /**
536      * Performs a calendar-query on the contents of this calendar.
537      *
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).
542      *
543      * This method should just return a list of (relative) urls that match this
544      * query.
545      *
546      * The list of filters are specified as an array. The exact array is
547      * documented by Sabre_CalDAV_CalendarQueryParser.
548      *
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.
552      *
553      * This method provides a default implementation, which parses *all* the
554      * iCalendar objects in the specified calendar.
555      *
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.
559      *
560      * The best way to do so is override this method and to optimize
561      * specifically for 'common filters'.
562      *
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.
567      *
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.
571      *
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
578      * to think of.
579      *
580      * This specific implementation (for the PDO) backend optimizes filters on
581      * specific components, and VEVENT time-ranges.
582      *
583      * @param string $calendarId
584      * @param array $filters
585      * @return array
586      */
587     public function calendarQuery($calendarId, array $filters) {
588
589         $result = array();
590         $validator = new Sabre_CalDAV_CalendarQueryValidator();
591
592         $componentType = null;
593         $requirePostFilter = true;
594         $timeRange = null;
595
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;
599         }
600
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'];
604
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;
608             }
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'];
612             }
613
614         }
615
616         if ($requirePostFilter) {
617             $query = "SELECT uri, calendardata FROM ".$this->calendarObjectTableName." WHERE calendarid = :calendarid";
618         } else {
619             $query = "SELECT uri FROM ".$this->calendarObjectTableName." WHERE calendarid = :calendarid";
620         }
621
622         $values = array(
623             'calendarid' => $calendarId,
624         );
625
626         if ($componentType) {
627             $query.=" AND componenttype = :componenttype";
628             $values['componenttype'] = $componentType;
629         }
630
631         if ($timeRange && $timeRange['start']) {
632             $query.=" AND lastoccurence > :startdate";
633             $values['startdate'] = $timeRange['start']->getTimeStamp();
634         }
635         if ($timeRange && $timeRange['end']) {
636             $query.=" AND firstoccurence < :enddate";
637             $values['enddate'] = $timeRange['end']->getTimeStamp();
638         }
639
640         $stmt = $this->pdo->prepare($query);
641         $stmt->execute($values);
642
643         $result = array();
644         while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
645             if ($requirePostFilter) {
646                 if (!$this->validateFilterForObject($row, $filters)) {
647                     continue;
648                 }
649             }
650             $result[] = $row['uri'];
651
652         }
653
654         return $result;
655
656     }
657 }