diff options
author | Morris Jobke <hey@morrisjobke.de> | 2019-08-05 14:52:45 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-08-05 14:52:45 +0200 |
commit | 1d72073e349bf6926a13c085495c44fce2406e61 (patch) | |
tree | 4ff4ea8580be37abdf19d044e21d9eb4ad2bdb4a /apps/dav | |
parent | 7b0e11f7094967eb63033f6e520f2f4309f06a72 (diff) | |
parent | 3e5946bd0d91bd52bd6d3adf5486c604b59d6651 (diff) | |
download | nextcloud-server-1d72073e349bf6926a13c085495c44fce2406e61.tar.gz nextcloud-server-1d72073e349bf6926a13c085495c44fce2406e61.zip |
Merge pull request #16498 from nextcloud/feature/noid/room_metadata
Allow calendar resources/rooms to provide metadata
Diffstat (limited to 'apps/dav')
12 files changed, 873 insertions, 1000 deletions
diff --git a/apps/dav/appinfo/info.xml b/apps/dav/appinfo/info.xml index 2a11eacd9be..71b3699b1ec 100644 --- a/apps/dav/appinfo/info.xml +++ b/apps/dav/appinfo/info.xml @@ -5,7 +5,7 @@ <name>WebDAV</name> <summary>WebDAV endpoint</summary> <description>WebDAV endpoint</description> - <version>1.10.0</version> + <version>1.11.0</version> <licence>agpl</licence> <author>owncloud.org</author> <namespace>DAV</namespace> diff --git a/apps/dav/composer/composer/autoload_classmap.php b/apps/dav/composer/composer/autoload_classmap.php index b550e37a31c..18b94dbf71f 100644 --- a/apps/dav/composer/composer/autoload_classmap.php +++ b/apps/dav/composer/composer/autoload_classmap.php @@ -179,6 +179,7 @@ return array( 'OCA\\DAV\\Migration\\Version1008Date20181105110300' => $baseDir . '/../lib/Migration/Version1008Date20181105110300.php', 'OCA\\DAV\\Migration\\Version1008Date20181105112049' => $baseDir . '/../lib/Migration/Version1008Date20181105112049.php', 'OCA\\DAV\\Migration\\Version1008Date20181114084440' => $baseDir . '/../lib/Migration/Version1008Date20181114084440.php', + 'OCA\\DAV\\Migration\\Version1011Date20190725113607' => $baseDir . '/../lib/Migration/Version1011Date20190725113607.php', 'OCA\\DAV\\Provisioning\\Apple\\AppleProvisioningNode' => $baseDir . '/../lib/Provisioning/Apple/AppleProvisioningNode.php', 'OCA\\DAV\\Provisioning\\Apple\\AppleProvisioningPlugin' => $baseDir . '/../lib/Provisioning/Apple/AppleProvisioningPlugin.php', 'OCA\\DAV\\RootCollection' => $baseDir . '/../lib/RootCollection.php', diff --git a/apps/dav/composer/composer/autoload_static.php b/apps/dav/composer/composer/autoload_static.php index 736b77aa11a..4c45dc60e4f 100644 --- a/apps/dav/composer/composer/autoload_static.php +++ b/apps/dav/composer/composer/autoload_static.php @@ -194,6 +194,7 @@ class ComposerStaticInitDAV 'OCA\\DAV\\Migration\\Version1008Date20181105110300' => __DIR__ . '/..' . '/../lib/Migration/Version1008Date20181105110300.php', 'OCA\\DAV\\Migration\\Version1008Date20181105112049' => __DIR__ . '/..' . '/../lib/Migration/Version1008Date20181105112049.php', 'OCA\\DAV\\Migration\\Version1008Date20181114084440' => __DIR__ . '/..' . '/../lib/Migration/Version1008Date20181114084440.php', + 'OCA\\DAV\\Migration\\Version1011Date20190725113607' => __DIR__ . '/..' . '/../lib/Migration/Version1011Date20190725113607.php', 'OCA\\DAV\\Provisioning\\Apple\\AppleProvisioningNode' => __DIR__ . '/..' . '/../lib/Provisioning/Apple/AppleProvisioningNode.php', 'OCA\\DAV\\Provisioning\\Apple\\AppleProvisioningPlugin' => __DIR__ . '/..' . '/../lib/Provisioning/Apple/AppleProvisioningPlugin.php', 'OCA\\DAV\\RootCollection' => __DIR__ . '/..' . '/../lib/RootCollection.php', diff --git a/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php b/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php index 3a9e3def05d..1327a095056 100644 --- a/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php +++ b/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php @@ -1,6 +1,6 @@ <?php /** - * @copyright 2018, Georg Ehrke <oc.list@georgehrke.com> + * @copyright 2019, Georg Ehrke <oc.list@georgehrke.com> * * @author Georg Ehrke <oc.list@georgehrke.com> * @@ -26,6 +26,8 @@ namespace OCA\DAV\BackgroundJob; use OC\BackgroundJob\TimedJob; use OCA\DAV\CalDAV\CalDavBackend; use OCP\Calendar\BackendTemporarilyUnavailableException; +use OCP\Calendar\IMetadataProvider; +use OCP\Calendar\Resource\IBackend as IResourceBackend; use OCP\Calendar\Resource\IManager as IResourceManager; use OCP\Calendar\Resource\IResource; use OCP\Calendar\Room\IManager as IRoomManager; @@ -41,23 +43,11 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { private $roomManager; /** @var IDBConnection */ - private $db; + private $dbConnection; /** @var CalDavBackend */ private $calDavBackend; - /** @var string */ - private $resourceDbTable; - - /** @var string */ - private $resourcePrincipalUri; - - /** @var string */ - private $roomDbTable; - - /** @var string */ - private $roomPrincipalUri; - /** * UpdateCalendarResourcesRoomsBackgroundJob constructor. * @@ -66,16 +56,14 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { * @param IDBConnection $dbConnection * @param CalDavBackend $calDavBackend */ - public function __construct(IResourceManager $resourceManager, IRoomManager $roomManager, - IDBConnection $dbConnection, CalDavBackend $calDavBackend) { + public function __construct(IResourceManager $resourceManager, + IRoomManager $roomManager, + IDBConnection $dbConnection, + CalDavBackend $calDavBackend) { $this->resourceManager = $resourceManager; $this->roomManager = $roomManager; - $this->db = $dbConnection; + $this->dbConnection = $dbConnection; $this->calDavBackend = $calDavBackend; - $this->resourceDbTable = 'calendar_resources'; - $this->resourcePrincipalUri = 'principals/calendar-resources'; - $this->roomDbTable = 'calendar_rooms'; - $this->roomPrincipalUri = 'principals/calendar-rooms'; // run once an hour $this->setInterval(60 * 60); @@ -84,211 +72,132 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { /** * @param $argument */ - public function run($argument) { - $this->runResources(); - $this->runRooms(); + public function run($argument):void { + $this->runForBackend( + $this->resourceManager, + 'calendar_resources', + 'calendar_resources_md', + 'resource_id', + 'principals/calendar-resources' + ); + $this->runForBackend( + $this->roomManager, + 'calendar_rooms', + 'calendar_rooms_md', + 'room_id', + 'principals/calendar-rooms' + ); } /** - * run timed job for resources + * Run background-job for one specific backendManager + * either ResourceManager or RoomManager + * + * @param IResourceManager|IRoomManager $backendManager + * @param string $dbTable + * @param string $dbTableMetadata + * @param string $foreignKey + * @param string $principalPrefix */ - private function runResources() { - $resourceBackends = $this->resourceManager->getBackends(); - $cachedResources = $this->getCached($this->resourceDbTable); - $cachedResourceIds = $this->getCachedResourceIds($cachedResources); + private function runForBackend($backendManager, + string $dbTable, + string $dbTableMetadata, + string $foreignKey, + string $principalPrefix):void { + $backends = $backendManager->getBackends(); + + foreach($backends as $backend) { + $backendId = $backend->getBackendIdentifier(); - $remoteResourceIds = []; - foreach($resourceBackends as $resourceBackend) { try { - $remoteResourceIds[$resourceBackend->getBackendIdentifier()] = - $resourceBackend->listAllResources(); + if ($backend instanceof IResourceBackend) { + $list = $backend->listAllResources(); + } else { + $list = $backend->listAllRooms(); + } } catch(BackendTemporarilyUnavailableException $ex) { - // If the backend is temporarily unavailable - // ignore this backend in this execution - unset($cachedResourceIds[$resourceBackend->getBackendIdentifier()]); + continue; } - } - - $sortedResources = $this->sortByNewDeletedExisting($cachedResourceIds, $remoteResourceIds); - foreach($sortedResources['new'] as $backendId => $newResources) { - foreach ($newResources as $newResource) { - $backend = $this->resourceManager->getBackend($backendId); - if ($backend === null) { + $cachedList = $this->getAllCachedByBackend($dbTable, $backendId); + $newIds = array_diff($list, $cachedList); + $deletedIds = array_diff($cachedList, $list); + $editedIds = array_intersect($list, $cachedList); + + foreach($newIds as $newId) { + try { + if ($backend instanceof IResourceBackend) { + $resource = $backend->getResource($newId); + } else { + $resource = $backend->getRoom($newId); + } + + $metadata = []; + if ($resource instanceof IMetadataProvider) { + $metadata = $this->getAllMetadataOfBackend($resource); + } + } catch(BackendTemporarilyUnavailableException $ex) { continue; } - $resource = $backend->getResource($newResource); - $this->addToCache($this->resourceDbTable, $resource); + $id = $this->addToCache($dbTable, $backendId, $resource); + $this->addMetadataToCache($dbTableMetadata, $foreignKey, $id, $metadata); + // we don't create the calendar here, it is created lazily + // when an event is actually scheduled with this resource / room } - } - foreach($sortedResources['deleted'] as $backendId => $deletedResources) { - foreach ($deletedResources as $deletedResource) { - $this->deleteFromCache($this->resourceDbTable, - $this->resourcePrincipalUri, $backendId, $deletedResource); - } - } - foreach($sortedResources['edited'] as $backendId => $editedResources) { - foreach ($editedResources as $editedResource) { - $backend = $this->resourceManager->getBackend($backendId); - if ($backend === null) { - continue; - } - $resource = $backend->getResource($editedResource); - $this->updateCache($this->resourceDbTable, $resource); - } - } - } + foreach($deletedIds as $deletedId) { + $id = $this->getIdForBackendAndResource($dbTable, $backendId, $deletedId); + $this->deleteFromCache($dbTable, $id); + $this->deleteMetadataFromCache($dbTableMetadata, $foreignKey, $id); - /** - * run timed job for rooms - */ - private function runRooms() { - $roomBackends = $this->roomManager->getBackends(); - $cachedRooms = $this->getCached($this->roomDbTable); - $cachedRoomIds = $this->getCachedRoomIds($cachedRooms); - - $remoteRoomIds = []; - foreach($roomBackends as $roomBackend) { - try { - $remoteRoomIds[$roomBackend->getBackendIdentifier()] = - $roomBackend->listAllRooms(); - } catch(BackendTemporarilyUnavailableException $ex) { - // If the backend is temporarily unavailable - // ignore this backend in this execution - unset($cachedRoomIds[$roomBackend->getBackendIdentifier()]); + $principalName = implode('-', [$backendId, $deletedId]); + $this->deleteCalendarDataForResource($principalPrefix, $principalName); } - } - $sortedRooms = $this->sortByNewDeletedExisting($cachedRoomIds, $remoteRoomIds); - - foreach($sortedRooms['new'] as $backendId => $newRooms) { - foreach ($newRooms as $newRoom) { - $backend = $this->roomManager->getBackend($backendId); - if ($backend === null) { + foreach($editedIds as $editedId) { + $id = $this->getIdForBackendAndResource($dbTable, $backendId, $editedId); + + try { + if ($backend instanceof IResourceBackend) { + $resource = $backend->getResource($editedId); + } else { + $resource = $backend->getRoom($editedId); + } + + $metadata = []; + if ($resource instanceof IMetadataProvider) { + $metadata = $this->getAllMetadataOfBackend($resource); + } + } catch(BackendTemporarilyUnavailableException $ex) { continue; } - $resource = $backend->getRoom($newRoom); - $this->addToCache($this->roomDbTable, $resource); - } - } - foreach($sortedRooms['deleted'] as $backendId => $deletedRooms) { - foreach ($deletedRooms as $deletedRoom) { - $this->deleteFromCache($this->roomDbTable, - $this->roomPrincipalUri, $backendId, $deletedRoom); - } - } - foreach($sortedRooms['edited'] as $backendId => $editedRooms) { - foreach ($editedRooms as $editedRoom) { - $backend = $this->roomManager->getBackend($backendId); - if ($backend === null) { - continue; - } - - $resource = $backend->getRoom($editedRoom); - $this->updateCache($this->roomDbTable, $resource); - } - } - } + $this->updateCache($dbTable, $id, $resource); - /** - * get cached db rows for resources / rooms - * @param string $tableName - * @return array - */ - private function getCached($tableName):array { - $query = $this->db->getQueryBuilder(); - $query->select('*')->from($tableName); - - $rows = []; - $stmt = $query->execute(); - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { - $rows[] = $row; - } - - return $rows; - } - - /** - * @param array $cachedResources - * @return array - */ - private function getCachedResourceIds(array $cachedResources):array { - $cachedResourceIds = []; - foreach ($cachedResources as $cachedResource) { - if (!isset($cachedResourceIds[$cachedResource['backend_id']])) { - $cachedResourceIds[$cachedResource['backend_id']] = []; - } - - $cachedResourceIds[$cachedResource['backend_id']][] = - $cachedResource['resource_id']; - } - - return $cachedResourceIds; - } - - /** - * @param array $cachedRooms - * @return array - */ - private function getCachedRoomIds(array $cachedRooms):array { - $cachedRoomIds = []; - foreach ($cachedRooms as $cachedRoom) { - if (!isset($cachedRoomIds[$cachedRoom['backend_id']])) { - $cachedRoomIds[$cachedRoom['backend_id']] = []; - } - - $cachedRoomIds[$cachedRoom['backend_id']][] = - $cachedRoom['resource_id']; - } - - return $cachedRoomIds; - } - - /** - * sort list of ids by whether they appear only in the backend / - * only in the cache / in both - * - * @param array $cached - * @param array $remote - * @return array - */ - private function sortByNewDeletedExisting(array $cached, array $remote):array { - $sorted = [ - 'new' => [], - 'deleted' => [], - 'edited' => [], - ]; - - $backendIds = array_merge(array_keys($cached), array_keys($remote)); - foreach($backendIds as $backendId) { - if (!isset($cached[$backendId])) { - $sorted['new'][$backendId] = $remote[$backendId]; - } elseif (!isset($remote[$backendId])) { - $sorted['deleted'][$backendId] = $cached[$backendId]; - } else { - $sorted['new'][$backendId] = array_diff($remote[$backendId], $cached[$backendId]); - $sorted['deleted'][$backendId] = array_diff($cached[$backendId], $remote[$backendId]); - $sorted['edited'][$backendId] = array_intersect($remote[$backendId], $cached[$backendId]); + if ($resource instanceof IMetadataProvider) { + $cachedMetadata = $this->getAllMetadataOfCache($dbTableMetadata, $foreignKey, $id); + $this->updateMetadataCache($dbTableMetadata, $foreignKey, $id, $metadata, $cachedMetadata); + } } } - - return $sorted; } /** * add entry to cache that exists remotely but not yet in cache * * @param string $table + * @param string $backendId * @param IResource|IRoom $remote + * @return int Insert id */ - private function addToCache($table, $remote) { - $query = $this->db->getQueryBuilder(); + private function addToCache(string $table, + string $backendId, + $remote):int { + $query = $this->dbConnection->getQueryBuilder(); $query->insert($table) ->values([ - 'backend_id' => $query->createNamedParameter($remote->getBackend()->getBackendIdentifier()), + 'backend_id' => $query->createNamedParameter($backendId), 'resource_id' => $query->createNamedParameter($remote->getId()), 'email' => $query->createNamedParameter($remote->getEMail()), 'displayname' => $query->createNamedParameter($remote->getDisplayName()), @@ -298,37 +207,70 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { )) ]) ->execute(); + return $query->getLastInsertId(); + } + + /** + * @param string $table + * @param string $foreignKey + * @param int $foreignId + * @param array $metadata + */ + private function addMetadataToCache(string $table, + string $foreignKey, + int $foreignId, + array $metadata):void { + foreach($metadata as $key => $value) { + $query = $this->dbConnection->getQueryBuilder(); + $query->insert($table) + ->values([ + $foreignKey => $query->createNamedParameter($foreignId), + 'key' => $query->createNamedParameter($key), + 'value' => $query->createNamedParameter($value), + ]) + ->execute(); + } } /** * delete entry from cache that does not exist anymore remotely * * @param string $table - * @param string $principalUri - * @param string $backendId - * @param string $resourceId + * @param int $id */ - private function deleteFromCache($table, $principalUri, $backendId, $resourceId) { - $query = $this->db->getQueryBuilder(); + private function deleteFromCache(string $table, + int $id):void { + $query = $this->dbConnection->getQueryBuilder(); $query->delete($table) - ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId))) - ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId))) + ->where($query->expr()->eq('id', $query->createNamedParameter($id))) ->execute(); + } - $calendar = $this->calDavBackend->getCalendarByUri($principalUri, implode('-', [$backendId, $resourceId])); - if ($calendar !== null) { - $this->calDavBackend->deleteCalendar($calendar['id']); - } + /** + * @param string $table + * @param string $foreignKey + * @param int $id + */ + private function deleteMetadataFromCache(string $table, + string $foreignKey, + int $id):void { + $query = $this->dbConnection->getQueryBuilder(); + $query->delete($table) + ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id))) + ->execute(); } /** * update an existing entry in cache * * @param string $table + * @param int $id * @param IResource|IRoom $remote */ - private function updateCache($table, $remote) { - $query = $this->db->getQueryBuilder(); + private function updateCache(string $table, + int $id, + $remote):void { + $query = $this->dbConnection->getQueryBuilder(); $query->update($table) ->set('email', $query->createNamedParameter($remote->getEMail())) ->set('displayname', $query->createNamedParameter($remote->getDisplayName())) @@ -336,12 +278,58 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { $this->serializeGroupRestrictions( $remote->getGroupRestrictions() ))) - ->where($query->expr()->eq('backend_id', $query->createNamedParameter($remote->getBackend()->getBackendIdentifier()))) - ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($remote->getId()))) + ->where($query->expr()->eq('id', $query->createNamedParameter($id))) ->execute(); } /** + * @param string $dbTable + * @param string $foreignKey + * @param int $id + * @param array $metadata + * @param array $cachedMetadata + */ + private function updateMetadataCache(string $dbTable, + string $foreignKey, + int $id, + array $metadata, + array $cachedMetadata):void { + $newMetadata = array_diff_key($metadata, $cachedMetadata); + $deletedMetadata = array_diff_key($cachedMetadata, $metadata); + + foreach ($newMetadata as $key => $value) { + $query = $this->dbConnection->getQueryBuilder(); + $query->insert($dbTable) + ->values([ + $foreignKey => $query->createNamedParameter($id), + 'key' => $query->createNamedParameter($key), + 'value' => $query->createNamedParameter($value), + ]) + ->execute(); + } + + foreach($deletedMetadata as $key => $value) { + $query = $this->dbConnection->getQueryBuilder(); + $query->delete($dbTable) + ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id))) + ->andWhere($query->expr()->eq('key', $query->createNamedParameter($key))) + ->execute(); + } + + $existingKeys = array_keys(array_intersect_key($metadata, $cachedMetadata)); + foreach($existingKeys as $existingKey) { + if ($metadata[$existingKey] !== $cachedMetadata[$existingKey]) { + $query = $this->dbConnection->getQueryBuilder(); + $query->update($dbTable) + ->set('value', $query->createNamedParameter($metadata[$existingKey])) + ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id))) + ->andWhere($query->expr()->eq('key', $query->createNamedParameter($existingKey))) + ->execute(); + } + } + } + + /** * serialize array of group restrictions to store them in database * * @param array $groups @@ -350,4 +338,102 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { private function serializeGroupRestrictions(array $groups):string { return \json_encode($groups); } + + /** + * Gets all metadata of a backend + * + * @param IResource|IRoom $resource + * @return array + */ + private function getAllMetadataOfBackend($resource):array { + if (!($resource instanceof IMetadataProvider)) { + return []; + } + + $keys = $resource->getAllAvailableMetadataKeys(); + $metadata = []; + foreach($keys as $key) { + $metadata[$key] = $resource->getMetadataForKey($key); + } + + return $metadata; + } + + /** + * @param string $table + * @param string $foreignKey + * @param int $id + * @return array + */ + private function getAllMetadataOfCache(string $table, + string $foreignKey, + int $id):array { + $query = $this->dbConnection->getQueryBuilder(); + $query->select(['key', 'value']) + ->from($table) + ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id))); + $stmt = $query->execute(); + $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); + + $metadata = []; + foreach($rows as $row) { + $metadata[$row['key']] = $row['value']; + } + + return $metadata; + } + + /** + * Gets all cached rooms / resources by backend + * + * @param $tableName + * @param $backendId + * @return array + */ + private function getAllCachedByBackend(string $tableName, + string $backendId):array { + $query = $this->dbConnection->getQueryBuilder(); + $query->select('resource_id') + ->from($tableName) + ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId))); + $stmt = $query->execute(); + + return array_map(function($row) { + return $row['resource_id']; + }, $stmt->fetchAll(\PDO::FETCH_NAMED)); + } + + /** + * @param $principalPrefix + * @param $principalUri + */ + private function deleteCalendarDataForResource(string $principalPrefix, + string $principalUri):void { + $calendar = $this->calDavBackend->getCalendarByUri( + implode('/', [$principalPrefix, $principalUri]), + CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI); + + if ($calendar !== null) { + $this->calDavBackend->deleteCalendar($calendar['id']); + } + } + + /** + * @param $table + * @param $backendId + * @param $resourceId + * @return int + */ + private function getIdForBackendAndResource(string $table, + string $backendId, + string $resourceId):int { + $query = $this->dbConnection->getQueryBuilder(); + $query->select('id') + ->from($table) + ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId))) + ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId))); + $stmt = $query->execute(); + + return $stmt->fetch(\PDO::FETCH_NAMED)['id']; + } } diff --git a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php index 90d147f6741..aab5fcab8ad 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php @@ -1,6 +1,6 @@ <?php /** - * @copyright 2018, Georg Ehrke <oc.list@georgehrke.com> + * @copyright 2019, Georg Ehrke <oc.list@georgehrke.com> * * @author Georg Ehrke <oc.list@georgehrke.com> * @@ -51,6 +51,12 @@ abstract class AbstractPrincipalBackend implements BackendInterface { private $dbTableName; /** @var string */ + private $dbMetaDataTableName; + + /** @var string */ + private $dbForeignKeyName; + + /** @var string */ private $cuType; /** @@ -74,7 +80,9 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $this->groupManager = $groupManager; $this->logger = $logger; $this->principalPrefix = $principalPrefix; - $this->dbTableName = 'calendar_' . $dbPrefix; + $this->dbTableName = 'calendar_' . $dbPrefix . 's'; + $this->dbMetaDataTableName = $this->dbTableName . '_md'; + $this->dbForeignKeyName = $dbPrefix . '_id'; $this->cuType = $cuType; } @@ -100,8 +108,31 @@ abstract class AbstractPrincipalBackend implements BackendInterface { ->from($this->dbTableName); $stmt = $query->execute(); + $metaDataQuery = $this->db->getQueryBuilder(); + $metaDataQuery->select([$this->dbForeignKeyName, 'key', 'value']) + ->from($this->dbMetaDataTableName); + $metaDataStmt = $metaDataQuery->execute(); + $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); + + $metaDataById = []; + foreach($metaDataRows as $metaDataRow) { + if (!isset($metaDataById[$metaDataRow[$this->dbForeignKeyName]])) { + $metaDataById[$metaDataRow[$this->dbForeignKeyName]] = []; + } + + $metaDataById[$metaDataRow[$this->dbForeignKeyName]][$metaDataRow['key']] = + $metaDataRow['value']; + } + while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { - $principals[] = $this->rowToPrincipal($row); + $id = $row['id']; + + if (isset($metaDataById[$id])) { + $principals[] = $this->rowToPrincipal($row, $metaDataById[$id]); + } else { + $principals[] = $this->rowToPrincipal($row); + } + } $stmt->closeCursor(); @@ -138,7 +169,50 @@ abstract class AbstractPrincipalBackend implements BackendInterface { return null; } - return $this->rowToPrincipal($row); + $metaDataQuery = $this->db->getQueryBuilder(); + $metaDataQuery->select(['key', 'value']) + ->from($this->dbMetaDataTableName) + ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id']))); + $metaDataStmt = $metaDataQuery->execute(); + $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); + $metadata = []; + + foreach($metaDataRows as $metaDataRow) { + $metadata[$metaDataRow['key']] = $metaDataRow['value']; + } + + return $this->rowToPrincipal($row, $metadata); + } + + /** + * @param int $id + * @return array|null + */ + public function getPrincipalById($id):?array { + $query = $this->db->getQueryBuilder(); + $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname']) + ->from($this->dbTableName) + ->where($query->expr()->eq('id', $query->createNamedParameter($id))); + $stmt = $query->execute(); + $row = $stmt->fetch(\PDO::FETCH_ASSOC); + + if(!$row) { + return null; + } + + $metaDataQuery = $this->db->getQueryBuilder(); + $metaDataQuery->select(['key', 'value']) + ->from($this->dbMetaDataTableName) + ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id']))); + $metaDataStmt = $metaDataQuery->execute(); + $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); + $metadata = []; + + foreach($metaDataRows as $metaDataRow) { + $metadata[$metaDataRow['key']] = $metaDataRow['value']; + } + + return $this->rowToPrincipal($row, $metadata); } /** @@ -253,7 +327,15 @@ abstract class AbstractPrincipalBackend implements BackendInterface { break; default: - $results[] = []; + $rowsByMetadata = $this->searchPrincipalsByMetadataKey($prop, $value); + $filteredRows = array_filter($rowsByMetadata, function($row) use ($usersGroups) { + return $this->isAllowedToAccessResource($row, $usersGroups); + }); + + $results[] = array_map(function($row) { + return $row['uri']; + }, $filteredRows); + break; } } @@ -275,6 +357,39 @@ abstract class AbstractPrincipalBackend implements BackendInterface { } /** + * Searches principals based on their metadata keys. + * This allows to search for all principals with a specific key. + * e.g.: + * '{http://nextcloud.com/ns}room-building-address' => 'ABC Street 123, ...' + * + * @param $key + * @param $value + * @return array + */ + private function searchPrincipalsByMetadataKey($key, $value):array { + $query = $this->db->getQueryBuilder(); + $query->select([$this->dbForeignKeyName]) + ->from($this->dbMetaDataTableName) + ->where($query->expr()->eq('key', $query->createNamedParameter($key))) + ->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%'))); + $stmt = $query->execute(); + + $rows = []; + while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + $id = $row[$this->dbForeignKeyName]; + + $principalRow = $this->getPrincipalById($id); + if (!$principalRow) { + continue; + } + + $rows[] = $principalRow; + } + + return $rows; + } + + /** * @param string $uri * @param string $principalPrefix * @return null|string @@ -338,14 +453,18 @@ abstract class AbstractPrincipalBackend implements BackendInterface { /** * convert database row to principal + * + * @param String[] $row + * @param String[] $metadata + * @return Array */ - private function rowToPrincipal($row) { - return [ + private function rowToPrincipal(array $row, array $metadata=[]):array { + return array_merge([ 'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'], '{DAV:}displayname' => $row['displayname'], '{http://sabredav.org/ns}email-address' => $row['email'], '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->cuType, - ]; + ], $metadata); } /** @@ -353,7 +472,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { * @param $userGroups * @return bool */ - private function isAllowedToAccessResource($row, $userGroups) { + private function isAllowedToAccessResource(array $row, array $userGroups):bool { if (!isset($row['group_restrictions']) || $row['group_restrictions'] === null || $row['group_restrictions'] === '') { diff --git a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php index f8f10e78f94..0f6e6e7b4fd 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php @@ -40,6 +40,6 @@ class ResourcePrincipalBackend extends AbstractPrincipalBackend { IGroupManager $groupManager, ILogger $logger) { parent::__construct($dbConnection, $userSession, $groupManager, $logger, - 'principals/calendar-resources', 'resources', 'RESOURCE'); + 'principals/calendar-resources', 'resource', 'RESOURCE'); } } diff --git a/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php index 3059ed80ea6..68a344aa0ca 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php @@ -40,6 +40,6 @@ class RoomPrincipalBackend extends AbstractPrincipalBackend { IGroupManager $groupManager, ILogger $logger) { parent::__construct($dbConnection, $userSession, $groupManager, $logger, - 'principals/calendar-rooms', 'rooms', 'ROOM'); + 'principals/calendar-rooms', 'room', 'ROOM'); } } diff --git a/apps/dav/lib/Migration/Version1011Date20190725113607.php b/apps/dav/lib/Migration/Version1011Date20190725113607.php new file mode 100644 index 00000000000..ac4019e64e6 --- /dev/null +++ b/apps/dav/lib/Migration/Version1011Date20190725113607.php @@ -0,0 +1,69 @@ +<?php + +declare(strict_types=1); + +namespace OCA\DAV\Migration; + +use Closure; +use Doctrine\DBAL\Types\Type; +use OCP\DB\ISchemaWrapper; +use OCP\Migration\SimpleMigrationStep; +use OCP\Migration\IOutput; + +/** + * Auto-generated migration step: Please modify to your needs! + */ +class Version1011Date20190725113607 extends SimpleMigrationStep { + + /** + * @param IOutput $output + * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper` + * @param array $options + * @return null|ISchemaWrapper + * @since 13.0.0 + */ + public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) { + /** @var ISchemaWrapper $schema */ + $schema = $schemaClosure(); + + $types = ['resource', 'room']; + foreach($types as $type) { + if (!$schema->hasTable($this->getMetadataTableName($type))) { + $table = $schema->createTable($this->getMetadataTableName($type)); + + $table->addColumn('id', Type::BIGINT, [ + 'autoincrement' => true, + 'notnull' => true, + 'length' => 11, + 'unsigned' => true, + ]); + $table->addColumn($type . '_id', Type::BIGINT, [ + 'notnull' => true, + 'length' => 11, + 'unsigned' => true, + ]); + $table->addColumn('key', Type::STRING, [ + 'notnull' => true, + 'length' => 255, + ]); + $table->addColumn('value', Type::STRING, [ + 'notnull' => false, + 'length' => 4000, + ]); + + $table->setPrimaryKey(['id']); + $table->addIndex([$type . '_id', 'key'], $this->getMetadataTableName($type) . '_idk'); + } + } + + return $schema; + } + + /** + * @param string $type + * @return string + */ + private function getMetadataTableName(string $type):string { + return 'calendar_' . $type . 's_md'; + } +} diff --git a/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php b/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php index e012d5e3f18..e451570b73f 100644 --- a/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php +++ b/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php @@ -26,6 +26,7 @@ use OCA\DAV\BackgroundJob\UpdateCalendarResourcesRoomsBackgroundJob; use OCA\DAV\CalDAV\CalDavBackend; use OCP\Calendar\BackendTemporarilyUnavailableException; +use OCP\Calendar\IMetadataProvider; use OCP\Calendar\Resource\IBackend; use OCP\Calendar\Resource\IManager as IResourceManager; use OCP\Calendar\Resource\IResource; @@ -61,34 +62,38 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { protected function tearDown() { $query = self::$realDatabase->getQueryBuilder(); $query->delete('calendar_resources')->execute(); + $query->delete('calendar_resources_md')->execute(); $query->delete('calendar_rooms')->execute(); + $query->delete('calendar_rooms_md')->execute(); } /** * Data in Cache: * resources: - * [backend1, res1, Beamer1, {}] - * [backend1, res2, TV1, {}] - * [backend2, res3, Beamer2, {}] - * [backend2, res4, TV2, {}] - * [backend3, res5, Beamer3, {}] - * [backend3, res6, Pointer, {foo, bar}] + * [backend1, res1, Beamer1, {}] - [] + * [backend1, res2, TV1, {}] - [] + * [backend2, res3, Beamer2, {}] - ['meta1' => 'value1', 'meta2' => 'value2'] + * [backend2, res4, TV2, {}] - ['meta1' => 'value1', 'meta3' => 'value3-old'] + * [backend3, res5, Beamer3, {}] - [] + * [backend3, res6, Pointer, {foo, bar}] - ['meta99' => 'value99'] * * Data in Backend: * backend1 gone * backend2 throws BackendTemporarilyUnavailableException - * [backend3, res6, Pointer123, {foo, biz}] - * [backend3, res7, Resource4, {biz}] - * [backend4, res8, Beamer, {}] - * [backend4, res9, Beamer2, {}] + * [backend3, res6, Pointer123, {foo, biz}] - ['meta99' => 'value99-new', 'meta123' => 'meta456'] + * [backend3, res7, Resource4, {biz}] - ['meta1' => 'value1'] + * [backend4, res8, Beamer, {}] - ['meta2' => 'value2'] + * [backend4, res9, Beamer2, {}] - [] * * Expected after run: - * [backend2, res3, Beamer2, {}] - * [backend2, res4, TV2, {}] - * [backend3, res6, Pointer123, {foo, biz}] - * [backend3, res7, Resource4, {biz}] - * [backend4, res8, Beamer, {}] - * [backend4, res9, Beamer2, {}] + * [backend1, res1, Beamer1, {}] - [] + * [backend1, res2, TV1, {}] - [] + * [backend2, res3, Beamer2, {}] - ['meta1' => 'value1', 'meta2' => 'value2'] + * [backend2, res4, TV2, {}] - ['meta1' => 'value1', 'meta3' => 'value3-old'] + * [backend3, res6, Pointer123, {foo, biz}] - ['meta99' => 'value99-new', 'meta123' => 'meta456'] + * [backend3, res7, Resource4, {biz}] - ['meta1' => 'value1'] + * [backend4, res8, Beamer, {}] - ['meta2' => 'value2'] + * [backend4, res9, Beamer2, {}] - [] */ public function testRun() { @@ -98,9 +103,9 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { $backend3 = $this->createMock(IBackend::class); $backend4 = $this->createMock(IBackend::class); - $res6 = $this->createMock(IResource::class); - $res7 = $this->createMock(IResource::class); - $res8 = $this->createMock(IResource::class); + $res6 = $this->createMock([IResource::class, IMetadataProvider::class]); + $res7 = $this->createMock([IResource::class, IMetadataProvider::class]); + $res8 = $this->createMock([IResource::class, IMetadataProvider::class]); $res9 = $this->createMock(IResource::class); $backend2->method('getBackendIdentifier') @@ -136,17 +141,51 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { $res6->method('getEMail')->will($this->returnValue('res6@foo.bar')); $res6->method('getBackend')->will($this->returnValue($backend3)); + $res6->method('getAllAvailableMetadataKeys')->will($this->returnValue(['meta99', 'meta123'])); + $res6->method('getMetadataForKey')->will($this->returnCallback(function($key) { + switch($key) { + case 'meta99': + return 'value99-new'; + + case 'meta123': + return 'meta456'; + + default: + return null; + } + })); + $res7->method('getId')->will($this->returnValue('res7')); $res7->method('getDisplayName')->will($this->returnValue('Resource4')); $res7->method('getGroupRestrictions')->will($this->returnValue(['biz'])); $res7->method('getEMail')->will($this->returnValue('res7@foo.bar')); $res7->method('getBackend')->will($this->returnValue($backend3)); + $res7->method('getAllAvailableMetadataKeys')->will($this->returnValue(['meta1'])); + $res7->method('getMetadataForKey')->will($this->returnCallback(function($key) { + switch($key) { + case 'meta1': + return 'value1'; + + default: + return null; + } + })); $res8->method('getId')->will($this->returnValue('res8')); $res8->method('getDisplayName')->will($this->returnValue('Beamer')); $res8->method('getGroupRestrictions')->will($this->returnValue([])); $res8->method('getEMail')->will($this->returnValue('res8@foo.bar')); $res8->method('getBackend')->will($this->returnValue($backend4)); + $res8->method('getAllAvailableMetadataKeys')->will($this->returnValue(['meta2'])); + $res8->method('getMetadataForKey')->will($this->returnCallback(function($key) { + switch($key) { + case 'meta2': + return 'value2'; + + default: + return null; + } + })); $res9->method('getId')->will($this->returnValue('res9')); $res9->method('getDisplayName')->will($this->returnValue('Beamer2')); @@ -173,14 +212,30 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { $query->select('*')->from('calendar_resources'); $rows = []; + $ids = []; $stmt = $query->execute(); while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + $ids[$row['backend_id'] . '::' . $row['resource_id']] = $row['id']; unset($row['id']); $rows[] = $row; } $this->assertEquals([ [ + 'backend_id' => 'backend1', + 'resource_id' => 'res1', + 'displayname' => 'Beamer1', + 'email' => 'res1@foo.bar', + 'group_restrictions' => '[]', + ], + [ + 'backend_id' => 'backend1', + 'resource_id' => 'res2', + 'displayname' => 'TV1', + 'email' => 'res2@foo.bar', + 'group_restrictions' => '[]', + ], + [ 'backend_id' => 'backend2', 'resource_id' => 'res3', 'displayname' => 'Beamer2', @@ -223,6 +278,59 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { 'group_restrictions' => '[]', ], ], $rows); + + $query2 = self::$realDatabase->getQueryBuilder(); + $query2->select('*')->from('calendar_resources_md'); + + $rows2 = []; + $stmt = $query2->execute(); + while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + unset($row['id']); + $rows2[] = $row; + } + + $this->assertEquals([ + [ + 'resource_id' => $ids['backend2::res3'], + 'key' => 'meta1', + 'value' => 'value1', + ], + [ + 'resource_id' => $ids['backend2::res3'], + 'key' => 'meta2', + 'value' => 'value2', + ], + [ + 'resource_id' => $ids['backend2::res4'], + 'key' => 'meta1', + 'value' => 'value1', + ], + [ + 'resource_id' => $ids['backend2::res4'], + 'key' => 'meta3', + 'value' => 'value3-old', + ], + [ + 'resource_id' => $ids['backend3::res6'], + 'key' => 'meta99', + 'value' => 'value99-new', + ], + [ + 'resource_id' => $ids['backend3::res7'], + 'key' => 'meta1', + 'value' => 'value1', + ], + [ + 'resource_id' => $ids['backend3::res6'], + 'key' => 'meta123', + 'value' => 'meta456', + ], + [ + 'resource_id' => $ids['backend4::res8'], + 'key' => 'meta2', + 'value' => 'value2', + ] + ], $rows2); } protected function createTestResourcesInCache() { @@ -236,6 +344,7 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { 'group_restrictions' => $query->createNamedParameter('[]'), ]) ->execute(); + $query->insert('calendar_resources') ->values([ 'backend_id' => $query->createNamedParameter('backend1'), @@ -245,6 +354,7 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { 'group_restrictions' => $query->createNamedParameter('[]'), ]) ->execute(); + $query->insert('calendar_resources') ->values([ 'backend_id' => $query->createNamedParameter('backend2'), @@ -254,6 +364,8 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { 'group_restrictions' => $query->createNamedParameter('[]'), ]) ->execute(); + $id3 = $query->getLastInsertId(); + $query->insert('calendar_resources') ->values([ 'backend_id' => $query->createNamedParameter('backend2'), @@ -263,6 +375,8 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { 'group_restrictions' => $query->createNamedParameter('[]'), ]) ->execute(); + $id4 = $query->getLastInsertId(); + $query->insert('calendar_resources') ->values([ 'backend_id' => $query->createNamedParameter('backend3'), @@ -272,6 +386,7 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { 'group_restrictions' => $query->createNamedParameter('[]'), ]) ->execute(); + $query->insert('calendar_resources') ->values([ 'backend_id' => $query->createNamedParameter('backend3'), @@ -281,5 +396,42 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { 'group_restrictions' => $query->createNamedParameter('["foo", "bar"]'), ]) ->execute(); + $id6 = $query->getLastInsertId(); + + $query->insert('calendar_resources_md') + ->values([ + 'resource_id' => $query->createNamedParameter($id3), + 'key' => $query->createNamedParameter('meta1'), + 'value' => $query->createNamedParameter('value1') + ]) + ->execute(); + $query->insert('calendar_resources_md') + ->values([ + 'resource_id' => $query->createNamedParameter($id3), + 'key' => $query->createNamedParameter('meta2'), + 'value' => $query->createNamedParameter('value2') + ]) + ->execute(); + $query->insert('calendar_resources_md') + ->values([ + 'resource_id' => $query->createNamedParameter($id4), + 'key' => $query->createNamedParameter('meta1'), + 'value' => $query->createNamedParameter('value1') + ]) + ->execute(); + $query->insert('calendar_resources_md') + ->values([ + 'resource_id' => $query->createNamedParameter($id4), + 'key' => $query->createNamedParameter('meta3'), + 'value' => $query->createNamedParameter('value3-old') + ]) + ->execute(); + $query->insert('calendar_resources_md') + ->values([ + 'resource_id' => $query->createNamedParameter($id6), + 'key' => $query->createNamedParameter('meta99'), + 'value' => $query->createNamedParameter('value99') + ]) + ->execute(); } } diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php index 19da1782ccd..f4019d86e2b 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php @@ -22,7 +22,6 @@ namespace OCA\DAV\Tests\unit\CalDAV\ResourceBooking; use OCP\DB\QueryBuilder\IQueryBuilder; -use OCP\IDBConnection; use OCP\IGroupManager; use OCP\ILogger; use OCP\IUser; @@ -35,9 +34,6 @@ abstract class AbstractPrincipalBackendTest extends TestCase { /** @var \OCA\DAV\CalDAV\ResourceBooking\ResourcePrincipalBackend|\OCA\DAV\CalDAV\ResourceBooking\RoomPrincipalBackend */ protected $principalBackend; - /** @var IDBConnection|\PHPUnit_Framework_MockObject_MockObject */ - protected $dbConnection; - /** @var IUserSession|\PHPUnit_Framework_MockObject_MockObject */ protected $userSession; @@ -48,7 +44,13 @@ abstract class AbstractPrincipalBackendTest extends TestCase { protected $logger; /** @var string */ - protected $expectedDbTable; + protected $mainDbTable; + + /** @var string */ + protected $metadataDbTable; + + /** @var string */ + protected $foreignKey; /** @var string */ protected $principalPrefix; @@ -59,222 +61,92 @@ abstract class AbstractPrincipalBackendTest extends TestCase { public function setUp() { parent::setUp(); - $this->dbConnection = $this->createMock(IDBConnection::class); $this->userSession = $this->createMock(IUserSession::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->logger = $this->createMock(ILogger::class); } - public function testGetPrincipalsByPrefix() { - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $this->dbConnection->expects($this->once()) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(2)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); + protected function tearDown() { + $query = self::$realDatabase->getQueryBuilder(); - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '123', - 'email' => 'foo@bar.com', - 'displayname' => 'Resource 123' - ])); - $stmt->expects($this->at(1)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 1, - 'backend_id' => 'ldap', - 'resource_id' => '123', - 'email' => 'ldap@bar.com', - 'displayname' => 'Resource 123 ldap' - ])); - $stmt->expects($this->at(2)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 2, - 'backend_id' => 'db', - 'resource_id' => '456', - 'email' => 'bli@bar.com', - 'displayname' => 'Resource 456' - ])); - $stmt->expects($this->at(3)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue(null)); - $stmt->expects($this->at(4)) - ->method('closeCursor') - ->with(); + $query->delete('calendar_resources')->execute(); + $query->delete('calendar_resources_md')->execute(); + $query->delete('calendar_rooms')->execute(); + $query->delete('calendar_rooms_md')->execute(); + } + public function testGetPrincipalsByPrefix() { $actual = $this->principalBackend->getPrincipalsByPrefix($this->principalPrefix); + $this->assertEquals([ [ - 'uri' => $this->principalPrefix . '/db-123', - '{DAV:}displayname' => 'Resource 123', - '{http://sabredav.org/ns}email-address' => 'foo@bar.com', + 'uri' => $this->principalPrefix . '/backend1-res1', + '{DAV:}displayname' => 'Beamer1', + '{http://sabredav.org/ns}email-address' => 'res1@foo.bar', '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType, ], [ - 'uri' => $this->principalPrefix . '/ldap-123', - '{DAV:}displayname' => 'Resource 123 ldap', - '{http://sabredav.org/ns}email-address' => 'ldap@bar.com', + 'uri' => $this->principalPrefix . '/backend1-res2', + '{DAV:}displayname' => 'TV1', + '{http://sabredav.org/ns}email-address' => 'res2@foo.bar', '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType, ], [ - 'uri' => $this->principalPrefix . '/db-456', - '{DAV:}displayname' => 'Resource 456', - '{http://sabredav.org/ns}email-address' => 'bli@bar.com', + 'uri' => $this->principalPrefix . '/backend2-res3', + '{DAV:}displayname' => 'Beamer2', + '{http://sabredav.org/ns}email-address' => 'res3@foo.bar', '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType, + '{http://nextcloud.com/ns}foo' => 'value1', + '{http://nextcloud.com/ns}meta2' => 'value2', ], + [ + 'uri' => $this->principalPrefix . '/backend2-res4', + '{DAV:}displayname' => 'TV2', + '{http://sabredav.org/ns}email-address' => 'res4@foo.bar', + '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType, + '{http://nextcloud.com/ns}meta1' => 'value1', + '{http://nextcloud.com/ns}meta3' => 'value3-old', + ], + [ + 'uri' => $this->principalPrefix . '/backend3-res5', + '{DAV:}displayname' => 'Beamer3', + '{http://sabredav.org/ns}email-address' => 'res5@foo.bar', + '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType, + ], + [ + 'uri' => $this->principalPrefix . '/backend3-res6', + '{DAV:}displayname' => 'Pointer', + '{http://sabredav.org/ns}email-address' => 'res6@foo.bar', + '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType, + '{http://nextcloud.com/ns}meta99' => 'value99' + ] ], $actual); } public function testGetNoPrincipalsByPrefixForWrongPrincipalPrefix() { - $this->dbConnection->expects($this->never()) - ->method('getQueryBuilder'); - $actual = $this->principalBackend->getPrincipalsByPrefix('principals/users'); $this->assertEquals([], $actual); } public function testGetPrincipalByPath() { - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - $queryBuilder->method('expr') - ->will($this->returnValue($expr)); - $expr->method('eq') - ->will($this->returnValueMap([ - ['backend_id', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'], - ['resource_id', 'createNamedParameter-2', null, 'WHERE_CLAUSE_2'], - ])); - $queryBuilder->method('createNamedParameter') - ->will($this->returnValueMap([ - ['db', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ['123', \PDO::PARAM_STR, null, 'createNamedParameter-2'], - ])); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(4)) - ->method('where') - ->with('WHERE_CLAUSE_1') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(7)) - ->method('andWhere') - ->with('WHERE_CLAUSE_2') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(8)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); - - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '123', - 'email' => 'foo@bar.com', - 'displayname' => 'Resource 123' - ])); - - $actual = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/db-123'); + $actual = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/backend2-res3'); $this->assertEquals([ - 'uri' => $this->principalPrefix . '/db-123', - '{DAV:}displayname' => 'Resource 123', - '{http://sabredav.org/ns}email-address' => 'foo@bar.com', + 'uri' => $this->principalPrefix . '/backend2-res3', + '{DAV:}displayname' => 'Beamer2', + '{http://sabredav.org/ns}email-address' => 'res3@foo.bar', '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->expectedCUType, + '{http://nextcloud.com/ns}foo' => 'value1', + '{http://nextcloud.com/ns}meta2' => 'value2', ], $actual); } public function testGetPrincipalByPathNotFound() { - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - $queryBuilder->method('expr') - ->will($this->returnValue($expr)); - $expr->method('eq') - ->will($this->returnValueMap([ - ['backend_id', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'], - ['resource_id', 'createNamedParameter-2', null, 'WHERE_CLAUSE_2'], - ])); - $queryBuilder->method('createNamedParameter') - ->will($this->returnValueMap([ - ['db', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ['123', \PDO::PARAM_STR, null, 'createNamedParameter-2'], - ])); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(4)) - ->method('where') - ->with('WHERE_CLAUSE_1') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(7)) - ->method('andWhere') - ->with('WHERE_CLAUSE_2') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(8)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); - - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue(false)); - $actual = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/db-123'); $this->assertEquals(null, $actual); } public function testGetPrincipalByPathWrongPrefix() { - $this->dbConnection->expects($this->never()) - ->method('getQueryBuilder'); - $actual = $this->principalBackend->getPrincipalByPath('principals/users/foo-bar'); $this->assertEquals(null, $actual); } @@ -318,182 +190,9 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->with($user) ->will($this->returnValue(['group1', 'group2'])); - $queryBuilder1 = $this->createMock(IQueryBuilder::class); - $queryBuilder2 = $this->createMock(IQueryBuilder::class); - $stmt1 = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $stmt2 = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr1 = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - $expr2 = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder1)); - $this->dbConnection->expects($this->at(1)) - ->method('escapeLikeParameter') - ->with('foo') - ->will($this->returnValue('escapedFoo')); - $this->dbConnection->expects($this->at(2)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder2)); - $this->dbConnection->expects($this->at(3)) - ->method('escapeLikeParameter') - ->with('bar') - ->will($this->returnValue('escapedBar')); - - $queryBuilder1->method('expr') - ->will($this->returnValue($expr1)); - $queryBuilder2->method('expr') - ->will($this->returnValue($expr2)); - - $expr1->method('iLike') - ->will($this->returnValueMap([ - ['email', 'createNamedParameter-1', null, 'ILIKE_CLAUSE_1'], - ])); - $expr2->method('iLike') - ->will($this->returnValueMap([ - ['displayname', 'createNamedParameter-2', null, 'ILIKE_CLAUSE_2'], - ])); - - $queryBuilder1->method('expr') - ->will($this->returnValue($expr1)); - $queryBuilder2->method('expr') - ->will($this->returnValue($expr2)); - - $queryBuilder1->method('createNamedParameter') - ->will($this->returnValueMap([ - ['%escapedFoo%', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ])); - $queryBuilder2->method('createNamedParameter') - ->will($this->returnValueMap([ - ['%escapedBar%', \PDO::PARAM_STR, null, 'createNamedParameter-2'], - ])); - - $queryBuilder1->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder1)); - $queryBuilder1->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder1)); - $queryBuilder1->expects($this->at(4)) - ->method('where') - ->with('ILIKE_CLAUSE_1') - ->will($this->returnValue($queryBuilder1)); - $queryBuilder1->expects($this->at(5)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt1)); - - $queryBuilder2->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder2)); - $queryBuilder2->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder2)); - $queryBuilder2->expects($this->at(4)) - ->method('where') - ->with('ILIKE_CLAUSE_2') - ->will($this->returnValue($queryBuilder2)); - $queryBuilder2->expects($this->at(5)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt2)); - - $stmt1->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '1', - 'email' => '1', - 'displayname' => 'Resource 1', - 'group_restrictions' => null, - ])); - $stmt1->expects($this->at(1)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 1, - 'backend_id' => 'db', - 'resource_id' => '2', - 'email' => '2', - 'displayname' => 'Resource 2', - 'group_restrictions' => '', - ])); - $stmt1->expects($this->at(2)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 2, - 'backend_id' => 'db', - 'resource_id' => '3', - 'email' => '3', - 'displayname' => 'Resource 3', - 'group_restrictions' => '["group3"]', - ])); - $stmt1->expects($this->at(3)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 99, - 'backend_id' => 'db', - 'resource_id' => '99', - 'email' => '99', - 'displayname' => 'Resource 99', - 'group_restrictions' => '["group1", "group2"]', - ])); - $stmt1->expects($this->at(4)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue(null)); - - $stmt2->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '4', - 'email' => '4', - 'displayname' => 'Resource 4', - 'group_restrictions' => '[]' - ])); - $stmt2->expects($this->at(1)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 1, - 'backend_id' => 'db', - 'resource_id' => '5', - 'email' => '5', - 'displayname' => 'Resource 5', - 'group_restrictions' => '["group1", "group5"]' - ])); - $stmt2->expects($this->at(2)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 99, - 'backend_id' => 'db', - 'resource_id' => '99', - 'email' => '99', - 'displayname' => 'Resource 99', - 'group_restrictions' => '["group1", "group2"]', - ])); - $stmt2->expects($this->at(3)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue(null)); - $actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [ '{http://sabredav.org/ns}email-address' => 'foo', - '{DAV:}displayname' => 'bar', + '{DAV:}displayname' => 'Beamer', ], $test); $this->assertEquals( @@ -507,133 +206,55 @@ abstract class AbstractPrincipalBackendTest extends TestCase { // at that point, so we need this hack return [ [[ - '%prefix%/db-99' + '%prefix%/backend1-res1', + '%prefix%/backend2-res3', ], 'allof'], [[ - '%prefix%/db-1', - '%prefix%/db-2', - '%prefix%/db-99', - '%prefix%/db-4', - '%prefix%/db-5', + '%prefix%/backend1-res1', + '%prefix%/backend1-res2', + '%prefix%/backend2-res3', + '%prefix%/backend2-res4', + '%prefix%/backend3-res6', ], 'anyof'], ]; } - public function testSearchPrincipalsByCalendarUserAddressSet() { + public function testSearchPrincipalsByMetadataKey() { $user = $this->createMock(IUser::class); - $this->userSession->expects($this->exactly(2)) + $this->userSession->expects($this->once()) ->method('getUser') ->with() ->will($this->returnValue($user)); - $this->groupManager->expects($this->exactly(2)) + $this->groupManager->expects($this->once()) ->method('getUserGroupIds') ->with($user) ->will($this->returnValue(['group1', 'group2'])); - $queryBuilder1 = $this->createMock(IQueryBuilder::class); - $stmt1 = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr1 = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder1)); - $this->dbConnection->expects($this->at(1)) - ->method('escapeLikeParameter') - ->with('foo') - ->will($this->returnValue('escapedFoo')); - - $queryBuilder1->method('expr') - ->will($this->returnValue($expr1)); - - $expr1->method('iLike') - ->will($this->returnValueMap([ - ['email', 'createNamedParameter-1', null, 'ILIKE_CLAUSE_1'], - ])); - - $queryBuilder1->method('expr') - ->will($this->returnValue($expr1)); + $actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [ + '{http://nextcloud.com/ns}meta3' => 'value', + ]); - $queryBuilder1->method('createNamedParameter') - ->will($this->returnValueMap([ - ['%escapedFoo%', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ])); + $this->assertEquals([ + $this->principalPrefix . '/backend2-res4', + ], $actual); + } - $queryBuilder1->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder1)); - $queryBuilder1->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder1)); - $queryBuilder1->expects($this->at(4)) - ->method('where') - ->with('ILIKE_CLAUSE_1') - ->will($this->returnValue($queryBuilder1)); - $queryBuilder1->expects($this->at(5)) - ->method('execute') + public function testSearchPrincipalsByCalendarUserAddressSet() { + $user = $this->createMock(IUser::class); + $this->userSession->method('getUser') ->with() - ->will($this->returnValue($stmt1)); - - $stmt1->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '1', - 'email' => '1', - 'displayname' => 'Resource 1', - 'group_restrictions' => null, - ])); - $stmt1->expects($this->at(1)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 1, - 'backend_id' => 'db', - 'resource_id' => '2', - 'email' => '2', - 'displayname' => 'Resource 2', - 'group_restrictions' => '', - ])); - $stmt1->expects($this->at(2)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 2, - 'backend_id' => 'db', - 'resource_id' => '3', - 'email' => '3', - 'displayname' => 'Resource 3', - 'group_restrictions' => '["group3"]', - ])); - $stmt1->expects($this->at(3)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 99, - 'backend_id' => 'db', - 'resource_id' => '99', - 'email' => '99', - 'displayname' => 'Resource 99', - 'group_restrictions' => '["group1", "group2"]', - ])); - $stmt1->expects($this->at(4)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue(null)); + ->will($this->returnValue($user)); + $this->groupManager->method('getUserGroupIds') + ->with($user) + ->will($this->returnValue(['group1', 'group2'])); $actual = $this->principalBackend->searchPrincipals($this->principalPrefix, [ - '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set' => 'foo', + '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set' => 'res2@foo.bar', ]); $this->assertEquals( str_replace('%prefix%', $this->principalPrefix, [ - '%prefix%/db-1', - '%prefix%/db-2', - '%prefix%/db-99', + '%prefix%/backend1-res2', ]), $actual); } @@ -643,8 +264,6 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->method('getUser'); $this->groupManager->expects($this->never()) ->method('getUserGroupIds'); - $this->dbConnection->expects($this->never()) - ->method('getQueryBuilder'); $this->principalBackend->searchPrincipals($this->principalPrefix, []); } @@ -654,8 +273,6 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->method('getUser'); $this->groupManager->expects($this->never()) ->method('getUserGroupIds'); - $this->dbConnection->expects($this->never()) - ->method('getQueryBuilder'); $this->principalBackend->searchPrincipals('principals/users', [ '{http://sabredav.org/ns}email-address' => 'foo' @@ -673,56 +290,8 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->with($user) ->will($this->returnValue(['group1', 'group2'])); - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - $queryBuilder->method('expr') - ->will($this->returnValue($expr)); - $expr->method('eq') - ->will($this->returnValueMap([ - ['email', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'], - ])); - $queryBuilder->method('createNamedParameter') - ->will($this->returnValueMap([ - ['foo@bar.com', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ])); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(4)) - ->method('where') - ->with('WHERE_CLAUSE_1') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(5)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); - - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '123', - 'email' => 'foo@bar.com', - 'displayname' => 'Resource 123', - 'group_restrictions' => '["group1"]', - ])); - - $actual = $this->principalBackend->findByUri('mailto:foo@bar.com', $this->principalPrefix); - $this->assertEquals($this->principalPrefix . '/db-123', $actual); + $actual = $this->principalBackend->findByUri('mailto:res1@foo.bar', $this->principalPrefix); + $this->assertEquals($this->principalPrefix . '/backend1-res1', $actual); } public function testFindByUriByEmailForbiddenResource() { @@ -736,55 +305,7 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->with($user) ->will($this->returnValue(['group1', 'group2'])); - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - $queryBuilder->method('expr') - ->will($this->returnValue($expr)); - $expr->method('eq') - ->will($this->returnValueMap([ - ['email', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'], - ])); - $queryBuilder->method('createNamedParameter') - ->will($this->returnValueMap([ - ['foo@bar.com', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ])); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(4)) - ->method('where') - ->with('WHERE_CLAUSE_1') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(5)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); - - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '123', - 'email' => 'foo@bar.com', - 'displayname' => 'Resource 123', - 'group_restrictions' => '["group3"]', - ])); - - $actual = $this->principalBackend->findByUri('mailto:foo@bar.com', $this->principalPrefix); + $actual = $this->principalBackend->findByUri('mailto:res5@foo.bar', $this->principalPrefix); $this->assertEquals(null, $actual); } @@ -799,48 +320,7 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->with($user) ->will($this->returnValue(['group1', 'group2'])); - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - $queryBuilder->method('expr') - ->will($this->returnValue($expr)); - $expr->method('eq') - ->will($this->returnValueMap([ - ['email', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'], - ])); - $queryBuilder->method('createNamedParameter') - ->will($this->returnValueMap([ - ['foo@bar.com', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ])); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(4)) - ->method('where') - ->with('WHERE_CLAUSE_1') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(5)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); - - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue(null)); - - $actual = $this->principalBackend->findByUri('mailto:foo@bar.com', $this->principalPrefix); + $actual = $this->principalBackend->findByUri('mailto:res99@foo.bar', $this->principalPrefix); $this->assertEquals(null, $actual); } @@ -855,56 +335,8 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->with($user) ->will($this->returnValue(['group1', 'group2'])); - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - $queryBuilder->method('expr') - ->will($this->returnValue($expr)); - $expr->method('eq') - ->will($this->returnValueMap([ - ['email', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'], - ])); - $queryBuilder->method('createNamedParameter') - ->will($this->returnValueMap([ - ['foo@bar.com', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ])); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(4)) - ->method('where') - ->with('WHERE_CLAUSE_1') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(5)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); - - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '123', - 'email' => 'foo@bar.com', - 'displayname' => 'Resource 123', - 'group_restrictions' => '["group1"]', - ])); - - $actual = $this->principalBackend->findByUri('mailto:foo@bar.com', $this->principalPrefix); - $this->assertEquals($this->principalPrefix . '/db-123', $actual); + $actual = $this->principalBackend->findByUri('mailto:res6@foo.bar', $this->principalPrefix); + $this->assertEquals($this->principalPrefix . '/backend3-res6', $actual); } public function testFindByUriByPrincipalForbiddenResource() { @@ -918,61 +350,7 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->with($user) ->will($this->returnValue(['group1', 'group2'])); - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - $queryBuilder->method('expr') - ->will($this->returnValue($expr)); - $expr->method('eq') - ->will($this->returnValueMap([ - ['backend_id', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'], - ['resource_id', 'createNamedParameter-2', null, 'WHERE_CLAUSE_2'], - ])); - $queryBuilder->method('createNamedParameter') - ->will($this->returnValueMap([ - ['db', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ['123', \PDO::PARAM_STR, null, 'createNamedParameter-2'], - ])); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(4)) - ->method('where') - ->with('WHERE_CLAUSE_1') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(7)) - ->method('andWhere') - ->with('WHERE_CLAUSE_2') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(8)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); - - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue([ - 'id' => 0, - 'backend_id' => 'db', - 'resource_id' => '123', - 'email' => 'foo@bar.com', - 'displayname' => 'Resource 123', - 'group_restrictions' => '["group3"]', - ])); - - $actual = $this->principalBackend->findByUri('principal:' . $this->principalPrefix . '/db-123', $this->principalPrefix); + $actual = $this->principalBackend->findByUri('principal:' . $this->principalPrefix . '/backend3-res5', $this->principalPrefix); $this->assertEquals(null, $actual); } @@ -987,53 +365,6 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ->with($user) ->will($this->returnValue(['group1', 'group2'])); - $queryBuilder = $this->createMock(IQueryBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - - $this->dbConnection->expects($this->at(0)) - ->method('getQueryBuilder') - ->with() - ->will($this->returnValue($queryBuilder)); - $queryBuilder->method('expr') - ->will($this->returnValue($expr)); - $expr->method('eq') - ->will($this->returnValueMap([ - ['backend_id', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'], - ['resource_id', 'createNamedParameter-2', null, 'WHERE_CLAUSE_2'], - ])); - $queryBuilder->method('createNamedParameter') - ->will($this->returnValueMap([ - ['db', \PDO::PARAM_STR, null, 'createNamedParameter-1'], - ['123', \PDO::PARAM_STR, null, 'createNamedParameter-2'], - ])); - - $queryBuilder->expects($this->at(0)) - ->method('select') - ->with(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(1)) - ->method('from') - ->with($this->expectedDbTable) - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(4)) - ->method('where') - ->with('WHERE_CLAUSE_1') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(7)) - ->method('andWhere') - ->with('WHERE_CLAUSE_2') - ->will($this->returnValue($queryBuilder)); - $queryBuilder->expects($this->at(8)) - ->method('execute') - ->with() - ->will($this->returnValue($stmt)); - - $stmt->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->will($this->returnValue(null)); - $actual = $this->principalBackend->findByUri('principal:' . $this->principalPrefix . '/db-123', $this->principalPrefix); $this->assertEquals(null, $actual); } @@ -1053,4 +384,106 @@ abstract class AbstractPrincipalBackendTest extends TestCase { $this->assertEquals(null, $actual); } + protected function createTestDatasetInDb() { + $query = self::$realDatabase->getQueryBuilder(); + $query->insert($this->mainDbTable) + ->values([ + 'backend_id' => $query->createNamedParameter('backend1'), + 'resource_id' => $query->createNamedParameter('res1'), + 'email' => $query->createNamedParameter('res1@foo.bar'), + 'displayname' => $query->createNamedParameter('Beamer1'), + 'group_restrictions' => $query->createNamedParameter('[]'), + ]) + ->execute(); + + $query->insert($this->mainDbTable) + ->values([ + 'backend_id' => $query->createNamedParameter('backend1'), + 'resource_id' => $query->createNamedParameter('res2'), + 'email' => $query->createNamedParameter('res2@foo.bar'), + 'displayname' => $query->createNamedParameter('TV1'), + 'group_restrictions' => $query->createNamedParameter('[]'), + ]) + ->execute(); + + $query->insert($this->mainDbTable) + ->values([ + 'backend_id' => $query->createNamedParameter('backend2'), + 'resource_id' => $query->createNamedParameter('res3'), + 'email' => $query->createNamedParameter('res3@foo.bar'), + 'displayname' => $query->createNamedParameter('Beamer2'), + 'group_restrictions' => $query->createNamedParameter('[]'), + ]) + ->execute(); + $id3 = $query->getLastInsertId(); + + $query->insert($this->mainDbTable) + ->values([ + 'backend_id' => $query->createNamedParameter('backend2'), + 'resource_id' => $query->createNamedParameter('res4'), + 'email' => $query->createNamedParameter('res4@foo.bar'), + 'displayname' => $query->createNamedParameter('TV2'), + 'group_restrictions' => $query->createNamedParameter('[]'), + ]) + ->execute(); + $id4 = $query->getLastInsertId(); + + $query->insert($this->mainDbTable) + ->values([ + 'backend_id' => $query->createNamedParameter('backend3'), + 'resource_id' => $query->createNamedParameter('res5'), + 'email' => $query->createNamedParameter('res5@foo.bar'), + 'displayname' => $query->createNamedParameter('Beamer3'), + 'group_restrictions' => $query->createNamedParameter('["foo", "bar"]'), + ]) + ->execute(); + + $query->insert($this->mainDbTable) + ->values([ + 'backend_id' => $query->createNamedParameter('backend3'), + 'resource_id' => $query->createNamedParameter('res6'), + 'email' => $query->createNamedParameter('res6@foo.bar'), + 'displayname' => $query->createNamedParameter('Pointer'), + 'group_restrictions' => $query->createNamedParameter('["group1", "bar"]'), + ]) + ->execute(); + $id6 = $query->getLastInsertId(); + + $query->insert($this->metadataDbTable) + ->values([ + $this->foreignKey => $query->createNamedParameter($id3), + 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}foo'), + 'value' => $query->createNamedParameter('value1') + ]) + ->execute(); + $query->insert($this->metadataDbTable) + ->values([ + $this->foreignKey => $query->createNamedParameter($id3), + 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta2'), + 'value' => $query->createNamedParameter('value2') + ]) + ->execute(); + $query->insert($this->metadataDbTable) + ->values([ + $this->foreignKey => $query->createNamedParameter($id4), + 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta1'), + 'value' => $query->createNamedParameter('value1') + ]) + ->execute(); + $query->insert($this->metadataDbTable) + ->values([ + $this->foreignKey => $query->createNamedParameter($id4), + 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta3'), + 'value' => $query->createNamedParameter('value3-old') + ]) + ->execute(); + $query->insert($this->metadataDbTable) + ->values([ + $this->foreignKey => $query->createNamedParameter($id6), + 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta99'), + 'value' => $query->createNamedParameter('value99') + ]) + ->execute(); + } + } diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/ResourcePrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/ResourcePrincipalBackendTest.php index d3c774417c0..3787e4df951 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/ResourcePrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/ResourcePrincipalBackendTest.php @@ -27,10 +27,16 @@ Class ResourcePrincipalBackendTest extends AbstractPrincipalBackendTest { public function setUp() { parent::setUp(); - $this->principalBackend = new ResourcePrincipalBackend($this->dbConnection, + $this->principalBackend = new ResourcePrincipalBackend(self::$realDatabase, $this->userSession, $this->groupManager, $this->logger); - $this->expectedDbTable = 'calendar_resources'; + + $this->mainDbTable = 'calendar_resources'; + $this->metadataDbTable = 'calendar_resources_md'; + $this->foreignKey = 'resource_id'; + $this->principalPrefix = 'principals/calendar-resources'; $this->expectedCUType = 'RESOURCE'; + + $this->createTestDatasetInDb(); } } diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/RoomPrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/RoomPrincipalBackendTest.php index a10aaa26b35..9b259c30adf 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/RoomPrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/RoomPrincipalBackendTest.php @@ -27,10 +27,16 @@ Class RoomPrincipalBackendTest extends AbstractPrincipalBackendTest { public function setUp() { parent::setUp(); - $this->principalBackend = new RoomPrincipalBackend($this->dbConnection, + $this->principalBackend = new RoomPrincipalBackend(self::$realDatabase, $this->userSession, $this->groupManager, $this->logger); - $this->expectedDbTable = 'calendar_rooms'; + + $this->mainDbTable = 'calendar_rooms'; + $this->metadataDbTable = 'calendar_rooms_md'; + $this->foreignKey = 'room_id'; + $this->principalPrefix = 'principals/calendar-rooms'; $this->expectedCUType = 'ROOM'; + + $this->createTestDatasetInDb(); } } |