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;
36 * @param array $calendar
40 public function getPermissionsCalendar($calendar, $user)
42 if ($calendar["namespace"] == CALDAV_NAMESPACE_PRIVATE && $user == $calendar["namespace_id"]) return array("read"=> true, "write"=> true);
43 return array("read"=> false, "write"=> false);
48 * @param array $calendar
50 * @param string $calendarobject_id
51 * @param null|array $item_arr
54 public function getPermissionsItem($calendar, $user, $calendarobject_id, $item_arr = null)
56 return $this->getPermissionsCalendar($calendar, $user);
62 * @param array $calendar
63 * @param string $base_path
66 private function jqcal2wdcal($row, $calendar, $base_path)
68 $not = q("SELECT COUNT(*) num FROM %s%snotifications WHERE `calendar_id` = %d AND `calendarobject_id` = %d",
69 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($row["calendar_id"]), IntVal($row["calendarobject_id"])
71 $editable = $this->getPermissionsItem($calendar["namespace_id"], $row["calendarobject_id"], $row);
73 $end = wdcal_mySql2PhpTime($row["EndTime"]);
74 if ($row["IsAllDayEvent"]) $end -= 1;
77 "jq_id" => $row["id"],
78 "ev_id" => $row["calendarobject_id"],
79 "summary" => escape_tags($row["Summary"]),
80 "start" => wdcal_mySql2PhpTime($row["StartTime"]),
82 "is_allday" => $row["IsAllDayEvent"],
84 "is_recurring" => $row["IsRecurring"],
85 "color" => (is_null($row["Color"]) || $row["Color"] == "" ? $calendar["calendarcolor"] : $row["Color"]),
86 "is_editable" => ($editable ? 1 : 0),
87 "is_editable_quick" => ($editable && !$row["IsRecurring"] ? 1 : 0),
90 "has_notification" => ($not[0]["num"] > 0 ? 1 : 0),
91 "url_detail" => $base_path . $row["calendarobject_id"] . "/",
92 "url_edit" => $base_path . $row["calendarobject_id"] . "/edit/",
98 * @param int $calendarId
101 * @param string $base_path
104 public function listItemsByRange($calendarId, $sd, $ed, $base_path)
106 $calendar = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId);
107 $von = wdcal_php2MySqlTime($sd);
108 $bis = wdcal_php2MySqlTime($ed);
110 // @TODO Events, die früher angefangen haben, aber noch andauern
111 $evs = q("SELECT * FROM %s%sjqcalendar WHERE `calendar_id` = %d AND `starttime` between '%s' and '%s'",
112 CALDAV_SQL_DB, CALDAV_SQL_PREFIX,
113 IntVal($calendarId), dbesc($von), dbesc($bis));
116 foreach ($evs as $row) $events[] = $this->jqcal2wdcal($row, $calendar, $base_path . $row["calendar_id"] . "/");
123 * @param int $calendar_id
124 * @param int $calendarobject_id
127 public function getItemDetailRedirect($calendar_id, $calendarobject_id)
129 return "/dav/wdcal/$calendar_id/$calendarobject_id/edit/";
133 * Returns a list of calendars for a principal.
135 * Every project is an array with the following keys:
136 * * id, a unique id that will be used by other functions to modify the
137 * calendar. This can be the same as the uri or a database key.
138 * * uri, which the basename of the uri with which the calendar is
140 * * principaluri. The owner of the calendar. Almost always the same as
141 * principalUri passed to this method.
143 * Furthermore it can contain webdav properties in clark notation. A very
144 * common one is '{DAV:}displayname'.
146 * @param string $principalUri
149 public function getCalendarsForUser($principalUri)
151 $n = dav_compat_principal2namespace($principalUri);
152 if ($n["namespace"] != $this->getNamespace()) return array();
154 $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"]));
156 foreach ($cals as $cal) {
157 if (in_array($cal["uri"], $GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"])) continue;
161 "uri" => $cal["uri"],
162 "principaluri" => $principalUri,
163 '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $cal['ctag'] ? $cal['ctag'] : '0',
164 "calendar_class" => "Sabre_CalDAV_Calendar",
166 foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field];
176 * Creates a new calendar for a principal.
178 * If the creation was a success, an id must be returned that can be used to reference
179 * this calendar in other methods, such as updateCalendar.
181 * @param string $principalUri
182 * @param string $calendarUri
183 * @param array $properties
184 * @throws Sabre_DAV_Exception
185 * @return string|void
187 public function createCalendar($principalUri, $calendarUri, array $properties)
190 $uid = dav_compat_principal2uid($principalUri);
192 $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));
193 if (count($r) > 0) throw new Sabre_DAV_Exception("A calendar with this URI already exists");
195 $keys = array("`namespace`", "`namespace_id`", "`ctag`", "`uri`");
196 $vals = array(CALDAV_NAMESPACE_PRIVATE, IntVal($uid), 1, "'" . dbesc($calendarUri) . "'");
199 $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
200 $has_vevent = $has_vtodo = 1;
201 if (isset($properties[$sccs])) {
202 if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) {
203 throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet');
205 $v = $properties[$sccs]->getValue();
206 $has_vevent = $has_vtodo = 0;
208 if (mb_strtolower($w) == "vevent") $has_vevent = 1;
209 if (mb_strtolower($w) == "vtodo") $has_vtodo = 1;
212 $keys[] = "`has_vevent`";
213 $keys[] = "`has_vtodo`";
214 $vals[] = $has_vevent;
215 $vals[] = $has_vtodo;
217 foreach ($this->propertyMap as $xmlName=> $dbName) {
218 if (isset($properties[$xmlName])) {
219 $keys[] = "`$dbName`";
220 $vals[] = "'" . dbesc($properties[$xmlName]) . "'";
224 $sql = sprintf("INSERT INTO %s%scalendars (" . implode(', ', $keys) . ") VALUES (" . implode(', ', $vals) . ")", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
228 $x = q("SELECT id FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
229 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, $uid, $calendarUri
236 * Updates properties for a calendar.
238 * The mutations array uses the propertyName in clark-notation as key,
239 * and the array value for the property value. In the case a property
240 * should be deleted, the property value will be null.
242 * This method must be atomic. If one property cannot be changed, the
243 * entire operation must fail.
245 * If the operation was successful, true can be returned.
246 * If the operation failed, false can be returned.
248 * Deletion of a non-existent property is always successful.
250 * Lastly, it is optional to return detailed information about any
251 * failures. In this case an array should be returned with the following
256 * '{DAV:}displayname' => null,
259 * '{DAV:}owner' => null,
263 * In this example it was forbidden to update {DAV:}displayname.
264 * (403 Forbidden), which in turn also caused {DAV:}owner to fail
265 * (424 Failed Dependency) because the request needs to be atomic.
267 * @param string $calendarId
268 * @param array $mutations
271 public function updateCalendar($calendarId, array $mutations)
274 $newValues = array();
276 200 => array(), // Ok
277 403 => array(), // Forbidden
278 424 => array(), // Failed Dependency
283 foreach ($mutations as $propertyName=> $propertyValue) {
285 // We don't know about this property.
286 if (!isset($this->propertyMap[$propertyName])) {
288 $result[403][$propertyName] = null;
289 unset($mutations[$propertyName]);
293 $fieldName = $this->propertyMap[$propertyName];
294 $newValues[$fieldName] = $propertyValue;
298 // If there were any errors we need to fail the request
300 // Properties has the remaining properties
301 foreach ($mutations as $propertyName=> $propertyValue) {
302 $result[424][$propertyName] = null;
305 // Removing unused statuscodes for cleanliness
306 foreach ($result as $status=> $properties) {
307 if (is_array($properties) && count($properties) === 0) unset($result[$status]);
314 $sql = "`ctag` = `ctag` + 1";
315 foreach ($newValues as $key=> $val) $sql .= ", `" . $key . "` = '" . dbesc($val) . "'";
317 $sql = sprintf("UPDATE %s%scalendars SET $sql WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
327 * Delete a calendar and all it's objects
329 * @param string $calendarId
332 public function deleteCalendar($calendarId)
334 q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
335 q("DELETE FROM %s%scalendars WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
341 * Returns all calendar objects within a calendar.
343 * Every item contains an array with the following keys:
344 * * id - unique identifier which will be used for subsequent updates
345 * * calendardata - The iCalendar-compatible calendar data
346 * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string.
347 * * lastmodified - a timestamp of the last modification time
348 * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
350 * * calendarid - The calendarid as it was passed to this function.
351 * * size - The size of the calendar objects, in bytes.
353 * Note that the etag is optional, but it's highly encouraged to return for
356 * The calendardata is also optional. If it's not returned
357 * 'getCalendarObject' will be called later, which *is* expected to return
360 * If neither etag or size are specified, the calendardata will be
361 * used/fetched to determine these numbers. If both are specified the
362 * amount of times this is needed is reduced by a great degree.
364 * @param mixed $calendarId
367 function getCalendarObjects($calendarId)
369 $objs = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
371 foreach ($objs as $obj) {
373 "id" => IntVal($obj["id"]),
374 "calendardata" => $obj["calendardata"],
375 "uri" => $obj["uri"],
376 "lastmodified" => $obj["lastmodified"],
377 "calendarid" => $calendarId,
378 "etag" => $obj["etag"],
379 "size" => IntVal($obj["size"]),
386 * Returns information from a single calendar object, based on it's object
389 * The returned array must have the same keys as getCalendarObjects. The
390 * 'calendardata' object is required here though, while it's not required
391 * for getCalendarObjects.
393 * @param string $calendarId
394 * @param string $objectUri
395 * @throws Sabre_DAV_Exception_NotFound
398 function getCalendarObject($calendarId, $objectUri)
400 $o = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'",
401 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
403 $o[0]["calendarid"] = $calendarId;
404 $o[0]["calendardata"] = str_ireplace("Europe/Belgrade", "Europe/Berlin", $o[0]["calendardata"]);
406 } else throw new Sabre_DAV_Exception_NotFound($calendarId . " / " . $objectUri);
410 * Creates a new calendar object.
412 * It is possible return an etag from this function, which will be used in
413 * the response to this PUT request. Note that the ETag must be surrounded
416 * However, you should only really return this ETag if you don't mangle the
417 * calendar-data. If the result of a subsequent GET to this object is not
418 * the exact same as this request body, you should omit the ETag.
420 * @param mixed $calendarId
421 * @param string $objectUri
422 * @param string $calendarData
423 * @return string|null
425 function createCalendarObject($calendarId, $objectUri, $calendarData)
428 $calendarData = icalendar_sanitize_string($calendarData);
430 $extraData = $this->getDenormalizedData($calendarData);
432 q("INSERT INTO %s%scalendarobjects (`calendar_id`, `uri`, `calendardata`, `lastmodified`, `componentType`, `firstOccurence`, `lastOccurence`, `etag`, `size`)
433 VALUES (%d, '%s', '%s', NOW(), '%s', '%s', '%s', '%s', %d)",
434 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri), addslashes($calendarData), dbesc($extraData['componentType']),
435 dbesc(wdcal_php2MySqlTime($extraData['firstOccurence'])), dbesc(wdcal_php2MySqlTime($extraData['lastOccurence'])), dbesc($extraData["etag"]), IntVal($extraData["size"])
438 $this->increaseCalendarCtag($calendarId);
439 renderCalDavEntry_uri($objectUri);
441 return '"' . $extraData['etag'] . '"';
445 * Updates an existing calendarobject, based on it's uri.
447 * It is possible return an etag from this function, which will be used in
448 * the response to this PUT request. Note that the ETag must be surrounded
451 * However, you should only really return this ETag if you don't mangle the
452 * calendar-data. If the result of a subsequent GET to this object is not
453 * the exact same as this request body, you should omit the ETag.
455 * @param mixed $calendarId
456 * @param string $objectUri
457 * @param string $calendarData
458 * @return string|null
460 function updateCalendarObject($calendarId, $objectUri, $calendarData)
462 $calendarData = icalendar_sanitize_string($calendarData);
464 $extraData = $this->getDenormalizedData($calendarData);
466 q("UPDATE %s%scalendarobjects SET `calendardata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `componentType` = '%s', `firstOccurence` = '%s', `lastOccurence` = '%s'
467 WHERE `calendar_id` = %d AND `uri` = '%s'",
468 CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($calendarData), dbesc($extraData["etag"]), IntVal($extraData["size"]), dbesc($extraData["componentType"]),
469 dbesc(wdcal_php2MySqlTime($extraData["firstOccurence"])), dbesc(wdcal_php2MySqlTime($extraData["lastOccurence"])), IntVal($calendarId), dbesc($objectUri));
471 $this->increaseCalendarCtag($calendarId);
472 renderCalDavEntry_uri($objectUri);
474 return '"' . $extraData['etag'] . '"';
478 * Deletes an existing calendar object.
480 * @param string $calendarId
481 * @param string $objectUri
482 * @throws Sabre_DAV_Exception_NotFound
485 function deleteCalendarObject($calendarId, $objectUri)
487 $r = q("SELECT `id` FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
488 if (count($r) == 0) throw new Sabre_DAV_Exception_NotFound();
490 q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
492 $this->increaseCalendarCtag($calendarId);
493 renderCalDavEntry_calobj_id($r[0]["id"]);