]> git.mxchange.org Git - friendica-addons.git/commitdiff
More refactoring, mainly of the addressbook/VCARD-part
authorTobias Hößl <tobias@hoessl.eu>
Thu, 2 Aug 2012 20:26:52 +0000 (20:26 +0000)
committerTobias Hößl <tobias@hoessl.eu>
Thu, 2 Aug 2012 20:26:52 +0000 (20:26 +0000)
13 files changed:
dav/calendar.friendica.fnk.php
dav/common/calendar.fnk.php
dav/common/dav_caldav_backend_private.inc.php
dav/common/dav_caldav_calendar_private.inc.php [new file with mode: 0644]
dav/common/dav_carddav_backend_common.inc.php [new file with mode: 0644]
dav/common/dav_carddav_backend_private.inc.php [new file with mode: 0644]
dav/common/dav_carddav_backend_std.inc.php [deleted file]
dav/common/dav_carddav_backend_virtual.inc.php [new file with mode: 0644]
dav/common/dav_user_calendars.inc.php
dav/database-init.inc.php
dav/dav_caldav_backend_virtual_friendica.inc.php
dav/dav_carddav_backend_virtual_friendica.inc.php
dav/main.php

index 7019cb500bbee6e8d58a117dd1c45eb6c7fcd4d2..60dd9c6bd190a4e9f97ad5570218398d4a4405a4 100644 (file)
@@ -13,16 +13,18 @@ define("CALDAV_URL_PREFIX", $path . "dav/");
 define("DAV_APPNAME", "Friendica");
 
 define("CALDAV_NAMESPACE_PRIVATE", 1);
-
 define("CALDAV_FRIENDICA_MINE", "friendica-mine");
 define("CALDAV_FRIENDICA_CONTACTS", "friendica-contacts");
 
 $GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"] = array(CALDAV_FRIENDICA_MINE, CALDAV_FRIENDICA_CONTACTS);
 $GLOBALS["CALDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CalDAV_Backend_Friendica");
 
-define("CARDDAV_NAMESPACE_COMMUNITYCONTACTS", 1);
-define("CARDDAV_NAMESPACE_PHONECONTACTS", 2);
-$GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CardDAV_Backend_FriendicaCommunity");
+define("CARDDAV_NAMESPACE_PRIVATE", 1);
+define("CARDDAV_FRIENDICA_CONTACT", "friendica");
+$GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"] = array(CARDDAV_FRIENDICA_CONTACT);
+$GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CardDAV_Backend_Friendica");
+
+$GLOBALS["CALDAV_ACL_PLUGIN_CLASS"] = "Sabre_DAVACL_Plugin_Friendica";
 
 define("CALDAV_MAX_YEAR", date("Y") + 5);
 
@@ -229,3 +231,44 @@ function wdcal_create_std_calendars()
        $stms = wdcal_create_std_calendars_get_statements($a->user["uid"]);
        foreach ($stms as $stmt) q($stmt);
 }
+
+
+
+
+/**
+ * @param int $user_id
+ * @param bool $withcheck
+ * @return array
+ */
+function wdcal_create_std_addressbooks_get_statements($user_id, $withcheck = true)
+{
+       $stms = array();
+       $a = get_app();
+       $uris = array(
+               'private'                 => t("Private Addresses"),
+               CARDDAV_FRIENDICA_CONTACT     => t("Friendica Contacts"),
+       );
+       foreach ($uris as $uri => $name) {
+               $cals = q("SELECT * FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
+                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, IntVal($user_id), dbesc($uri));
+               if (count($cals) == 0 || !$withcheck) $stms[] =
+                       sprintf("INSERT INTO %s%saddressbooks (`namespace`, `namespace_id`, `displayname`, `ctag`, `uri`)
+                               VALUES (%d, %d, '%s', 1, '%s')",
+                               CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($user_id), dbesc($name), dbesc($uri));
+       }
+       return $stms;
+}
+
+/**
+ */
+function wdcal_create_std_addressbooks()
+{
+       $a = get_app();
+       if (!local_user()) return;
+
+       $privates = q("SELECT COUNT(*) num FROM %s%addressbooks WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($a->user["uid"]));
+       if ($privates[0]["num"] > 0) return;
+
+       $stms = wdcal_create_std_addressbooks_get_statements($a->user["uid"]);
+       foreach ($stms as $stmt) q($stmt);
+}
index 10d88833d0b2b51b1df70676ed0da07df5a371fd..14951119158b927df0d3b437add3aad5c86094f8 100644 (file)
@@ -249,6 +249,11 @@ function dav_create_server($force_authentication = false, $needs_caldav = true,
                $server->addPlugin($carddavPlugin);
        }
 
+       $aclPlugin                      = new $GLOBALS["CALDAV_ACL_PLUGIN_CLASS"]();
+       $aclPlugin->defaultUsernamePath = "principals/users";
+       $server->addPlugin($aclPlugin);
+
+
        if ($force_authentication) $server->broadcastEvent('beforeMethod', array("GET", "/")); // Make it authenticate
 
        return $server;
@@ -275,7 +280,7 @@ function dav_get_current_user_calendars(&$server, $with_privilege = "")
        $calendars = array();
        /** @var Sabre_DAVACL_Plugin $aclplugin  */
        $aclplugin = $server->getPlugin("acl");
-       foreach ($children as $child) if (is_a($child, "Sabre_CalDAV_Calendar")) {
+       foreach ($children as $child) if (is_a($child, "Sabre_CalDAV_Calendar") || is_subclass_of($child, "Sabre_CalDAV_Calendar")) {
                if ($with_privilege != "") {
                        $caluri = $calendar_path . $child->getName();
                        if ($aclplugin->checkPrivileges($caluri, $with_privilege, Sabre_DAVACL_Plugin::R_PARENT, false)) $calendars[] = $child;
index 5356280a42c225a98797836306aafb272dfd1b0d..1eb3b3656c7b76684afa9972209722dc09af9f63 100644 (file)
@@ -177,7 +177,7 @@ class Sabre_CalDAV_Backend_Private extends Sabre_CalDAV_Backend_Common
                                "principaluri"                                                             => $principalUri,
                                '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag'                  => $cal['ctag'] ? $cal['ctag'] : '0',
                                '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components),
-                               "calendar_class"                                                           => "Sabre_CalDAV_Calendar",
+                               "calendar_class"                                                           => "Sabre_CalDAV_Calendar_Private",
                        );
                        foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field];
 
diff --git a/dav/common/dav_caldav_calendar_private.inc.php b/dav/common/dav_caldav_calendar_private.inc.php
new file mode 100644 (file)
index 0000000..65f7c2b
--- /dev/null
@@ -0,0 +1,50 @@
+<?php
+
+
+class Sabre_CalDAV_Calendar_Private extends Sabre_CalDAV_Calendar
+{
+
+       public function getACL()
+       {
+
+               return array(
+                       array(
+                               'privilege' => '{DAV:}read',
+                               'principal' => $this->calendarInfo['principaluri'],
+                               'protected' => true,
+                       ),
+                       array(
+                               'privilege' => '{DAV:}write',
+                               'principal' => $this->calendarInfo['principaluri'],
+                               'protected' => true,
+                       ),
+                       /*
+                       array(
+                               'privilege' => '{DAV:}read',
+                               'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write',
+                               'protected' => true,
+                       ),
+                       array(
+                               'privilege' => '{DAV:}write',
+                               'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write',
+                               'protected' => true,
+                       ),
+                       array(
+                               'privilege' => '{DAV:}read',
+                               'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read',
+                               'protected' => true,
+                       ),
+                       array(
+                               'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy',
+                               'principal' => '{DAV:}authenticated',
+                               'protected' => true,
+                       ),
+                       */
+
+               );
+
+       }
+
+
+
+}
\ No newline at end of file
diff --git a/dav/common/dav_carddav_backend_common.inc.php b/dav/common/dav_carddav_backend_common.inc.php
new file mode 100644 (file)
index 0000000..4279f8a
--- /dev/null
@@ -0,0 +1,116 @@
+<?php
+
+abstract class Sabre_CardDAV_Backend_Common extends Sabre_CardDAV_Backend_Abstract
+{
+       /**
+        * @abstract
+        * @return int
+        */
+       abstract public function getNamespace();
+
+       /**
+        * @static
+        * @abstract
+        * @return string
+        */
+       abstract public static function getBackendTypeName();
+
+       /**
+        * @var array
+        */
+       static private $addressbookCache = array();
+
+       /**
+        * @var array
+        */
+       static private $addressbookObjectCache = array();
+
+       /**
+        * @static
+        * @param int $addressbookId
+        * @return array
+        */
+       static public function loadCalendarById($addressbookId)
+       {
+               if (!isset(self::$addressbookCache[$addressbookId])) {
+                       $c                                = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
+                       self::$addressbookCache[$addressbookId] = $c[0];
+               }
+               return self::$addressbookCache[$addressbookId];
+       }
+
+       /**
+        * @static
+        * @param int $obj_id
+        * @return array
+        */
+       static public function loadAddressbookobjectById($obj_id)
+       {
+               if (!isset(self::$addressbookObjectCache[$obj_id])) {
+                       $o                                  = q("SELECT * FROM %s%saddressbookobjects WHERE `id` = %d",
+                               CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($obj_id)
+                       );
+                       self::$addressbookObjectCache[$obj_id] = $o[0];
+               }
+               return self::$addressbookObjectCache[$obj_id];
+       }
+
+
+       /**
+        * Updates an addressbook's properties
+        *
+        * See Sabre_DAV_IProperties for a description of the mutations array, as
+        * well as the return value.
+        *
+        * @param mixed $addressBookId
+        * @param array $mutations
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @see Sabre_DAV_IProperties::updateProperties
+        * @return bool|array
+        */
+       public function updateAddressBook($addressBookId, array $mutations)
+       {
+               $updates = array();
+
+               foreach ($mutations as $property=> $newValue) {
+
+                       switch ($property) {
+                               case '{DAV:}displayname' :
+                                       $updates['displayname'] = $newValue;
+                                       break;
+                               case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' :
+                                       $updates['description'] = $newValue;
+                                       break;
+                               default :
+                                       // If any unsupported values were being updated, we must
+                                       // let the entire request fail.
+                                       return false;
+                       }
+
+               }
+
+               // No values are being updated?
+               if (!$updates) {
+                       return false;
+               }
+
+               $query = 'UPDATE ' . CALDAV_SQL_DB . CALDAV_SQL_PREFIX . 'addressbooks SET ctag = ctag + 1 ';
+               foreach ($updates as $key=> $value) {
+                       $query .= ', `' . dbesc($key) . '` = ' . dbesc($key) . ' ';
+               }
+               $query .= ' WHERE id = ' . IntVal($addressBookId);
+               q($query);
+
+               return true;
+
+       }
+
+       /**
+        * @param int $addressbookId
+        */
+       protected function increaseAddressbookCtag($addressbookId)
+       {
+               q("UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = '%d'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
+               self::$addressbookCache = array();
+       }
+}
\ No newline at end of file
diff --git a/dav/common/dav_carddav_backend_private.inc.php b/dav/common/dav_carddav_backend_private.inc.php
new file mode 100644 (file)
index 0000000..71923b9
--- /dev/null
@@ -0,0 +1,275 @@
+<?php
+
+class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Common
+{
+
+       /**
+        * @var null|Sabre_CardDAV_Backend_Std
+        */
+       private static $instance = null;
+
+       /**
+        * @static
+        * @return Sabre_CardDAV_Backend_Std
+        */
+       public static function getInstance() {
+               if (self::$instance == null) {
+                       self::$instance = new Sabre_CardDAV_Backend_Std();
+               }
+               return self::$instance;
+       }
+
+
+       /**
+        * Sets up the object
+        */
+       public function __construct()
+       {
+
+       }
+
+
+       /**
+        * @return int
+        */
+       public function getNamespace()
+       {
+               return CARDDAV_NAMESPACE_PRIVATE;
+       }
+
+       /**
+        * @static
+        * @return string
+        */
+       public static function getBackendTypeName()
+       {
+               return t("Private Addressbooks");
+       }
+
+       /**
+        * Returns the list of addressbooks for a specific user.
+        *
+        * @param string $principalUri
+        * @return array
+        */
+       public function getAddressBooksForUser($principalUri)
+       {
+               $n = dav_compat_principal2namespace($principalUri);
+               if ($n["namespace"] != $this->getNamespace()) return array();
+
+               $addressBooks = array();
+
+               $books = q("SELECT * FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($n["namespace"]), IntVal($n["namespace_id"]));
+               foreach ($books as $row) {
+                       if (in_array($row["uri"], $GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"])) continue;
+
+                       $addressBooks[] = array(
+                               'id'                                                                => $row['id'],
+                               'uri'                                                               => $row['uri'],
+                               'principaluri'                                                      => $principalUri,
+                               '{DAV:}displayname'                                                 => $row['displayname'],
+                               '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
+                               '{http://calendarserver.org/ns/}getctag'                            => $row['ctag'],
+                               '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data'  =>
+                               new Sabre_CardDAV_Property_SupportedAddressData(),
+                       );
+               }
+
+               return $addressBooks;
+
+       }
+
+
+       /**
+        * Creates a new address book
+        *
+        * @param string $principalUri
+        * @param string $url Just the 'basename' of the url.
+        * @param array $properties
+        * @throws Sabre_DAV_Exception_BadRequest
+        * @return void
+        */
+       public function createAddressBook($principalUri, $url, array $properties)
+       {
+               $uid = dav_compat_principal2uid($principalUri);
+
+               $values = array(
+                       'displayname'  => null,
+                       'description'  => null,
+                       'principaluri' => $principalUri,
+                       'uri'          => $url,
+               );
+
+               foreach ($properties as $property=> $newValue) {
+
+                       switch ($property) {
+                               case '{DAV:}displayname' :
+                                       $values['displayname'] = $newValue;
+                                       break;
+                               case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' :
+                                       $values['description'] = $newValue;
+                                       break;
+                               default :
+                                       throw new Sabre_DAV_Exception_BadRequest('Unknown property: ' . $property);
+                       }
+
+               }
+
+               q("INSERT INTO %s%saddressbooks (`uri`, `displayname`, `description`, `namespace`, `namespace_id`, `ctag`) VALUES ('%s', '%s', '%s', %d, %d, 1)",
+                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($values["uri"]), dbesc($values["displayname"]), dbesc($values["description"]), CARDDAV_NAMESPACE_PRIVATE, IntVal($uid)
+               );
+       }
+
+       /**
+        * Deletes an entire addressbook and all its contents
+        *
+        * @param int $addressBookId
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return void
+        */
+       public function deleteAddressBook($addressBookId)
+       {
+               q("DELETE FROM %s%saddressbookobjects WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
+               q("DELETE FROM %s%saddressbooks WHERE `addressbook_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
+       }
+
+       /**
+        * Returns all cards for a specific addressbook id.
+        *
+        * This method should return the following properties for each card:
+        *   * carddata - raw vcard data
+        *   * uri - Some unique url
+        *   * lastmodified - A unix timestamp
+        *
+        * It's recommended to also return the following properties:
+        *   * etag - A unique etag. This must change every time the card changes.
+        *   * size - The size of the card in bytes.
+        *
+        * If these last two properties are provided, less time will be spent
+        * calculating them. If they are specified, you can also ommit carddata.
+        * This may speed up certain requests, especially with large cards.
+        *
+        * @param string $addressbookId
+        * @return array
+        */
+       public function getCards($addressbookId)
+       {
+               $r = q('SELECT `id`, `carddata`, `uri`, `lastmodified`, `etag`, `size`, `contact` FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `manually_deleted` = 0',
+                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId)
+               );
+               if ($r) return $r;
+               return array();
+       }
+
+       /**
+        * Returns a specfic card.
+        *
+        * The same set of properties must be returned as with getCards. The only
+        * exception is that 'carddata' is absolutely required.
+        *
+        * @param mixed $addressBookId
+        * @param string $cardUri
+        * @throws Sabre_DAV_Exception_NotFound
+        * @return array
+        */
+       public function getCard($addressBookId, $cardUri)
+       {
+               $x = q("SELECT `id`, `carddata`, `uri`, `lastmodified`, `etag`, `size` FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `uri` = '%s'",
+                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId), dbesc($cardUri));
+               if (count($x) == 0) throw new Sabre_DAV_Exception_NotFound();
+               return $x[0];
+       }
+
+       /**
+        * Creates a new card.
+        *
+        * The addressbook id will be passed as the first argument. This is the
+        * same id as it is returned from the getAddressbooksForUser method.
+        *
+        * The cardUri is a base uri, and doesn't include the full path. The
+        * cardData argument is the vcard body, and is passed as a string.
+        *
+        * It is possible to return an ETag from this method. This ETag is for the
+        * newly created resource, and must be enclosed with double quotes (that
+        * is, the string itself must contain the double quotes).
+        *
+        * You should only return the ETag if you store the carddata as-is. If a
+        * subsequent GET request on the same card does not have the same body,
+        * byte-by-byte and you did return an ETag here, clients tend to get
+        * confused.
+        *
+        * If you don't return an ETag, you can just return null.
+        *
+        * @param string $addressBookId
+        * @param string $cardUri
+        * @param string $cardData
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return string
+        */
+       public function createCard($addressBookId, $cardUri, $cardData)
+       {
+               $etag = md5($cardData);
+               q("INSERT INTO %s%saddressbookobjects (`carddata`, `uri`, `lastmodified`, `addressbook_id`, `etag`, `size`) VALUES ('%s', '%s', NOW(), %d, '%s', %d)",
+                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($cardUri), IntVal($addressBookId), dbesc($etag), strlen($cardData)
+               );
+
+               q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
+
+               return '"' . $etag . '"';
+
+       }
+
+       /**
+        * Updates a card.
+        *
+        * The addressbook id will be passed as the first argument. This is the
+        * same id as it is returned from the getAddressbooksForUser method.
+        *
+        * The cardUri is a base uri, and doesn't include the full path. The
+        * cardData argument is the vcard body, and is passed as a string.
+        *
+        * It is possible to return an ETag from this method. This ETag should
+        * match that of the updated resource, and must be enclosed with double
+        * quotes (that is: the string itself must contain the actual quotes).
+        *
+        * You should only return the ETag if you store the carddata as-is. If a
+        * subsequent GET request on the same card does not have the same body,
+        * byte-by-byte and you did return an ETag here, clients tend to get
+        * confused.
+        *
+        * If you don't return an ETag, you can just return null.
+        *
+        * @param string $addressBookId
+        * @param string $cardUri
+        * @param string $cardData
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return string|null
+        */
+       public function updateCard($addressBookId, $cardUri, $cardData)
+       {
+               $etag = md5($cardData);
+               q("UPDATE %s%saddressbookobjects SET `carddata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `manually_edited` = 1 WHERE `uri` = '%s' AND `addressbook_id` = %d",
+                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($etag), strlen($cardData), dbesc($cardUri), IntVal($addressBookId)
+               );
+
+               q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
+
+               return '"' . $etag . '"';
+       }
+
+       /**
+        * Deletes a card
+        *
+        * @param string $addressBookId
+        * @param string $cardUri
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return bool
+        */
+       public function deleteCard($addressBookId, $cardUri)
+       {
+               q("DELETE FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId), dbesc($cardUri));
+               q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
+
+               return true;
+       }
+}
diff --git a/dav/common/dav_carddav_backend_std.inc.php b/dav/common/dav_carddav_backend_std.inc.php
deleted file mode 100644 (file)
index e257d15..0000000
+++ /dev/null
@@ -1,330 +0,0 @@
-<?php
-
-/**
- * PDO CardDAV backend
- *
- * This CardDAV backend uses PDO to store addressbooks
- *
- * @package Sabre
- * @subpackage CardDAV
- * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
- * @author Evert Pot (http://www.rooftopsolutions.nl/)
- * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
- */
-class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
-{
-
-       /**
-        * @var null|Sabre_CardDAV_Backend_Std
-        */
-       private static $instance = null;
-
-       /**
-        * @static
-        * @return Sabre_CardDAV_Backend_Std
-        */
-       public static function getInstance() {
-               if (self::$instance == null) {
-                       self::$instance = new Sabre_CardDAV_Backend_Std();
-               }
-               return self::$instance;
-       }
-
-
-       /**
-        * Sets up the object
-        */
-       public function __construct()
-       {
-
-       }
-
-       /**
-        * Returns the list of addressbooks for a specific user.
-        *
-        * @param string $principalUri
-        * @return array
-        */
-       public function getAddressBooksForUser($principalUri)
-       {
-               $uid = dav_compat_principal2uid($principalUri);
-
-               $addressBooks = array();
-
-               $books = q("SELECT id, uri, displayname, principaluri, description, ctag FROM %s%saddressbooks_phone WHERE principaluri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($principalUri));
-               if (count($books) == 0) {
-                       q("INSERT INTO %s%saddressbooks_phone (uid, principaluri, displayname, uri, description, ctag) VALUES (%d, '%s', '%s', '%s', '%s', 1)",
-                               CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $uid, dbesc($principalUri), 'Other', 'phone', 'Manually added contacts'
-                       );
-                       $books = q("SELECT id, uri, displayname, principaluri, description, ctag FROM %s%saddressbooks_phone WHERE principaluri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($principalUri));
-               }
-               foreach ($books as $row) {
-                       $addressBooks[] = array(
-                               'id'                                                                => CARDDAV_NAMESPACE_PHONECONTACTS . "-" . $row['id'],
-                               'uri'                                                               => $row['uri'],
-                               'principaluri'                                                      => $row['principaluri'],
-                               '{DAV:}displayname'                                                 => $row['displayname'],
-                               '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
-                               '{http://calendarserver.org/ns/}getctag'                            => $row['ctag'],
-                               '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data'  =>
-                               new Sabre_CardDAV_Property_SupportedAddressData(),
-                       );
-               }
-
-               return $addressBooks;
-
-       }
-
-
-       /**
-        * Updates an addressbook's properties
-        *
-        * See Sabre_DAV_IProperties for a description of the mutations array, as
-        * well as the return value.
-        *
-        * @param mixed $addressBookId
-        * @param array $mutations
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @see Sabre_DAV_IProperties::updateProperties
-        * @return bool|array
-        */
-       public function updateAddressBook($addressBookId, array $mutations)
-       {
-               $x = explode("-", $addressBookId);
-
-               $updates = array();
-
-               foreach ($mutations as $property=> $newValue) {
-
-                       switch ($property) {
-                               case '{DAV:}displayname' :
-                                       $updates['displayname'] = $newValue;
-                                       break;
-                               case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' :
-                                       $updates['description'] = $newValue;
-                                       break;
-                               default :
-                                       // If any unsupported values were being updated, we must
-                                       // let the entire request fail.
-                                       return false;
-                       }
-
-               }
-
-               // No values are being updated?
-               if (!$updates) {
-                       return false;
-               }
-
-               $query = 'UPDATE ' . CALDAV_SQL_DB . CALDAV_SQL_PREFIX . 'addressbooks_phone SET ctag = ctag + 1 ';
-               foreach ($updates as $key=> $value) {
-                       $query .= ', `' . dbesc($key) . '` = ' . dbesc($key) . ' ';
-               }
-               $query .= ' WHERE id = ' . IntVal($x[1]);
-               q($query);
-
-               return true;
-
-       }
-
-       /**
-        * Creates a new address book
-        *
-        * @param string $principalUri
-        * @param string $url Just the 'basename' of the url.
-        * @param array $properties
-        * @throws Sabre_DAV_Exception_BadRequest
-        * @return void
-        */
-       public function createAddressBook($principalUri, $url, array $properties)
-       {
-               $values = array(
-                       'displayname'  => null,
-                       'description'  => null,
-                       'principaluri' => $principalUri,
-                       'uri'          => $url,
-               );
-
-               foreach ($properties as $property=> $newValue) {
-
-                       switch ($property) {
-                               case '{DAV:}displayname' :
-                                       $values['displayname'] = $newValue;
-                                       break;
-                               case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' :
-                                       $values['description'] = $newValue;
-                                       break;
-                               default :
-                                       throw new Sabre_DAV_Exception_BadRequest('Unknown property: ' . $property);
-                       }
-
-               }
-
-               q("INSERT INTO %s%saddressbooks_phone (uri, displayname, description, principaluri, ctag) VALUES ('%s', '%s', '%s', '%s', 1)",
-                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($values["uri"]), dbesc($values["displayname"]), dbesc($values["description"]), dbesc($values["principaluri"])
-               );
-       }
-
-       /**
-        * Deletes an entire addressbook and all its contents
-        *
-        * @param int $addressBookId
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @return void
-        */
-       public function deleteAddressBook($addressBookId)
-       {
-               $x = explode("-", $addressBookId);
-               q("DELETE FROM %s%scards WHERE namespace = %d AND namespace_id = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]));
-               q("DELETE FROM %s%saddressbooks_phone WHERE id = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
-       }
-
-       /**
-        * Returns all cards for a specific addressbook id.
-        *
-        * This method should return the following properties for each card:
-        *   * carddata - raw vcard data
-        *   * uri - Some unique url
-        *   * lastmodified - A unix timestamp
-        *
-        * It's recommended to also return the following properties:
-        *   * etag - A unique etag. This must change every time the card changes.
-        *   * size - The size of the card in bytes.
-        *
-        * If these last two properties are provided, less time will be spent
-        * calculating them. If they are specified, you can also ommit carddata.
-        * This may speed up certain requests, especially with large cards.
-        *
-        * @param string $addressbookId
-        * @return array
-        */
-       public function getCards($addressbookId)
-       {
-               $x = explode("-", $addressbookId);
-
-               $r = q('SELECT id, carddata, uri, lastmodified, etag, size, contact FROM %s%scards WHERE namespace = %d AND namespace_id = %d AND manually_deleted = 0',
-                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1])
-               );
-               if ($r) return $r;
-               return array();
-       }
-
-       /**
-        * Returns a specfic card.
-        *
-        * The same set of properties must be returned as with getCards. The only
-        * exception is that 'carddata' is absolutely required.
-        *
-        * @param mixed $addressBookId
-        * @param string $cardUri
-        * @throws Sabre_DAV_Exception_NotFound
-        * @return array
-        */
-       public function getCard($addressBookId, $cardUri)
-       {
-               $x = explode("-", $addressBookId);
-               $x = q("SELECT id, carddata, uri, lastmodified, etag, size FROM %s%scards WHERE namespace = %d AND namespace_id = %d AND uri = '%s'",
-                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
-               if (count($x) == 0) throw new Sabre_DAV_Exception_NotFound();
-               return $x[0];
-       }
-
-       /**
-        * Creates a new card.
-        *
-        * The addressbook id will be passed as the first argument. This is the
-        * same id as it is returned from the getAddressbooksForUser method.
-        *
-        * The cardUri is a base uri, and doesn't include the full path. The
-        * cardData argument is the vcard body, and is passed as a string.
-        *
-        * It is possible to return an ETag from this method. This ETag is for the
-        * newly created resource, and must be enclosed with double quotes (that
-        * is, the string itself must contain the double quotes).
-        *
-        * You should only return the ETag if you store the carddata as-is. If a
-        * subsequent GET request on the same card does not have the same body,
-        * byte-by-byte and you did return an ETag here, clients tend to get
-        * confused.
-        *
-        * If you don't return an ETag, you can just return null.
-        *
-        * @param string $addressBookId
-        * @param string $cardUri
-        * @param string $cardData
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @return string
-        */
-       public function createCard($addressBookId, $cardUri, $cardData)
-       {
-               $x = explode("-", $addressBookId);
-
-               $etag = md5($cardData);
-               q("INSERT INTO %s%scards (carddata, uri, lastmodified, namespace, namespace_id, etag, size) VALUES ('%s', '%s', %d, %d, '%s', %d)",
-                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($cardUri), time(), IntVal($x[0]), IntVal($x[1]), $etag, strlen($cardData)
-               );
-
-               q('UPDATE %s%saddressbooks_phone SET ctag = ctag + 1 WHERE id = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
-
-               return '"' . $etag . '"';
-
-       }
-
-       /**
-        * Updates a card.
-        *
-        * The addressbook id will be passed as the first argument. This is the
-        * same id as it is returned from the getAddressbooksForUser method.
-        *
-        * The cardUri is a base uri, and doesn't include the full path. The
-        * cardData argument is the vcard body, and is passed as a string.
-        *
-        * It is possible to return an ETag from this method. This ETag should
-        * match that of the updated resource, and must be enclosed with double
-        * quotes (that is: the string itself must contain the actual quotes).
-        *
-        * You should only return the ETag if you store the carddata as-is. If a
-        * subsequent GET request on the same card does not have the same body,
-        * byte-by-byte and you did return an ETag here, clients tend to get
-        * confused.
-        *
-        * If you don't return an ETag, you can just return null.
-        *
-        * @param string $addressBookId
-        * @param string $cardUri
-        * @param string $cardData
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @return string|null
-        */
-       public function updateCard($addressBookId, $cardUri, $cardData)
-       {
-               $x = explode("-", $addressBookId);
-
-               $etag = md5($cardData);
-               q("UPDATE %s%scards SET carddata = '%s', lastmodified = %d, etag = '%s', size = %d, manually_edited = 1 WHERE uri = '%s' AND namespace = %d AND namespace_id =%d",
-                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), IntVal($x[10]), IntVal($x[1])
-               );
-
-               q('UPDATE %s%saddressbooks_phone SET ctag = ctag + 1 WHERE id = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
-
-               return '"' . $etag . '"';
-       }
-
-       /**
-        * Deletes a card
-        *
-        * @param string $addressBookId
-        * @param string $cardUri
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @return bool
-        */
-       public function deleteCard($addressBookId, $cardUri)
-       {
-               $x = explode("-", $addressBookId);
-
-               q("DELETE FROM %s%scards WHERE namespace = %d AND namespace_id = %d AND uri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
-               q('UPDATE %s%saddressbooks_phone SET ctag = ctag + 1 WHERE id = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
-
-               return true;
-       }
-}
diff --git a/dav/common/dav_carddav_backend_virtual.inc.php b/dav/common/dav_carddav_backend_virtual.inc.php
new file mode 100644 (file)
index 0000000..98597c6
--- /dev/null
@@ -0,0 +1,151 @@
+<?php
+
+abstract class Sabre_CardDAV_Backend_Virtual extends Sabre_CardDAV_Backend_Common
+{
+
+       /**
+        * @static
+        * @abstract
+        * @param int $addressbookId
+        * @param string $uri
+        * @return array
+        */
+       /*
+       abstract public function getItemsByUri($addressbookId, $uri);
+    */
+
+       /**
+        * @static
+        * @param int $uid
+        * @param int $namespace
+        */
+       static public function invalidateCache($uid = 0, $namespace = 0) {
+               q("DELETE FROM %s%sadd_virtual_object_sync WHERE `uid` = %d AND `namespace` = %d",
+                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($uid), IntVal($namespace));
+       }
+
+       /**
+        * @static
+        * @abstract
+        * @param int $addressbookId
+        */
+       static abstract protected function createCache_internal($addressbookId);
+
+       /**
+        * @static
+        * @param int $addressbookId
+        */
+       static protected function createCache($addressbookId) {
+               $addressbookId = IntVal($addressbookId);
+               q("DELETE FROM %s%saddressbookobjects WHERE `addressbook_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
+               static::createCache_internal($addressbookId);
+               q("REPLACE INTO %s%sadd_virtual_object_sync (`addressbook_id`, `date`) VALUES (%d, NOW())", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
+       }
+
+
+       /**
+        * @param string $addressbookId
+        * @return array
+        */
+       public function getCards($addressbookId)
+       {
+               $addressbookId = IntVal($addressbookId);
+               $r = q("SELECT COUNT(*) n FROM %s%sadd_virtual_object_sync WHERE `addressbook_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
+
+               if ($r[0]["n"] == 0) static::createCache($addressbookId);
+
+               return q("SELECT * FROM %s%saddressbookobjects WHERE `addressbook_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
+
+       }
+
+       /**
+        * @param string $addressbookId
+        * @param string $objectUri
+        * @throws Sabre_DAV_Exception_NotFound
+        * @return array
+        */
+       public function getCard($addressbookId, $objectUri)
+       {
+               $addressbookId = IntVal($addressbookId);
+               $r = q("SELECT COUNT(*) n FROM %s%sadd_virtual_object_sync WHERE `addressbook_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
+
+               if ($r[0]["n"] == 0) static::createCache($addressbookId);
+
+               $r = q("SELECT * FROM %s%saddressbookobjects WHERE `uri` = '%s' AND `addressbook_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($objectUri), IntVal($addressbookId));
+               if (count($r) == 0) throw new Sabre_DAV_Exception_NotFound();
+
+               $obj = $r[0];
+               $ret = array(
+                       "id" => IntVal($obj["uri"]),
+                       "carddata" => $obj["carddata"],
+                       "uri" => $obj["uri"],
+                       "lastmodified" => $obj["lastmodified"],
+                       "addressbookid" => $addressbookId,
+                       "etag" => $obj["etag"],
+                       "size" => IntVal($obj["size"]),
+               );
+               return $ret;
+       }
+
+
+
+       /**
+        * @param string $principalUri
+        * @param string $addressbookUri
+        * @param array $properties
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return void
+        */
+       public function createAddressBook($principalUri, $addressbookUri, array $properties)
+       {
+               throw new Sabre_DAV_Exception_Forbidden();
+       }
+
+       /**
+        * @param string $addressbookId
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return void
+        */
+       public function deleteAddressBook($addressbookId)
+       {
+               throw new Sabre_DAV_Exception_Forbidden();
+       }
+
+
+       /**
+        * @param string $addressbookId
+        * @param string $objectUri
+        * @param string $cardData
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return null|string|void
+        */
+       function createCard($addressbookId, $objectUri, $cardData)
+       {
+               throw new Sabre_DAV_Exception_Forbidden();
+       }
+
+       /**
+        * @param string $addressbookId
+        * @param string $objectUri
+        * @param string $cardData
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return null|string|void
+        */
+       function updateCard($addressbookId, $objectUri, $cardData)
+       {
+               throw new Sabre_DAV_Exception_Forbidden();
+       }
+
+       /**
+        * @param string $addressbookId
+        * @param string $objectUri
+        * @throws Sabre_DAV_Exception_Forbidden
+        * @return void
+        */
+       function deleteCard($addressbookId, $objectUri)
+       {
+               throw new Sabre_DAV_Exception_Forbidden();
+       }
+
+
+}
\ No newline at end of file
index 62837dc54d03665039151648c39883cf982455fd..b292074d6497082f4f704ba3165f69ca597f8f25 100644 (file)
@@ -169,7 +169,6 @@ class Sabre_CalDAV_AnimexxUserCalendars implements Sabre_DAV_IExtendedCollection
                $objs[] = new $calendar["calendar_class"]($this->principalBackend, $backend, $calendar);
                }
                }
-        //$objs[] = new Sabre_CalDAV_AnimexxUserZirkelCalendars($this->principalBackend, $this->caldavBackend, $this->username);
         return $objs;
 
     }
index 8cdd9b9b19bfc5a13eebeffe34edec5541a8b46d..7c0d23a3a98396621817db629bbaf14c06b560e5 100644 (file)
@@ -43,6 +43,39 @@ function dav_get_update_statements($from_version)
 
        }
 
+       if (in_array($from_version, array(1, 2))) {
+               $stms[] = "DROP TABLE `dav_addressbooks_phone`";
+               $stms[] = "DROP TABLE `dav_addressbooks_community`";
+               $stms[] = "DROP TABLE `dav_cards`";
+
+               $stms[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks` (
+  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+  `namespace` mediumint(9) NOT NULL,
+  `namespace_id` int(11) unsigned NOT NULL,
+  `displayname` varchar(200) NOT NULL,
+  `description` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
+  `uri` varchar(50) NOT NULL,
+  `ctag` int(11) unsigned NOT NULL DEFAULT '1',
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB  DEFAULT CHARSET=utf8;";
+
+               $stms[] = "CREATE TABLE IF NOT EXISTS `dav_addressbookobjects` (
+  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+  `addressbook_id` int(11) unsigned NOT NULL,
+  `contact` int(11) DEFAULT NULL,
+  `carddata` mediumtext CHARACTER SET utf8 COLLATE utf8_unicode_ci,
+  `uri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
+  `lastmodified` timestamp NULL DEFAULT NULL,
+  `manually_edited` tinyint(4) NOT NULL DEFAULT '0',
+  `manually_deleted` tinyint(4) NOT NULL DEFAULT '0',
+  `etag` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
+  `size` int(10) unsigned NOT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `namespace` (`addressbook_id`,`contact`),
+  KEY `contact` (`contact`)
+) ENGINE=InnoDB  DEFAULT CHARSET=utf8;";
+       }
+
        return $stms;
 }
 
@@ -54,24 +87,6 @@ function dav_get_create_statements($except = array())
 {
        $arr = array();
 
-       if (!in_array("dav_addressbooks_community", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks_community` (
-  `uid` int(11) NOT NULL,
-  `ctag` int(11) unsigned NOT NULL DEFAULT '1',
-  PRIMARY KEY (`uid`)
-) ENGINE=MyISAM DEFAULT CHARSET=utf8";
-
-       if (!in_array("dav_addressbooks_phone", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks_phone` (
-  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
-  `uid` int(11) NOT NULL,
-  `principaluri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
-  `displayname` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
-  `uri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
-  `description` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
-  `ctag` int(11) unsigned NOT NULL DEFAULT '1',
-  PRIMARY KEY (`id`),
-  UNIQUE KEY `principaluri` (`principaluri`,`uri`)
-) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
-
        if (!in_array("dav_caldav_log", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_caldav_log` (
   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `uid` mediumint(9) NOT NULL,
@@ -82,7 +97,7 @@ function dav_get_create_statements($except = array())
   `url` varchar(100) NOT NULL,
   PRIMARY KEY (`id`),
   KEY `mitglied` (`uid`)
-) ENGINE=MyISAM DEFAULT CHARSET=utf8";
+) ENGINE=InnoDB DEFAULT CHARSET=utf8";
 
        if (!in_array("dav_calendarobjects", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_calendarobjects` (
   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
@@ -98,7 +113,7 @@ function dav_get_create_statements($except = array())
   PRIMARY KEY (`id`),
   UNIQUE KEY `uri` (`uri`),
   KEY `calendar_id` (`calendar_id`)
-) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
+) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
 
        if (!in_array("dav_calendars", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_calendars` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
@@ -116,7 +131,7 @@ function dav_get_create_statements($except = array())
   PRIMARY KEY (`id`),
   UNIQUE KEY (`namespace` , `namespace_id` , `uri`),
   KEY `uri` (`uri`)
-) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
+) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
 
        if (!in_array("dav_cal_virtual_object_cache", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_cal_virtual_object_cache` (
   `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
@@ -135,7 +150,7 @@ function dav_get_create_statements($except = array())
   PRIMARY KEY (`id`),
   KEY `data_uri` (`data_uri`),
   KEY `ref_type` (`calendar_id`,`data_end`)
-) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
+) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
 
        if (!in_array("dav_cal_virtual_object_sync", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_cal_virtual_object_sync` (
   `calendar_id` int(10) unsigned NOT NULL,
@@ -143,23 +158,6 @@ function dav_get_create_statements($except = array())
   PRIMARY KEY (`calendar_id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
 
-       if (!in_array("dav_cards", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_cards` (
-  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
-  `namespace` tinyint(3) unsigned NOT NULL,
-  `namespace_id` int(11) unsigned NOT NULL,
-  `contact` int(11) DEFAULT NULL,
-  `carddata` mediumtext CHARACTER SET utf8 COLLATE utf8_unicode_ci,
-  `uri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
-  `lastmodified` int(11) unsigned DEFAULT NULL,
-  `manually_edited` tinyint(4) NOT NULL DEFAULT '0',
-  `manually_deleted` tinyint(4) NOT NULL DEFAULT '0',
-  `etag` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
-  `size` int(10) unsigned NOT NULL,
-  PRIMARY KEY (`id`),
-  UNIQUE KEY `namespace` (`namespace`,`namespace_id`,`contact`),
-  KEY `contact` (`contact`)
-) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
-
        if (!in_array("dav_jqcalendar", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_jqcalendar` (
   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `ical_recurr_uri` varchar(100) DEFAULT NULL,
@@ -190,6 +188,33 @@ function dav_get_create_statements($except = array())
   KEY `calendar_id` (`calendar_id`,`calendarobject_id`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
 
+       if (!in_array("dav_addressbooks", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks` (
+  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+  `namespace` mediumint(9) NOT NULL,
+  `namespace_id` int(11) unsigned NOT NULL,
+  `displayname` varchar(200) NOT NULL,
+  `description` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
+  `uri` varchar(50) NOT NULL,
+  `ctag` int(11) unsigned NOT NULL DEFAULT '1',
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB  DEFAULT CHARSET=utf8;";
+
+       if (!in_array("dav_addressbookobjects", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_addressbookobjects` (
+  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+  `addressbook_id` int(11) unsigned NOT NULL,
+  `contact` int(11) DEFAULT NULL,
+  `carddata` mediumtext CHARACTER SET utf8 COLLATE utf8_unicode_ci,
+  `uri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
+  `lastmodified` timestamp NULL DEFAULT NULL,
+  `manually_edited` tinyint(4) NOT NULL DEFAULT '0',
+  `manually_deleted` tinyint(4) NOT NULL DEFAULT '0',
+  `etag` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
+  `size` int(10) unsigned NOT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `namespace` (`addressbook_id`,`contact`),
+  KEY `contact` (`contact`)
+) ENGINE=InnoDB  DEFAULT CHARSET=utf8;";
+
        return $arr;
 }
 
@@ -201,6 +226,7 @@ function dav_check_tables()
        $x = q("DESCRIBE %s%scalendars", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
        if (!$x) return -1;
        if (count($x) == 9) return 1; // Version 0.1
+       // @TODO Detect Version 0.2
        if (count($x) == 12) return 0; // Correct
        return -2; // Unknown version
 }
@@ -229,7 +255,7 @@ function dav_create_tables()
 function dav_upgrade_tables()
 {
        $ver = dav_check_tables();
-       if (!in_array($ver, array(1) )) return array("Unknown error");
+       if (!in_array($ver, array(1))) return array("Unknown error");
 
        $stms   = dav_get_update_statements($ver);
        $errors = array();
index 9178aaabb315b44b0487150dcab72f1cc9f16817..d2810b4f8f044e0a249820422d4d5d86ef36a073 100644 (file)
@@ -33,7 +33,7 @@ class Sabre_CalDAV_Backend_Friendica extends Sabre_CalDAV_Backend_Virtual
         * @return string
         */
        public static function getBackendTypeName() {
-               return t("Friendicy-Native events");
+               return t("Friendica-Native events");
        }
 
        /**
index 8d8a156cae34995d8e45dd63da8849e28dfb6cac..3d7e09745574f55bd246dd5210cc504f4b8e65a8 100644 (file)
@@ -1,30 +1,39 @@
 <?php
 
-class Sabre_CardDAV_Backend_FriendicaCommunity extends Sabre_CardDAV_Backend_Abstract
+class Sabre_CardDAV_Backend_Friendica extends Sabre_CardDAV_Backend_Virtual
 {
 
        /**
-        * @var null|Sabre_CardDAV_Backend_FriendicaCommunity
+        * @var null|Sabre_CardDAV_Backend_Friendica
         */
        private static $instance = null;
 
        /**
         * @static
-        * @return Sabre_CardDAV_Backend_FriendicaCommunity
+        * @return Sabre_CardDAV_Backend_Friendica
         */
        public static function getInstance() {
                if (self::$instance == null) {
-                       self::$instance = new Sabre_CardDAV_Backend_FriendicaCommunity();
+                       self::$instance = new Sabre_CardDAV_Backend_Friendica();
                }
                return self::$instance;
        }
 
+
        /**
-        * Sets up the object
+        * @return int
         */
-       public function __construct()
+       public function getNamespace()
        {
+               return CARDDAV_NAMESPACE_PRIVATE;
+       }
 
+       /**
+        * @static
+        * @return string
+        */
+       public static function getBackendTypeName() {
+               return t("Friendica-Contacts");
        }
 
        /**
@@ -39,15 +48,12 @@ class Sabre_CardDAV_Backend_FriendicaCommunity extends Sabre_CardDAV_Backend_Abs
 
                $addressBooks = array();
 
-               $books = q("SELECT ctag FROM %s%saddressbooks_community WHERE uid = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($uid));
-               if (count($books) == 0) {
-                       q("INSERT INTO %s%saddressbooks_community (uid, ctag) VALUES (%d, 1)", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($uid));
-                       $ctag = 1;
-               } else {
-                       $ctag = $books[0]["ctag"];
-               }
+               $books = q("SELECT id, ctag FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
+                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($uid), dbesc(CARDDAV_FRIENDICA_CONTACT));
+               $ctag = $books[0]["ctag"];
+
                $addressBooks[] = array(
-                       'id'                                                                => CARDDAV_NAMESPACE_COMMUNITYCONTACTS . "-" . $uid,
+                       'id'                                                                => $books[0]["id"],
                        'uri'                                                               => "friendica",
                        'principaluri'                                                      => $principalUri,
                        '{DAV:}displayname'                                                 => t("Friendica-Contacts"),
@@ -61,56 +67,12 @@ class Sabre_CardDAV_Backend_FriendicaCommunity extends Sabre_CardDAV_Backend_Abs
 
        }
 
-
-       /**
-        * Updates an addressbook's properties
-        *
-        * See Sabre_DAV_IProperties for a description of the mutations array, as
-        * well as the return value.
-        *
-        * @param string $addressBookId
-        * @param array $mutations
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @see Sabre_DAV_IProperties::updateProperties
-        * @return bool|array
-        */
-       public function updateAddressBook($addressBookId, array $mutations)
-       {
-               throw new Sabre_DAV_Exception_Forbidden();
-       }
-
-       /**
-        * Creates a new address book
-        *
-        * @param string $principalUri
-        * @param string $url Just the 'basename' of the url.
-        * @param array $properties
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @return void
-        */
-       public function createAddressBook($principalUri, $url, array $properties)
-       {
-               throw new Sabre_DAV_Exception_Forbidden();
-       }
-
-       /**
-        * Deletes an entire addressbook and all its contents
-        *
-        * @param int $addressBookId
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @return void
-        */
-       public function deleteAddressBook($addressBookId)
-       {
-               throw new Sabre_DAV_Exception_Forbidden();
-       }
-
-
        /**
+        * @static
         * @param array $contact
         * @return array
         */
-       private function dav_contactarr2vcardsource($contact)
+       private static function dav_contactarr2vcardsource($contact)
        {
                $name        = explode(" ", $contact["name"]);
                $first_name  = $last_name = "";
@@ -164,118 +126,25 @@ class Sabre_CardDAV_Backend_FriendicaCommunity extends Sabre_CardDAV_Backend_Abs
        }
 
        /**
-        * @param int $uid
-        * @param array|int[] $exclude_ids
-        * @return array
+        * @static
+        * @param int $addressbookId
+        * @throws Sabre_DAV_Exception_NotFound
         */
-       private function dav_getCommunityContactsVCards($uid = 0, $exclude_ids = array())
-       {
-               $notin    = (count($exclude_ids) > 0 ? " AND id NOT IN (" . implode(", ", $exclude_ids) . ") " : "");
-               $uid      = IntVal($uid);
-               $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0 $notin ORDER BY `name` ASC", $uid);
+       static protected function createCache_internal($addressbookId) {
+               //$notin    = (count($exclude_ids) > 0 ? " AND id NOT IN (" . implode(", ", $exclude_ids) . ") " : "");
+               $addressbook = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
+               if (count($addressbook) != 1 || $addressbook[0]["namespace"] != CARDDAV_NAMESPACE_PRIVATE) throw new Sabre_DAV_Exception_NotFound();
+               $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0 ORDER BY `name` ASC", $addressbook[0]["namespace_id"]);
 
                $retdata = array();
                foreach ($contacts as $contact) {
-                       $x            = $this->dav_contactarr2vcardsource($contact);
-                       $x["contact"] = $contact["id"];
-                       $retdata[]    = $x;
-               }
-               return $retdata;
-       }
-
-
-       /**
-        * Returns all cards for a specific addressbook id.
-        *
-        * This method should return the following properties for each card:
-        *   * carddata - raw vcard data
-        *   * uri - Some unique url
-        *   * lastmodified - A unix timestamp
-        *
-        * It's recommended to also return the following properties:
-        *   * etag - A unique etag. This must change every time the card changes.
-        *   * size - The size of the card in bytes.
-        *
-        * If these last two properties are provided, less time will be spent
-        * calculating them. If they are specified, you can also ommit carddata.
-        * This may speed up certain requests, especially with large cards.
-        *
-        * @param string $addressbookId
-        * @return array
-        */
-       public function getCards($addressbookId)
-       {
-               $add = explode("-", $addressbookId);
-
-               $indb           = q('SELECT id, carddata, uri, lastmodified, etag, size, contact, manually_deleted FROM %s%scards WHERE namespace = %d AND namespace_id = %d',
-                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($add[0]), IntVal($add[1])
-               );
-               $found_contacts = array();
-               $contacts       = array();
-               foreach ($indb as $x) {
-                       if ($x["manually_deleted"] == 0) $contacts[] = $x;
-                       $found_contacts[] = IntVal($x["contact"]);
-               }
-               $new_found = $this->dav_getCommunityContactsVCards($add[1], $found_contacts);
-               foreach ($new_found as $new) {
-                       q("INSERT INTO %s%scards (namespace, namespace_id, contact, carddata, uri, lastmodified, manually_edited, manually_deleted, etag, size)
-                                       VALUES (%d, %d, %d, '%s', '%s', %d, 0, 0, '%s', %d)", CALDAV_SQL_DB, CALDAV_SQL_PREFIX,
-                               IntVal($add[0]), IntVal($add[1]), IntVal($new["contact"]), dbesc($new["carddata"]), dbesc($new["uri"]), time(), md5($new["carddata"]), strlen($new["carddata"])
+                       $x            = static::dav_contactarr2vcardsource($contact);
+                       q("INSERT INTO %s%saddressbookobjects (`addressbook_id`, `contact`, `carddata`, `uri`, `lastmodified`, `etag`, `size`) VALUES (%d, %d, '%s', '%s', NOW(), '%s', %d)",
+                               CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId, $contact["id"], dbesc($x["carddata"]), dbesc($x["uri"]), dbesc($x["etag"]), $x["size"]
                        );
                }
-               return array_merge($contacts, $new_found);
-       }
-
-       /**
-        * Returns a specfic card.
-        *
-        * The same set of properties must be returned as with getCards. The only
-        * exception is that 'carddata' is absolutely required.
-        *
-        * @param mixed $addressBookId
-        * @param string $cardUri
-        * @throws Sabre_DAV_Exception_NotFound
-        * @return array
-        */
-       public function getCard($addressBookId, $cardUri)
-       {
-               $x = explode("-", $addressBookId);
-               $x = q("SELECT id, carddata, uri, lastmodified, etag, size FROM %s%scards WHERE namespace = %d AND namespace_id = %d AND uri = '%s'",
-                       CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
-               if (count($x) == 0) throw new Sabre_DAV_Exception_NotFound();
-               return $x[0];
        }
 
-       /**
-        * Creates a new card.
-        *
-        * The addressbook id will be passed as the first argument. This is the
-        * same id as it is returned from the getAddressbooksForUser method.
-        *
-        * The cardUri is a base uri, and doesn't include the full path. The
-        * cardData argument is the vcard body, and is passed as a string.
-        *
-        * It is possible to return an ETag from this method. This ETag is for the
-        * newly created resource, and must be enclosed with double quotes (that
-        * is, the string itself must contain the double quotes).
-        *
-        * You should only return the ETag if you store the carddata as-is. If a
-        * subsequent GET request on the same card does not have the same body,
-        * byte-by-byte and you did return an ETag here, clients tend to get
-        * confused.
-        *
-        * If you don't return an ETag, you can just return null.
-        *
-        * @param string $addressBookId
-        * @param string $cardUri
-        * @param string $cardData
-        * @throws Sabre_DAV_Exception_Forbidden
-        * @return string
-        */
-       public function createCard($addressBookId, $cardUri, $cardData)
-       {
-               throw new Sabre_DAV_Exception_Forbidden();
-       }
 
        /**
         * Updates a card.
index a56862aecd9848908892a49545aa9a61d7ce4e4d..c36d00840a5eac1cd1d8f03b336116a19ca227be 100644 (file)
@@ -30,15 +30,21 @@ function dav_include_files()
 
        require_once (__DIR__ . "/common/calendar.fnk.php");
        require_once (__DIR__ . "/common/calendar_rendering.fnk.php");
+
        require_once (__DIR__ . "/common/dav_caldav_backend_common.inc.php");
        require_once (__DIR__ . "/common/dav_caldav_backend_private.inc.php");
        require_once (__DIR__ . "/common/dav_caldav_backend_virtual.inc.php");
        require_once (__DIR__ . "/common/dav_caldav_root.inc.php");
        require_once (__DIR__ . "/common/dav_user_calendars.inc.php");
+       require_once (__DIR__ . "/common/dav_caldav_calendar_virtual.inc.php");
+       require_once (__DIR__ . "/common/dav_caldav_calendar_private.inc.php");
+
        require_once (__DIR__ . "/common/dav_carddav_root.inc.php");
-       require_once (__DIR__ . "/common/dav_carddav_backend_std.inc.php");
+       require_once (__DIR__ . "/common/dav_carddav_backend_common.inc.php");
+       require_once (__DIR__ . "/common/dav_carddav_backend_virtual.inc.php");
+       require_once (__DIR__ . "/common/dav_carddav_backend_private.inc.php");
        require_once (__DIR__ . "/common/dav_user_addressbooks.inc.php");
-       require_once (__DIR__ . "/common/dav_caldav_calendar_virtual.inc.php");
+
        require_once (__DIR__ . "/common/wdcal_configuration.php");
        require_once (__DIR__ . "/common/wdcal_backend.inc.php");
 
@@ -65,6 +71,9 @@ function dav_init(&$a)
         * ALTER TABLE `photo` ADD INDEX ( `contact-id` )
         */
 
+       ini_set("display_errors", 1);
+       error_reporting(E_ALL);
+
        dav_include_files();
 
        if (false) {
@@ -74,6 +83,7 @@ function dav_init(&$a)
        }
 
        wdcal_create_std_calendars();
+       wdcal_create_std_addressbooks();
        wdcal_addRequiredHeaders();
 
        if ($a->argc >= 2 && $a->argv[1] == "wdcal") {
@@ -104,10 +114,6 @@ function dav_init(&$a)
        $browser = new Sabre_DAV_Browser_Plugin();
        $server->addPlugin($browser);
 
-       $aclPlugin                      = new Sabre_DAVACL_Plugin_Friendica();
-       $aclPlugin->defaultUsernamePath = "principals/users";
-       $server->addPlugin($aclPlugin);
-
        $server->exec();
 
        killme();