]> git.mxchange.org Git - friendica-addons.git/blob - dav/common/dav_caldav_backend_private.inc.php
Merge pull request #73 from CatoTH/master
[friendica-addons.git] / dav / common / dav_caldav_backend_private.inc.php
1 <?php
2
3 class Sabre_CalDAV_Backend_Private extends Sabre_CalDAV_Backend_Common
4 {
5
6
7         /**
8          * @var null|Sabre_CalDAV_Backend_Private
9          */
10         private static $instance = null;
11
12         /**
13          * @static
14          * @return Sabre_CalDAV_Backend_Private
15          */
16         public static function getInstance()
17         {
18                 if (self::$instance == null) {
19                         self::$instance = new Sabre_CalDAV_Backend_Private();
20                 }
21                 return self::$instance;
22         }
23
24
25         /**
26          * @return int
27          */
28         public function getNamespace()
29         {
30                 return CALDAV_NAMESPACE_PRIVATE;
31         }
32
33         /**
34          * @static
35          * @return string
36          */
37         public static function getBackendTypeName()
38         {
39                 return t("Private Events");
40         }
41
42         /**
43          * @obsolete
44          * @param array $calendar
45          * @param int $user
46          * @return array
47          */
48         public function getPermissionsCalendar($calendar, $user)
49         {
50                 if ($calendar["namespace"] == CALDAV_NAMESPACE_PRIVATE && $user == $calendar["namespace_id"]) return array("read"=> true, "write"=> true);
51                 return array("read"=> false, "write"=> false);
52         }
53
54         /**
55          * @obsolete
56          * @param array $calendar
57          * @param int $user
58          * @param string $calendarobject_id
59          * @param null|array $item_arr
60          * @return array
61          */
62         public function getPermissionsItem($calendar, $user, $calendarobject_id, $item_arr = null)
63         {
64                 return $this->getPermissionsCalendar($calendar, $user);
65         }
66
67
68         /**
69          * @param array $row
70          * @param array $calendar
71          * @param string $base_path
72          * @return array
73          */
74         private function jqcal2wdcal($row, $calendar, $base_path)
75         {
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"])
78                 );
79                 $editable = $this->getPermissionsItem($calendar["namespace_id"], $row["calendarobject_id"], $row);
80
81                 $end = wdcal_mySql2PhpTime($row["EndTime"]);
82                 if ($row["IsAllDayEvent"]) $end -= 1;
83
84                 return array(
85                         "jq_id"             => $row["id"],
86                         "ev_id"             => $row["calendarobject_id"],
87                         "summary"           => escape_tags($row["Summary"]),
88                         "start"             => wdcal_mySql2PhpTime($row["StartTime"]),
89                         "end"               => $end,
90                         "is_allday"         => $row["IsAllDayEvent"],
91                         "is_moredays"       => 0,
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),
96                         "location"          => "Loc.",
97                         "attendees"         => '',
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"      => "",
102                 );
103         }
104
105         /**
106          * @param int $calendarId
107          * @param string $sd
108          * @param string $ed
109          * @param string $base_path
110          * @return array
111          */
112         public function listItemsByRange($calendarId, $sd, $ed, $base_path)
113         {
114                 $calendar       = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId);
115                 $von            = wdcal_php2MySqlTime($sd);
116                 $bis            = wdcal_php2MySqlTime($ed);
117                 $timezoneOffset = date("P");
118
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));
123
124                 $events = array();
125                 foreach ($evs as $row) $events[] = $this->jqcal2wdcal($row, $calendar, $base_path . $row["calendar_id"] . "/");
126
127                 return $events;
128         }
129
130
131         /**
132          * @param int $calendar_id
133          * @param int $calendarobject_id
134          * @return string
135          */
136         public function getItemDetailRedirect($calendar_id, $calendarobject_id)
137         {
138                 return "/dav/wdcal/$calendar_id/$calendarobject_id/edit/";
139         }
140
141         /**
142          * Returns a list of calendars for a principal.
143          *
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
148          *    accessed.
149          *  * principaluri. The owner of the calendar. Almost always the same as
150          *    principalUri passed to this method.
151          *
152          * Furthermore it can contain webdav properties in clark notation. A very
153          * common one is '{DAV:}displayname'.
154          *
155          * @param string $principalUri
156          * @throws DAVVersionMismatchException
157          * @return array
158          */
159         public function getCalendarsForUser($principalUri)
160         {
161                 $n = dav_compat_principal2namespace($principalUri);
162                 if ($n["namespace"] != $this->getNamespace()) return array();
163
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"]));
165                 $ret  = array();
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;
169
170                         $components = array();
171                         if ($cal["has_vevent"]) $components[] = "VEVENT";
172                         if ($cal["has_vtodo"]) $components[] = "VTODO";
173
174                         $dat = array(
175                                 "id"                                                                       => $cal["id"],
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",
181                         );
182                         foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field];
183
184                         $ret[] = $dat;
185                 }
186
187                 return $ret;
188         }
189
190
191         /**
192          * Creates a new calendar for a principal.
193          *
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.
196          *
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
202          */
203         public function createCalendar($principalUri, $calendarUri, array $properties)
204         {
205
206                 $uid = dav_compat_principal2uid($principalUri);
207
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");
210
211                 $keys = array("`namespace`", "`namespace_id`", "`ctag`", "`uri`");
212                 $vals = array(CALDAV_NAMESPACE_PRIVATE, IntVal($uid), 1, "'" . dbesc($calendarUri) . "'");
213
214                 // Default value
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');
220                         }
221                         $v          = $properties[$sccs]->getValue();
222                         $has_vevent = $has_vtodo = 0;
223                         foreach ($v as $w) {
224                                 if (mb_strtolower($w) == "vevent") $has_vevent = 1;
225                                 if (mb_strtolower($w) == "vtodo") $has_vtodo = 1;
226                         }
227                 }
228                 $keys[] = "`has_vevent`";
229                 $keys[] = "`has_vtodo`";
230                 $vals[] = $has_vevent;
231                 $vals[] = $has_vtodo;
232
233                 foreach ($this->propertyMap as $xmlName=> $dbName) {
234                         if (isset($properties[$xmlName])) {
235                                 $keys[] = "`$dbName`";
236                                 $vals[] = "'" . dbesc($properties[$xmlName]) . "'";
237                         }
238                 }
239
240                 $sql = sprintf("INSERT INTO %s%scalendars (" . implode(', ', $keys) . ") VALUES (" . implode(', ', $vals) . ")", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
241
242                 q($sql);
243
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
246                 );
247                 return $x[0]["id"];
248
249         }
250
251         /**
252          * Updates properties for a calendar.
253          *
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.
257          *
258          * This method must be atomic. If one property cannot be changed, the
259          * entire operation must fail.
260          *
261          * If the operation was successful, true can be returned.
262          * If the operation failed, false can be returned.
263          *
264          * Deletion of a non-existent property is always successful.
265          *
266          * Lastly, it is optional to return detailed information about any
267          * failures. In this case an array should be returned with the following
268          * structure:
269          *
270          * array(
271          *   403 => array(
272          *      '{DAV:}displayname' => null,
273          *   ),
274          *   424 => array(
275          *      '{DAV:}owner' => null,
276          *   )
277          * )
278          *
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.
282          *
283          * @param string $calendarId
284          * @param array $mutations
285          * @return bool|array
286          */
287         public function updateCalendar($calendarId, array $mutations)
288         {
289
290                 $newValues = array();
291                 $result    = array(
292                         200 => array(), // Ok
293                         403 => array(), // Forbidden
294                         424 => array(), // Failed Dependency
295                 );
296
297                 $hasError = false;
298
299                 foreach ($mutations as $propertyName=> $propertyValue) {
300
301                         // We don't know about this property.
302                         if (!isset($this->propertyMap[$propertyName])) {
303                                 $hasError                   = true;
304                                 $result[403][$propertyName] = null;
305                                 unset($mutations[$propertyName]);
306                                 continue;
307                         }
308
309                         $fieldName             = $this->propertyMap[$propertyName];
310                         $newValues[$fieldName] = $propertyValue;
311
312                 }
313
314                 // If there were any errors we need to fail the request
315                 if ($hasError) {
316                         // Properties has the remaining properties
317                         foreach ($mutations as $propertyName=> $propertyValue) {
318                                 $result[424][$propertyName] = null;
319                         }
320
321                         // Removing unused statuscodes for cleanliness
322                         foreach ($result as $status=> $properties) {
323                                 if (is_array($properties) && count($properties) === 0) unset($result[$status]);
324                         }
325
326                         return $result;
327
328                 }
329
330                 $sql = "`ctag` = `ctag` + 1";
331                 foreach ($newValues as $key=> $val) $sql .= ", `" . $key . "` = '" . dbesc($val) . "'";
332
333                 $sql = sprintf("UPDATE %s%scalendars SET $sql WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
334
335                 q($sql);
336
337                 return true;
338
339         }
340
341
342         /**
343          * Delete a calendar and all it's objects
344          *
345          * @param string $calendarId
346          * @return void
347          */
348         public function deleteCalendar($calendarId)
349         {
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));
352
353         }
354
355
356         /**
357          * Returns all calendar objects within a calendar.
358          *
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.:
365          *   '  "abcdef"')
366          *   * calendarid - The calendarid as it was passed to this function.
367          *   * size - The size of the calendar objects, in bytes.
368          *
369          * Note that the etag is optional, but it's highly encouraged to return for
370          * speed reasons.
371          *
372          * The calendardata is also optional. If it's not returned
373          * 'getCalendarObject' will be called later, which *is* expected to return
374          * calendardata.
375          *
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.
379          *
380          * @param mixed $calendarId
381          * @return array
382          */
383         function getCalendarObjects($calendarId)
384         {
385                 $objs = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
386                 $ret  = array();
387                 foreach ($objs as $obj) {
388                         $ret[] = array(
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"]),
396                         );
397                 }
398                 return $ret;
399         }
400
401         /**
402          * Returns information from a single calendar object, based on it's object
403          * uri.
404          *
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.
408          *
409          * @param string $calendarId
410          * @param string $objectUri
411          * @throws Sabre_DAV_Exception_NotFound
412          * @return array
413          */
414         function getCalendarObject($calendarId, $objectUri)
415         {
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));
418                 if (count($o) > 0) {
419                         $o[0]["calendarid"]   = $calendarId;
420                         $o[0]["calendardata"] = str_ireplace("Europe/Belgrade", "Europe/Berlin", $o[0]["calendardata"]);
421                         return $o[0];
422                 } else throw new Sabre_DAV_Exception_NotFound($calendarId . " / " . $objectUri);
423         }
424
425         /**
426          * Creates a new calendar object.
427          *
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
430          * by double-quotes.
431          *
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.
435          *
436          * @param mixed $calendarId
437          * @param string $objectUri
438          * @param string $calendarData
439          * @return string|null
440          */
441         function createCalendarObject($calendarId, $objectUri, $calendarData)
442         {
443                 $calendarData = icalendar_sanitize_string($calendarData);
444
445                 $extraData = $this->getDenormalizedData($calendarData);
446
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"])
451                 );
452
453                 $this->increaseCalendarCtag($calendarId);
454                 renderCalDavEntry_uri($objectUri);
455
456                 return '"' . $extraData['etag'] . '"';
457         }
458
459         /**
460          * Updates an existing calendarobject, based on it's uri.
461          *
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
464          * by double-quotes.
465          *
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.
469          *
470          * @param mixed $calendarId
471          * @param string $objectUri
472          * @param string $calendarData
473          * @return string|null
474          */
475         function updateCalendarObject($calendarId, $objectUri, $calendarData)
476         {
477                 $calendarData = icalendar_sanitize_string($calendarData);
478
479                 $extraData = $this->getDenormalizedData($calendarData);
480
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));
485
486                 $this->increaseCalendarCtag($calendarId);
487                 renderCalDavEntry_uri($objectUri);
488
489                 return '"' . $extraData['etag'] . '"';
490         }
491
492         /**
493          * Deletes an existing calendar object.
494          *
495          * @param string $calendarId
496          * @param string $objectUri
497          * @throws Sabre_DAV_Exception_NotFound
498          * @return void
499          */
500         function deleteCalendarObject($calendarId, $objectUri)
501         {
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();
504
505                 q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
506
507                 $this->increaseCalendarCtag($calendarId);
508                 renderCalDavEntry_calobj_id($r[0]["id"]);
509         }
510 }