3 class Sabre_CalDAV_Backend_Private extends Sabre_CalDAV_Backend_Common
8 * @var null|Sabre_CalDAV_Backend_Private
10 private static $instance = null;
14 * @return Sabre_CalDAV_Backend_Private
16 public static function getInstance()
18 if (self::$instance == null) {
19 self::$instance = new Sabre_CalDAV_Backend_Private();
21 return self::$instance;
28 public function getNamespace()
30 return CALDAV_NAMESPACE_PRIVATE;
37 public static function getBackendTypeName()
39 return t("Private Events");
44 * @param array $calendar
48 public function getPermissionsCalendar($calendar, $user)
50 if ($calendar["namespace"] == CALDAV_NAMESPACE_PRIVATE && $user == $calendar["namespace_id"]) return array("read"=> true, "write"=> true);
51 return array("read"=> false, "write"=> false);
56 * @param array $calendar
58 * @param string $calendarobject_id
59 * @param null|array $item_arr
62 public function getPermissionsItem($calendar, $user, $calendarobject_id, $item_arr = null)
64 return $this->getPermissionsCalendar($calendar, $user);
70 * @param array $calendar
71 * @param string $base_path
74 private function jqcal2wdcal($row, $calendar, $base_path)
76 $not = q("SELECT COUNT(*) num FROM %s%snotifications WHERE `calendar_id` = %d AND `calendarobject_id` = %d",
77 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($row["calendar_id"]), IntVal($row["calendarobject_id"])
79 $editable = $this->getPermissionsItem($calendar["namespace_id"], $row["calendarobject_id"], $row);
81 $end = wdcal_mySql2PhpTime($row["EndTime"]);
82 if ($row["IsAllDayEvent"]) $end -= 1;
85 "jq_id" => $row["id"],
86 "ev_id" => $row["calendarobject_id"],
87 "summary" => escape_tags($row["Summary"]),
88 "start" => wdcal_mySql2PhpTime($row["StartTime"]),
90 "is_allday" => $row["IsAllDayEvent"],
92 "is_recurring" => $row["IsRecurring"],
93 "color" => (is_null($row["Color"]) || $row["Color"] == "" ? $calendar["calendarcolor"] : $row["Color"]),
94 "is_editable" => ($editable ? 1 : 0),
95 "is_editable_quick" => ($editable && !$row["IsRecurring"] ? 1 : 0),
98 "has_notification" => ($not[0]["num"] > 0 ? 1 : 0),
99 "url_detail" => $base_path . $row["calendarobject_id"] . "/",
100 "url_edit" => $base_path . $row["calendarobject_id"] . "/edit/",
101 "special_type" => "",
106 * @param int $calendarId
109 * @param string $base_path
112 public function listItemsByRange($calendarId, $sd, $ed, $base_path)
114 $calendar = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId);
115 $von = wdcal_php2MySqlTime($sd);
116 $bis = wdcal_php2MySqlTime($ed);
117 $timezoneOffset = date("P");
119 // @TODO Events, die früher angefangen haben, aber noch andauern
120 $evs = q("SELECT *, CONVERT_TZ(`StartTime`, @@session.time_zone, '$timezoneOffset') StartTime, CONVERT_TZ(`EndTime`, @@session.time_zone, '$timezoneOffset') EndTime
121 FROM %s%sjqcalendar WHERE `calendar_id` = %d AND `StartTime` between '%s' and '%s'",
122 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($von), dbesc($bis));
125 foreach ($evs as $row) $events[] = $this->jqcal2wdcal($row, $calendar, $base_path . $row["calendar_id"] . "/");
132 * @param int $calendar_id
133 * @param int $calendarobject_id
136 public function getItemDetailRedirect($calendar_id, $calendarobject_id)
138 return "/dav/wdcal/$calendar_id/$calendarobject_id/edit/";
142 * Returns a list of calendars for a principal.
144 * Every project is an array with the following keys:
145 * * id, a unique id that will be used by other functions to modify the
146 * calendar. This can be the same as the uri or a database key.
147 * * uri, which the basename of the uri with which the calendar is
149 * * principaluri. The owner of the calendar. Almost always the same as
150 * principalUri passed to this method.
152 * Furthermore it can contain webdav properties in clark notation. A very
153 * common one is '{DAV:}displayname'.
155 * @param string $principalUri
156 * @throws DAVVersionMismatchException
159 public function getCalendarsForUser($principalUri)
161 $n = dav_compat_principal2namespace($principalUri);
162 if ($n["namespace"] != $this->getNamespace()) return array();
164 $cals = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $this->getNamespace(), IntVal($n["namespace_id"]));
166 foreach ($cals as $cal) {
167 if (!isset($cal["uri"])) throw new DAVVersionMismatchException();
168 if (in_array($cal["uri"], $GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"])) continue;
170 $components = array();
171 if ($cal["has_vevent"]) $components[] = "VEVENT";
172 if ($cal["has_vtodo"]) $components[] = "VTODO";
176 "uri" => $cal["uri"],
177 "principaluri" => $principalUri,
178 '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $cal['ctag'] ? $cal['ctag'] : '0',
179 '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components),
180 "calendar_class" => "Sabre_CalDAV_Calendar_Private",
182 foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field];
192 * Creates a new calendar for a principal.
194 * If the creation was a success, an id must be returned that can be used to reference
195 * this calendar in other methods, such as updateCalendar.
197 * @param string $principalUri
198 * @param string $calendarUri
199 * @param array $properties
200 * @throws Sabre_DAV_Exception|Sabre_DAV_Exception_Conflict
201 * @return string|void
203 public function createCalendar($principalUri, $calendarUri, array $properties)
206 $uid = dav_compat_principal2uid($principalUri);
208 $r = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, $uid, dbesc($calendarUri));
209 if (count($r) > 0) throw new Sabre_DAV_Exception_Conflict("A calendar with this URI already exists");
211 $keys = array("`namespace`", "`namespace_id`", "`ctag`", "`uri`");
212 $vals = array(CALDAV_NAMESPACE_PRIVATE, IntVal($uid), 1, "'" . dbesc($calendarUri) . "'");
215 $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
216 $has_vevent = $has_vtodo = 1;
217 if (isset($properties[$sccs])) {
218 if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) {
219 throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet');
221 $v = $properties[$sccs]->getValue();
222 $has_vevent = $has_vtodo = 0;
224 if (mb_strtolower($w) == "vevent") $has_vevent = 1;
225 if (mb_strtolower($w) == "vtodo") $has_vtodo = 1;
228 $keys[] = "`has_vevent`";
229 $keys[] = "`has_vtodo`";
230 $vals[] = $has_vevent;
231 $vals[] = $has_vtodo;
233 foreach ($this->propertyMap as $xmlName=> $dbName) {
234 if (isset($properties[$xmlName])) {
235 $keys[] = "`$dbName`";
236 $vals[] = "'" . dbesc($properties[$xmlName]) . "'";
240 $sql = sprintf("INSERT INTO %s%scalendars (" . implode(', ', $keys) . ") VALUES (" . implode(', ', $vals) . ")", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
244 $x = q("SELECT id FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
245 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, $uid, $calendarUri
252 * Updates properties for a calendar.
254 * The mutations array uses the propertyName in clark-notation as key,
255 * and the array value for the property value. In the case a property
256 * should be deleted, the property value will be null.
258 * This method must be atomic. If one property cannot be changed, the
259 * entire operation must fail.
261 * If the operation was successful, true can be returned.
262 * If the operation failed, false can be returned.
264 * Deletion of a non-existent property is always successful.
266 * Lastly, it is optional to return detailed information about any
267 * failures. In this case an array should be returned with the following
272 * '{DAV:}displayname' => null,
275 * '{DAV:}owner' => null,
279 * In this example it was forbidden to update {DAV:}displayname.
280 * (403 Forbidden), which in turn also caused {DAV:}owner to fail
281 * (424 Failed Dependency) because the request needs to be atomic.
283 * @param string $calendarId
284 * @param array $mutations
287 public function updateCalendar($calendarId, array $mutations)
290 $newValues = array();
292 200 => array(), // Ok
293 403 => array(), // Forbidden
294 424 => array(), // Failed Dependency
299 foreach ($mutations as $propertyName=> $propertyValue) {
301 // We don't know about this property.
302 if (!isset($this->propertyMap[$propertyName])) {
304 $result[403][$propertyName] = null;
305 unset($mutations[$propertyName]);
309 $fieldName = $this->propertyMap[$propertyName];
310 $newValues[$fieldName] = $propertyValue;
314 // If there were any errors we need to fail the request
316 // Properties has the remaining properties
317 foreach ($mutations as $propertyName=> $propertyValue) {
318 $result[424][$propertyName] = null;
321 // Removing unused statuscodes for cleanliness
322 foreach ($result as $status=> $properties) {
323 if (is_array($properties) && count($properties) === 0) unset($result[$status]);
330 $sql = "`ctag` = `ctag` + 1";
331 foreach ($newValues as $key=> $val) $sql .= ", `" . $key . "` = '" . dbesc($val) . "'";
333 $sql = sprintf("UPDATE %s%scalendars SET $sql WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
343 * Delete a calendar and all it's objects
345 * @param string $calendarId
348 public function deleteCalendar($calendarId)
350 q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
351 q("DELETE FROM %s%scalendars WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
357 * Returns all calendar objects within a calendar.
359 * Every item contains an array with the following keys:
360 * * id - unique identifier which will be used for subsequent updates
361 * * calendardata - The iCalendar-compatible calendar data
362 * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string.
363 * * lastmodified - a timestamp of the last modification time
364 * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
366 * * calendarid - The calendarid as it was passed to this function.
367 * * size - The size of the calendar objects, in bytes.
369 * Note that the etag is optional, but it's highly encouraged to return for
372 * The calendardata is also optional. If it's not returned
373 * 'getCalendarObject' will be called later, which *is* expected to return
376 * If neither etag or size are specified, the calendardata will be
377 * used/fetched to determine these numbers. If both are specified the
378 * amount of times this is needed is reduced by a great degree.
380 * @param mixed $calendarId
383 function getCalendarObjects($calendarId)
385 $objs = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
387 foreach ($objs as $obj) {
389 "id" => IntVal($obj["id"]),
390 "calendardata" => $obj["calendardata"],
391 "uri" => $obj["uri"],
392 "lastmodified" => $obj["lastmodified"],
393 "calendarid" => $calendarId,
394 "etag" => $obj["etag"],
395 "size" => IntVal($obj["size"]),
402 * Returns information from a single calendar object, based on it's object
405 * The returned array must have the same keys as getCalendarObjects. The
406 * 'calendardata' object is required here though, while it's not required
407 * for getCalendarObjects.
409 * @param string $calendarId
410 * @param string $objectUri
411 * @throws Sabre_DAV_Exception_NotFound
414 function getCalendarObject($calendarId, $objectUri)
416 $o = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'",
417 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
419 $o[0]["calendarid"] = $calendarId;
420 $o[0]["calendardata"] = str_ireplace("Europe/Belgrade", "Europe/Berlin", $o[0]["calendardata"]);
422 } else throw new Sabre_DAV_Exception_NotFound($calendarId . " / " . $objectUri);
426 * Creates a new calendar object.
428 * It is possible return an etag from this function, which will be used in
429 * the response to this PUT request. Note that the ETag must be surrounded
432 * However, you should only really return this ETag if you don't mangle the
433 * calendar-data. If the result of a subsequent GET to this object is not
434 * the exact same as this request body, you should omit the ETag.
436 * @param mixed $calendarId
437 * @param string $objectUri
438 * @param string $calendarData
439 * @return string|null
441 function createCalendarObject($calendarId, $objectUri, $calendarData)
443 $calendarData = icalendar_sanitize_string($calendarData);
445 $extraData = $this->getDenormalizedData($calendarData);
447 q("INSERT INTO %s%scalendarobjects (`calendar_id`, `uri`, `calendardata`, `lastmodified`, `componentType`, `firstOccurence`, `lastOccurence`, `etag`, `size`)
448 VALUES (%d, '%s', '%s', NOW(), '%s', '%s', '%s', '%s', %d)",
449 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri), addslashes($calendarData), dbesc($extraData['componentType']),
450 dbesc(wdcal_php2MySqlTime($extraData['firstOccurence'])), dbesc(wdcal_php2MySqlTime($extraData['lastOccurence'])), dbesc($extraData["etag"]), IntVal($extraData["size"])
453 $this->increaseCalendarCtag($calendarId);
454 renderCalDavEntry_uri($objectUri);
456 return '"' . $extraData['etag'] . '"';
460 * Updates an existing calendarobject, based on it's uri.
462 * It is possible return an etag from this function, which will be used in
463 * the response to this PUT request. Note that the ETag must be surrounded
466 * However, you should only really return this ETag if you don't mangle the
467 * calendar-data. If the result of a subsequent GET to this object is not
468 * the exact same as this request body, you should omit the ETag.
470 * @param mixed $calendarId
471 * @param string $objectUri
472 * @param string $calendarData
473 * @return string|null
475 function updateCalendarObject($calendarId, $objectUri, $calendarData)
477 $calendarData = icalendar_sanitize_string($calendarData);
479 $extraData = $this->getDenormalizedData($calendarData);
481 q("UPDATE %s%scalendarobjects SET `calendardata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `componentType` = '%s', `firstOccurence` = '%s', `lastOccurence` = '%s'
482 WHERE `calendar_id` = %d AND `uri` = '%s'",
483 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($calendarData), dbesc($extraData["etag"]), IntVal($extraData["size"]), dbesc($extraData["componentType"]),
484 dbesc(wdcal_php2MySqlTime($extraData["firstOccurence"])), dbesc(wdcal_php2MySqlTime($extraData["lastOccurence"])), IntVal($calendarId), dbesc($objectUri));
486 $this->increaseCalendarCtag($calendarId);
487 renderCalDavEntry_uri($objectUri);
489 return '"' . $extraData['etag'] . '"';
493 * Deletes an existing calendar object.
495 * @param string $calendarId
496 * @param string $objectUri
497 * @throws Sabre_DAV_Exception_NotFound
500 function deleteCalendarObject($calendarId, $objectUri)
502 $r = q("SELECT `id` FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
503 if (count($r) == 0) throw new Sabre_DAV_Exception_NotFound();
505 q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
507 $this->increaseCalendarCtag($calendarId);
508 renderCalDavEntry_calobj_id($r[0]["id"]);