]> git.mxchange.org Git - friendica-addons.git/blob - dav/common/dav_caldav_backend_private.inc.php
Notifications by E-Mail implemented
[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                 return t("Private Events");
39         }
40
41         /**
42          * @obsolete
43          * @param array $calendar
44          * @param int $user
45          * @return array
46          */
47         public function getPermissionsCalendar($calendar, $user)
48         {
49                 if ($calendar["namespace"] == CALDAV_NAMESPACE_PRIVATE && $user == $calendar["namespace_id"]) return array("read"=> true, "write"=> true);
50                 return array("read"=> false, "write"=> false);
51         }
52
53         /**
54          * @obsolete
55          * @param array $calendar
56          * @param int $user
57          * @param string $calendarobject_id
58          * @param null|array $item_arr
59          * @return array
60          */
61         public function getPermissionsItem($calendar, $user, $calendarobject_id, $item_arr = null)
62         {
63                 return $this->getPermissionsCalendar($calendar, $user);
64         }
65
66
67         /**
68          * @param array $row
69          * @param array $calendar
70          * @param string $base_path
71          * @return array
72          */
73         private function jqcal2wdcal($row, $calendar, $base_path)
74         {
75                 $not      = q("SELECT COUNT(*) num FROM %s%snotifications WHERE `calendar_id` = %d AND `calendarobject_id` = %d",
76                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($row["calendar_id"]), IntVal($row["calendarobject_id"])
77                 );
78                 $editable = $this->getPermissionsItem($calendar["namespace_id"], $row["calendarobject_id"], $row);
79
80                 $end = wdcal_mySql2PhpTime($row["EndTime"]);
81                 if ($row["IsAllDayEvent"]) $end -= 1;
82
83                 return array(
84                         "jq_id"             => $row["id"],
85                         "ev_id"             => $row["calendarobject_id"],
86                         "summary"           => escape_tags($row["Summary"]),
87                         "start"             => wdcal_mySql2PhpTime($row["StartTime"]),
88                         "end"               => $end,
89                         "is_allday"         => $row["IsAllDayEvent"],
90                         "is_moredays"       => 0,
91                         "is_recurring"      => $row["IsRecurring"],
92                         "color"             => (is_null($row["Color"]) || $row["Color"] == "" ? $calendar["calendarcolor"] : $row["Color"]),
93                         "is_editable"       => ($editable ? 1 : 0),
94                         "is_editable_quick" => ($editable && !$row["IsRecurring"] ? 1 : 0),
95                         "location"          => "Loc.",
96                         "attendees"         => '',
97                         "has_notification"  => ($not[0]["num"] > 0 ? 1 : 0),
98                         "url_detail"        => $base_path . $row["calendarobject_id"] . "/",
99                         "url_edit"          => $base_path . $row["calendarobject_id"] . "/edit/",
100                         "special_type"      => "",
101                 );
102         }
103
104         /**
105          * @param int $calendarId
106          * @param string $sd
107          * @param string $ed
108          * @param string $base_path
109          * @return array
110          */
111         public function listItemsByRange($calendarId, $sd, $ed, $base_path)
112         {
113                 $calendar = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId);
114                 $von      = wdcal_php2MySqlTime($sd);
115                 $bis      = wdcal_php2MySqlTime($ed);
116                 $timezoneOffset = date("P");
117
118                 // @TODO Events, die früher angefangen haben, aber noch andauern
119                 $evs = q("SELECT *, CONVERT_TZ(`StartTime`, @@session.time_zone, '$timezoneOffset') StartTime, CONVERT_TZ(`EndTime`, @@session.time_zone, '$timezoneOffset') EndTime
120                         FROM %s%sjqcalendar WHERE `calendar_id` = %d AND `StartTime` between '%s' and '%s'",
121                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($von), dbesc($bis));
122
123                 $events = array();
124                 foreach ($evs as $row) $events[] = $this->jqcal2wdcal($row, $calendar, $base_path . $row["calendar_id"] . "/");
125
126                 return $events;
127         }
128
129
130         /**
131          * @param int $calendar_id
132          * @param int $calendarobject_id
133          * @return string
134          */
135         public function getItemDetailRedirect($calendar_id, $calendarobject_id)
136         {
137                 return "/dav/wdcal/$calendar_id/$calendarobject_id/edit/";
138         }
139
140         /**
141          * Returns a list of calendars for a principal.
142          *
143          * Every project is an array with the following keys:
144          *  * id, a unique id that will be used by other functions to modify the
145          *    calendar. This can be the same as the uri or a database key.
146          *  * uri, which the basename of the uri with which the calendar is
147          *    accessed.
148          *  * principaluri. The owner of the calendar. Almost always the same as
149          *    principalUri passed to this method.
150          *
151          * Furthermore it can contain webdav properties in clark notation. A very
152          * common one is '{DAV:}displayname'.
153          *
154          * @param string $principalUri
155          * @return array
156          */
157         public function getCalendarsForUser($principalUri)
158         {
159                 $n = dav_compat_principal2namespace($principalUri);
160                 if ($n["namespace"] != $this->getNamespace()) return array();
161
162                 $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"]));
163                 $ret  = array();
164                 foreach ($cals as $cal) {
165                         if (in_array($cal["uri"], $GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"])) continue;
166
167                         $dat = array(
168                                 "id"                                                      => $cal["id"],
169                                 "uri"                                                     => $cal["uri"],
170                                 "principaluri"                                            => $principalUri,
171                                 '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $cal['ctag'] ? $cal['ctag'] : '0',
172                                 "calendar_class"                                          => "Sabre_CalDAV_Calendar",
173                         );
174                         foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field];
175
176                         $ret[] = $dat;
177                 }
178
179                 return $ret;
180         }
181
182
183         /**
184          * Creates a new calendar for a principal.
185          *
186          * If the creation was a success, an id must be returned that can be used to reference
187          * this calendar in other methods, such as updateCalendar.
188          *
189          * @param string $principalUri
190          * @param string $calendarUri
191          * @param array $properties
192          * @throws Sabre_DAV_Exception
193          * @return string|void
194          */
195         public function createCalendar($principalUri, $calendarUri, array $properties)
196         {
197
198                 $uid = dav_compat_principal2uid($principalUri);
199
200                 $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));
201                 if (count($r) > 0) throw new Sabre_DAV_Exception("A calendar with this URI already exists");
202
203                 $keys = array("`namespace`", "`namespace_id`", "`ctag`", "`uri`");
204                 $vals = array(CALDAV_NAMESPACE_PRIVATE, IntVal($uid), 1, "'" . dbesc($calendarUri) . "'");
205
206                 // Default value
207                 $sccs       = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
208                 $has_vevent = $has_vtodo = 1;
209                 if (isset($properties[$sccs])) {
210                         if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) {
211                                 throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet');
212                         }
213                         $v          = $properties[$sccs]->getValue();
214                         $has_vevent = $has_vtodo = 0;
215                         foreach ($v as $w) {
216                                 if (mb_strtolower($w) == "vevent") $has_vevent = 1;
217                                 if (mb_strtolower($w) == "vtodo") $has_vtodo = 1;
218                         }
219                 }
220                 $keys[] = "`has_vevent`";
221                 $keys[] = "`has_vtodo`";
222                 $vals[] = $has_vevent;
223                 $vals[] = $has_vtodo;
224
225                 foreach ($this->propertyMap as $xmlName=> $dbName) {
226                         if (isset($properties[$xmlName])) {
227                                 $keys[] = "`$dbName`";
228                                 $vals[] = "'" . dbesc($properties[$xmlName]) . "'";
229                         }
230                 }
231
232                 $sql = sprintf("INSERT INTO %s%scalendars (" . implode(', ', $keys) . ") VALUES (" . implode(', ', $vals) . ")", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
233
234                 q($sql);
235
236                 $x = q("SELECT id FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
237                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, $uid, $calendarUri
238                 );
239                 return $x[0]["id"];
240
241         }
242
243         /**
244          * Updates properties for a calendar.
245          *
246          * The mutations array uses the propertyName in clark-notation as key,
247          * and the array value for the property value. In the case a property
248          * should be deleted, the property value will be null.
249          *
250          * This method must be atomic. If one property cannot be changed, the
251          * entire operation must fail.
252          *
253          * If the operation was successful, true can be returned.
254          * If the operation failed, false can be returned.
255          *
256          * Deletion of a non-existent property is always successful.
257          *
258          * Lastly, it is optional to return detailed information about any
259          * failures. In this case an array should be returned with the following
260          * structure:
261          *
262          * array(
263          *   403 => array(
264          *      '{DAV:}displayname' => null,
265          *   ),
266          *   424 => array(
267          *      '{DAV:}owner' => null,
268          *   )
269          * )
270          *
271          * In this example it was forbidden to update {DAV:}displayname.
272          * (403 Forbidden), which in turn also caused {DAV:}owner to fail
273          * (424 Failed Dependency) because the request needs to be atomic.
274          *
275          * @param string $calendarId
276          * @param array $mutations
277          * @return bool|array
278          */
279         public function updateCalendar($calendarId, array $mutations)
280         {
281
282                 $newValues = array();
283                 $result    = array(
284                         200 => array(), // Ok
285                         403 => array(), // Forbidden
286                         424 => array(), // Failed Dependency
287                 );
288
289                 $hasError = false;
290
291                 foreach ($mutations as $propertyName=> $propertyValue) {
292
293                         // We don't know about this property.
294                         if (!isset($this->propertyMap[$propertyName])) {
295                                 $hasError                   = true;
296                                 $result[403][$propertyName] = null;
297                                 unset($mutations[$propertyName]);
298                                 continue;
299                         }
300
301                         $fieldName             = $this->propertyMap[$propertyName];
302                         $newValues[$fieldName] = $propertyValue;
303
304                 }
305
306                 // If there were any errors we need to fail the request
307                 if ($hasError) {
308                         // Properties has the remaining properties
309                         foreach ($mutations as $propertyName=> $propertyValue) {
310                                 $result[424][$propertyName] = null;
311                         }
312
313                         // Removing unused statuscodes for cleanliness
314                         foreach ($result as $status=> $properties) {
315                                 if (is_array($properties) && count($properties) === 0) unset($result[$status]);
316                         }
317
318                         return $result;
319
320                 }
321
322                 $sql = "`ctag` = `ctag` + 1";
323                 foreach ($newValues as $key=> $val) $sql .= ", `" . $key . "` = '" . dbesc($val) . "'";
324
325                 $sql = sprintf("UPDATE %s%scalendars SET $sql WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
326
327                 q($sql);
328
329                 return true;
330
331         }
332
333
334         /**
335          * Delete a calendar and all it's objects
336          *
337          * @param string $calendarId
338          * @return void
339          */
340         public function deleteCalendar($calendarId)
341         {
342                 q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
343                 q("DELETE FROM %s%scalendars WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
344
345         }
346
347
348         /**
349          * Returns all calendar objects within a calendar.
350          *
351          * Every item contains an array with the following keys:
352          *   * id - unique identifier which will be used for subsequent updates
353          *   * calendardata - The iCalendar-compatible calendar data
354          *   * uri - a unique key which will be used to construct the uri. This can be any arbitrary string.
355          *   * lastmodified - a timestamp of the last modification time
356          *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
357          *   '  "abcdef"')
358          *   * calendarid - The calendarid as it was passed to this function.
359          *   * size - The size of the calendar objects, in bytes.
360          *
361          * Note that the etag is optional, but it's highly encouraged to return for
362          * speed reasons.
363          *
364          * The calendardata is also optional. If it's not returned
365          * 'getCalendarObject' will be called later, which *is* expected to return
366          * calendardata.
367          *
368          * If neither etag or size are specified, the calendardata will be
369          * used/fetched to determine these numbers. If both are specified the
370          * amount of times this is needed is reduced by a great degree.
371          *
372          * @param mixed $calendarId
373          * @return array
374          */
375         function getCalendarObjects($calendarId)
376         {
377                 $objs = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId));
378                 $ret  = array();
379                 foreach ($objs as $obj) {
380                         $ret[] = array(
381                                 "id"           => IntVal($obj["id"]),
382                                 "calendardata" => $obj["calendardata"],
383                                 "uri"          => $obj["uri"],
384                                 "lastmodified" => $obj["lastmodified"],
385                                 "calendarid"   => $calendarId,
386                                 "etag"         => $obj["etag"],
387                                 "size"         => IntVal($obj["size"]),
388                         );
389                 }
390                 return $ret;
391         }
392
393         /**
394          * Returns information from a single calendar object, based on it's object
395          * uri.
396          *
397          * The returned array must have the same keys as getCalendarObjects. The
398          * 'calendardata' object is required here though, while it's not required
399          * for getCalendarObjects.
400          *
401          * @param string $calendarId
402          * @param string $objectUri
403          * @throws Sabre_DAV_Exception_NotFound
404          * @return array
405          */
406         function getCalendarObject($calendarId, $objectUri)
407         {
408                 $o = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'",
409                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
410                 if (count($o) > 0) {
411                         $o[0]["calendarid"]   = $calendarId;
412                         $o[0]["calendardata"] = str_ireplace("Europe/Belgrade", "Europe/Berlin", $o[0]["calendardata"]);
413                         return $o[0];
414                 } else throw new Sabre_DAV_Exception_NotFound($calendarId . " / " . $objectUri);
415         }
416
417         /**
418          * Creates a new calendar object.
419          *
420          * It is possible return an etag from this function, which will be used in
421          * the response to this PUT request. Note that the ETag must be surrounded
422          * by double-quotes.
423          *
424          * However, you should only really return this ETag if you don't mangle the
425          * calendar-data. If the result of a subsequent GET to this object is not
426          * the exact same as this request body, you should omit the ETag.
427          *
428          * @param mixed $calendarId
429          * @param string $objectUri
430          * @param string $calendarData
431          * @return string|null
432          */
433         function createCalendarObject($calendarId, $objectUri, $calendarData)
434         {
435                 $calendarData = icalendar_sanitize_string($calendarData);
436
437                 $extraData = $this->getDenormalizedData($calendarData);
438
439                 q("INSERT INTO %s%scalendarobjects (`calendar_id`, `uri`, `calendardata`, `lastmodified`, `componentType`, `firstOccurence`, `lastOccurence`, `etag`, `size`)
440                         VALUES (%d, '%s', '%s', NOW(), '%s', '%s', '%s', '%s', %d)",
441                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri), addslashes($calendarData), dbesc($extraData['componentType']),
442                         dbesc(wdcal_php2MySqlTime($extraData['firstOccurence'])), dbesc(wdcal_php2MySqlTime($extraData['lastOccurence'])), dbesc($extraData["etag"]), IntVal($extraData["size"])
443                 );
444
445                 $this->increaseCalendarCtag($calendarId);
446                 renderCalDavEntry_uri($objectUri);
447
448                 return '"' . $extraData['etag'] . '"';
449         }
450
451         /**
452          * Updates an existing calendarobject, based on it's uri.
453          *
454          * It is possible return an etag from this function, which will be used in
455          * the response to this PUT request. Note that the ETag must be surrounded
456          * by double-quotes.
457          *
458          * However, you should only really return this ETag if you don't mangle the
459          * calendar-data. If the result of a subsequent GET to this object is not
460          * the exact same as this request body, you should omit the ETag.
461          *
462          * @param mixed $calendarId
463          * @param string $objectUri
464          * @param string $calendarData
465          * @return string|null
466          */
467         function updateCalendarObject($calendarId, $objectUri, $calendarData)
468         {
469                 $calendarData = icalendar_sanitize_string($calendarData);
470
471                 $extraData = $this->getDenormalizedData($calendarData);
472
473                 q("UPDATE %s%scalendarobjects SET `calendardata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `componentType` = '%s', `firstOccurence` = '%s', `lastOccurence` = '%s'
474                         WHERE `calendar_id` = %d AND `uri` = '%s'",
475                         CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($calendarData), dbesc($extraData["etag"]), IntVal($extraData["size"]), dbesc($extraData["componentType"]),
476                         dbesc(wdcal_php2MySqlTime($extraData["firstOccurence"])), dbesc(wdcal_php2MySqlTime($extraData["lastOccurence"])), IntVal($calendarId), dbesc($objectUri));
477
478                 $this->increaseCalendarCtag($calendarId);
479                 renderCalDavEntry_uri($objectUri);
480
481                 return '"' . $extraData['etag'] . '"';
482         }
483
484         /**
485          * Deletes an existing calendar object.
486          *
487          * @param string $calendarId
488          * @param string $objectUri
489          * @throws Sabre_DAV_Exception_NotFound
490          * @return void
491          */
492         function deleteCalendarObject($calendarId, $objectUri)
493         {
494                 $r = q("SELECT `id` FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
495                 if (count($r) == 0) throw new Sabre_DAV_Exception_NotFound();
496
497                 q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri));
498
499                 $this->increaseCalendarCtag($calendarId);
500                 renderCalDavEntry_calobj_id($r[0]["id"]);
501         }
502 }