ctucx.git: tinyDAV

[php] Cal-/ CardDAV server with a simple web-GUI based on SabreDAV

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 
<?php
declare(strict_types=1);

use Sabre\CalDAV;
use Sabre\DAV;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Xml\Element\Sharee;
use Sabre\VObject;

class SabreCalDAVJsonBackend extends Sabre\CalDAV\Backend\AbstractBackend implements Sabre\CalDAV\Backend\SyncSupport {
	const MAX_DATE = '2038-01-01';

	protected $calMgr;


	public $propertyMap = [
			'displayname'   => '{DAV:}displayname',
			'description'   => '{urn:ietf:params:xml:ns:caldav}calendar-description',
			'timezone'      => '{urn:ietf:params:xml:ns:caldav}calendar-timezone',
			'calendarorder' => '{http://apple.com/ns/ical/}calendar-order',
			'calendarcolor' => '{http://apple.com/ns/ical/}calendar-color',
		];

	public function __construct (CalendarCollectionManager $calMgr) {
		$this->calMgr = $calMgr;
	}

	public function getCalendarsForUser ($principalUri) {
		$calendars = [];

		foreach ($this->calMgr->getCollections($principalUri) as $row) {
			$components = [];
		
			if ($row['components']) {
				$components = explode(',', $row['components']);
			}
	
			$calendar = [
	 				   	'id'                                                             => [(int) $row['id'], (int) $row['id']],
						'uri'                                                            => $row['uri'],
						'principaluri'                                                   => $row['principaluri'],
			'{'.CalDAV\Plugin::NS_CALENDARSERVER.'}getctag'                  => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
			'{http://sabredav.org/ns}sync-token'                             => $row['synctoken'] ? $row['synctoken'] : '0',
			'{'.CalDAV\Plugin::NS_CALDAV.'}supported-calendar-component-set' => new CalDAV\Xml\Property\SupportedCalendarComponentSet($components),
					];

			foreach ($this->propertyMap as $dbName => $xmlName) {
				$calendar[$xmlName] = $row[$dbName];
			}

			$calendars[] = $calendar;
		}

		return $calendars;
	}

	public function createCalendar ($principalUri, $calendarUri, array $properties) {
		$sccs       = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
		$components = 'VEVENT,VTODO';

		if (isset($properties[$sccs])) {
			if (!($properties[$sccs] instanceof CalDAV\Xml\Property\SupportedCalendarComponentSet)) {
				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet');
			}
			
			$components = implode(',', $properties[$sccs]->getValue());
		}

		$values = [
				'components' => $components,				
			];

		foreach ($this->propertyMap as $xmlName => $dbName) {
			if (isset($properties[$xmlName])) {
				$values[$dbName] = $properties[$xmlName];
			}
		}

		$calendarId = $this->calMgr->createCollection($principalUri, $calendarUri, $values);

		return [ $calendarId, $calendarId ];
	}

	public function updateCalendar ($calendarId, \Sabre\DAV\PropPatch $propPatch) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}
		list($calendarId) = $calendarId;

		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
			$values = [];

	   		foreach ($this->propertyMap as $xmlName => $dbName) {
				if (isset($mutations[$xmlName])) {
					$values[$dbName] = $mutations[$xmlName];
		   		}
			}

			$this->calMgr->updateCollection($calendarId, $values);
			return true;
		});
	}

	public function deleteCalendar ($calendarId) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}

		list($calendarId) = $calendarId;

		$this->calMgr->deleteCollection($calendarId);
	}

	public function getCalendarObjects ($calendarId) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}

		list($calendarId) = $calendarId;

		$result = [];
		foreach ($this->calMgr->getObjects($calendarId) as $row) {
			$result[] = [
				'id'           => $row['id'],
				'uri'          => $row['uri'],
				'lastmodified' => (int) $row['lastmodified'],
				'etag'         => '"'.$row['etag'].'"',
				'size'         => (int) $row['size'],
				'component'    => strtolower($row['componenttype']),
			];
		}

		return $result;
	}

	public function getCalendarObject ($calendarId, $objectUri) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}
		
		list($calendarId ) = $calendarId;

		$row = $this->calMgr->getObject($calendarId, $objectUri);

		if (!$row) {
			return null;
		}

		return [
			'id'           => $row['id'],
			'uri'          => $row['uri'],
			'lastmodified' => (int) $row['lastmodified'],
			'etag'         => '"'.$row['etag'].'"',
			'size'         => (int) $row['size'],
			'calendardata' => $row['calendardata'],
			'component'    => strtolower($row['componenttype']),
		 ];
	}

	public function getMultipleCalendarObjects($calendarId, array $uris) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}

		list($calendarId) = $calendarId;

		$result = [];

		foreach (array_chunk($uris, 900) as $chunk) {
			$row = $this->calMgr()->getObject($calendarId, $chunk);

			$result[] = [
					'id'           => $row['id'],
					'uri'          => $row['uri'],
					'lastmodified' => (int) $row['lastmodified'],
					'etag'         => '"'.$row['etag'].'"',
					'size'         => (int) $row['size'],
					'calendardata' => $row['calendardata'],
					'component'    => strtolower($row['componenttype']),
				];
		}

		return $result;
	}

	public function createCalendarObject ($calendarId, $objectUri, $calendarData) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}

		list($calendarId) = $calendarId;

		return '"'.$this->calMgr->createObject($calendarId, $objectUri, $calendarData, $this->getDenormalizedData($calendarData)).'"';
	}

	public function updateCalendarObject ($calendarId, $objectUri, $calendarData) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}

		list($calendarId) = $calendarId;

		return '"'.$this->calMgr->updateObject($calendarId, $objectUri, $calendarData, $this->getDenormalizedData($calendarData)).'"';
	}

	public function deleteCalendarObject ($calendarId, $objectUri) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}

		list($calendarId) = $calendarId;

		$this->calMgr->deleteObject($calendarId, $objectUri);
	}

	public function calendarQuery ($calendarId, array $filters) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}

		list($calendarId) = $calendarId;

		$componentType     = NULL;
		$requirePostFilter = true;
		$timeRange         = NULL;

		// if no filters were specified, we don't need to filter after a query
		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
			$requirePostFilter = false;
		}

		// Figuring out if there's a component filter
		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
			$componentType = $filters['comp-filters'][0]['name'];

			// Checking if we need post-filters
			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
				$requirePostFilter = false;
			}
			// There was a time-range filter
			if ('VEVENT' == $componentType && isset($filters['comp-filters'][0]['time-range'])) {
				$timeRange = $filters['comp-filters'][0]['time-range'];

				// If start time OR the end time is not specified, we can do a
				// 100% accurate mysql query.
				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
					$requirePostFilter = false;
				}
			}
		}

		$entries = $this->calMgr->getObjects($calendarId);
		foreach ($entries as $key => $entry) {
			if ($componentType && $componentType !== $entry['componenttype']) unset($entries[$key]); continue;

			if ($timeRange) {
				if ($timeRange['start'] && $entry['lastoccurence'] > $timeRange['start']->getTimeStamp()) unset($entries[$key]); continue;
				if ($timeRange['end'] && $entry['firstoccurence'] < $timeRange['end']->getTimeStamp()) unset($entries[$key]); continue;
			}
		}

		$result = [];
		foreach ($entries as $row) {
			if ($requirePostFilter) {
				$row['calendarid'] = [$calendarId, $calendarId];

				if (!$this->validateFilterForObject($row, $filters)) {
					continue;
				}
			}

			$result[] = $row['uri'];
		}

		return $result;
	}

	public function getCalendarObjectByUID ($principalUri, $uid) {
		return $this->calMgr->getUriByUID($principalUri, $uid);
	}

	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
		if (!is_array($calendarId)) {
			throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
		}

		list($calendarId) = $calendarId;

		return $this->calMgr->getChanges($calendarid, $syncToken, $syncLevel);		
	}



	protected function getDenormalizedData ($calendarData) {
		$vObject = VObject\Reader::read($calendarData);
		$componentType = null;
		$component = null;
		$firstOccurence = null;
		$lastOccurence = null;
		$uid = null;

		foreach ($vObject->getComponents() as $component) {
			if ('VTIMEZONE' !== $component->name) {
				$componentType = $component->name;
				$uid = (string) $component->UID;
				break;
			}
		}

		if (!$componentType) {
			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
		}

		if ('VEVENT' === $componentType) {
			$firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
			// Finding the last occurence is a bit harder
			if (!isset($component->RRULE)) {
				if (isset($component->DTEND)) {
					$lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
				} elseif (isset($component->DURATION)) {
					$endDate = clone $component->DTSTART->getDateTime();
					$endDate = $endDate->add(VObject\DateTimeParser::parse($component->DURATION->getValue()));
					$lastOccurence = $endDate->getTimeStamp();
				} elseif (!$component->DTSTART->hasTime()) {
					$endDate = clone $component->DTSTART->getDateTime();
					$endDate = $endDate->modify('+1 day');
					$lastOccurence = $endDate->getTimeStamp();
				} else {
					$lastOccurence = $firstOccurence;
				}
			} else {
				$it = new VObject\Recur\EventIterator($vObject, (string) $component->UID);
				$maxDate = new \DateTime(self::MAX_DATE);
				if ($it->isInfinite()) {
					$lastOccurence = $maxDate->getTimeStamp();
				} else {
					$end = $it->getDtEnd();
					while ($it->valid() && $end < $maxDate) {
						$end = $it->getDtEnd();
						$it->next();
					}
					$lastOccurence = $end->getTimeStamp();
				}
			}

			// Ensure Occurence values are positive
			if ($firstOccurence < 0) {
				$firstOccurence = 0;
			}
			if ($lastOccurence < 0) {
				$lastOccurence = 0;
			}
		}

		// Destroy circular references to PHP will GC the object.
		$vObject->destroy();

		return [
			'etag'           => md5($calendarData),
			'size'           => strlen($calendarData),
			'componenttype'  => $componentType,
			'firstoccurence' => $firstOccurence,
			'lastoccurence'  => $lastOccurence,
			'uid'            => $uid,
		];
	}
}