aboutsummaryrefslogtreecommitdiffstats
path: root/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php
diff options
context:
space:
mode:
Diffstat (limited to 'apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php')
-rw-r--r--apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php259
1 files changed, 140 insertions, 119 deletions
diff --git a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php
index bfe4e938a5d..68bb3373346 100644
--- a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php
+++ b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php
@@ -1,59 +1,31 @@
<?php
+
/**
- * @copyright 2019, Georg Ehrke <oc.list@georgehrke.com>
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Georg Ehrke <oc.list@georgehrke.com>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
*/
-
namespace OCA\DAV\CalDAV\ResourceBooking;
use OCA\DAV\CalDAV\Proxy\ProxyMapper;
use OCA\DAV\Traits\PrincipalProxyTrait;
+use OCP\Calendar\Resource\IResourceMetadata;
+use OCP\Calendar\Room\IRoomMetadata;
+use OCP\DB\Exception;
+use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\IGroupManager;
-use OCP\ILogger;
use OCP\IUserSession;
+use Psr\Log\LoggerInterface;
use Sabre\DAV\PropPatch;
use Sabre\DAVACL\PrincipalBackend\BackendInterface;
+use function array_intersect;
+use function array_map;
+use function array_merge;
+use function array_unique;
+use function array_values;
abstract class AbstractPrincipalBackend implements BackendInterface {
- /** @var IDBConnection */
- private $db;
-
- /** @var IUserSession */
- private $userSession;
-
- /** @var IGroupManager */
- private $groupManager;
-
- /** @var ILogger */
- private $logger;
-
- /** @var ProxyMapper */
- private $proxyMapper;
-
- /** @var string */
- private $principalPrefix;
-
/** @var string */
private $dbTableName;
@@ -63,36 +35,19 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
/** @var string */
private $dbForeignKeyName;
- /** @var string */
- private $cuType;
-
- /**
- * @param IDBConnection $dbConnection
- * @param IUserSession $userSession
- * @param IGroupManager $groupManager
- * @param ILogger $logger
- * @param string $principalPrefix
- * @param string $dbPrefix
- * @param string $cuType
- */
- public function __construct(IDBConnection $dbConnection,
- IUserSession $userSession,
- IGroupManager $groupManager,
- ILogger $logger,
- ProxyMapper $proxyMapper,
- string $principalPrefix,
- string $dbPrefix,
- string $cuType) {
- $this->db = $dbConnection;
- $this->userSession = $userSession;
- $this->groupManager = $groupManager;
- $this->logger = $logger;
- $this->proxyMapper = $proxyMapper;
- $this->principalPrefix = $principalPrefix;
+ public function __construct(
+ private IDBConnection $db,
+ private IUserSession $userSession,
+ private IGroupManager $groupManager,
+ private LoggerInterface $logger,
+ private ProxyMapper $proxyMapper,
+ private string $principalPrefix,
+ string $dbPrefix,
+ private string $cuType,
+ ) {
$this->dbTableName = 'calendar_' . $dbPrefix . 's';
$this->dbMetaDataTableName = $this->dbTableName . '_md';
$this->dbForeignKeyName = $dbPrefix . '_id';
- $this->cuType = $cuType;
}
use PrincipalProxyTrait;
@@ -110,7 +65,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
* @param string $prefixPath
* @return string[]
*/
- public function getPrincipalsByPrefix($prefixPath) {
+ public function getPrincipalsByPrefix($prefixPath): array {
$principals = [];
if ($prefixPath === $this->principalPrefix) {
@@ -131,8 +86,8 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
$metaDataById[$metaDataRow[$this->dbForeignKeyName]] = [];
}
- $metaDataById[$metaDataRow[$this->dbForeignKeyName]][$metaDataRow['key']] =
- $metaDataRow['value'];
+ $metaDataById[$metaDataRow[$this->dbForeignKeyName]][$metaDataRow['key']]
+ = $metaDataRow['value'];
}
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
@@ -152,20 +107,21 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
}
/**
- * Returns a specific principal, specified by it's path.
+ * Returns a specific principal, specified by its path.
* The returned structure should be the exact same as from
* getPrincipalsByPrefix.
*
- * @param string $path
+ * @param string $prefixPath
+ *
* @return array
*/
public function getPrincipalByPath($path) {
- if (strpos($path, $this->principalPrefix) !== 0) {
+ if (!str_starts_with($path, $this->principalPrefix)) {
return null;
}
- list(, $name) = \Sabre\Uri\split($path);
+ [, $name] = \Sabre\Uri\split($path);
- list($backendId, $resourceId) = explode('-', $name, 2);
+ [$backendId, $resourceId] = explode('-', $name, 2);
$query = $this->db->getQueryBuilder();
$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
@@ -196,9 +152,9 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
/**
* @param int $id
- * @return array|null
+ * @return string[]|null
*/
- public function getPrincipalById($id):?array {
+ public function getPrincipalById($id): ?array {
$query = $this->db->getQueryBuilder();
$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
->from($this->dbTableName)
@@ -230,14 +186,14 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
* @param PropPatch $propPatch
* @return int
*/
- public function updatePrincipal($path, PropPatch $propPatch) {
+ public function updatePrincipal($path, PropPatch $propPatch): int {
return 0;
}
/**
* @param string $prefixPath
- * @param array $searchProperties
* @param string $test
+ *
* @return array
*/
public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
@@ -303,16 +259,17 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
], 'anyof');
break;
- default:
- $rowsByMetadata = $this->searchPrincipalsByMetadataKey($prop, $value);
- $filteredRows = array_filter($rowsByMetadata, function ($row) use ($usersGroups) {
- return $this->isAllowedToAccessResource($row, $usersGroups);
- });
+ case IRoomMetadata::FEATURES:
+ $results[] = $this->searchPrincipalsByRoomFeature($prop, $value);
+ break;
- $results[] = array_map(function ($row): string {
- return $row['uri'];
- }, $filteredRows);
+ case IRoomMetadata::CAPACITY:
+ case IResourceMetadata::VEHICLE_SEATING_CAPACITY:
+ $results[] = $this->searchPrincipalsByCapacity($prop, $value);
+ break;
+ default:
+ $results[] = $this->searchPrincipalsByMetadataKey($prop, $value, $usersGroups);
break;
}
}
@@ -334,28 +291,83 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
}
/**
+ * @param string $key
+ * @return IQueryBuilder
+ */
+ private function getMetadataQuery(string $key): IQueryBuilder {
+ $query = $this->db->getQueryBuilder();
+ $query->select([$this->dbForeignKeyName])
+ ->from($this->dbMetaDataTableName)
+ ->where($query->expr()->eq('key', $query->createNamedParameter($key)));
+ return $query;
+ }
+
+ /**
* 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
+ * @param string $key
+ * @param string $value
+ * @param string[] $usersGroups
+ * @return string[]
*/
- 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();
+ private function searchPrincipalsByMetadataKey(string $key, string $value, array $usersGroups = []): array {
+ $query = $this->getMetadataQuery($key);
+ $query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
+ return $this->getRows($query, $usersGroups);
+ }
+
+ /**
+ * Searches principals based on room features
+ * e.g.:
+ * '{http://nextcloud.com/ns}room-features' => 'TV,PROJECTOR'
+ *
+ * @param string $key
+ * @param string $value
+ * @param string[] $usersGroups
+ * @return string[]
+ */
+ private function searchPrincipalsByRoomFeature(string $key, string $value, array $usersGroups = []): array {
+ $query = $this->getMetadataQuery($key);
+ foreach (explode(',', $value) as $v) {
+ $query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($v) . '%')));
+ }
+ return $this->getRows($query, $usersGroups);
+ }
+
+ /**
+ * Searches principals based on room seating capacity or vehicle capacity
+ * e.g.:
+ * '{http://nextcloud.com/ns}room-seating-capacity' => '100'
+ *
+ * @param string $key
+ * @param string $value
+ * @param string[] $usersGroups
+ * @return string[]
+ */
+ private function searchPrincipalsByCapacity(string $key, string $value, array $usersGroups = []): array {
+ $query = $this->getMetadataQuery($key);
+ $query->andWhere($query->expr()->gte('value', $query->createNamedParameter($value)));
+ return $this->getRows($query, $usersGroups);
+ }
+
+ /**
+ * @param IQueryBuilder $query
+ * @param string[] $usersGroups
+ * @return string[]
+ */
+ private function getRows(IQueryBuilder $query, array $usersGroups): array {
+ try {
+ $stmt = $query->executeQuery();
+ } catch (Exception $e) {
+ $this->logger->error('Could not search resources: ' . $e->getMessage(), ['exception' => $e]);
+ }
$rows = [];
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
- $id = $row[$this->dbForeignKeyName];
-
- $principalRow = $this->getPrincipalById($id);
+ $principalRow = $this->getPrincipalById($row[$this->dbForeignKeyName]);
if (!$principalRow) {
continue;
}
@@ -363,22 +375,31 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
$rows[] = $principalRow;
}
- return $rows;
+ $stmt->closeCursor();
+
+ $filteredRows = array_filter($rows, function ($row) use ($usersGroups) {
+ return $this->isAllowedToAccessResource($row, $usersGroups);
+ });
+
+ return array_map(static function ($row): string {
+ return $row['uri'];
+ }, $filteredRows);
}
/**
* @param string $uri
* @param string $principalPrefix
* @return null|string
+ * @throws Exception
*/
- public function findByUri($uri, $principalPrefix) {
+ public function findByUri($uri, $principalPrefix): ?string {
$user = $this->userSession->getUser();
if (!$user) {
return null;
}
$usersGroups = $this->groupManager->getUserGroupIds($user);
- if (strpos($uri, 'mailto:') === 0) {
+ if (str_starts_with($uri, 'mailto:')) {
$email = substr($uri, 7);
$query = $this->db->getQueryBuilder();
$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
@@ -398,14 +419,14 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
return $this->rowToPrincipal($row)['uri'];
}
- if (strpos($uri, 'principal:') === 0) {
+ if (str_starts_with($uri, 'principal:')) {
$path = substr($uri, 10);
- if (strpos($path, $this->principalPrefix) !== 0) {
+ if (!str_starts_with($path, $this->principalPrefix)) {
return null;
}
- list(, $name) = \Sabre\Uri\split($path);
- list($backendId, $resourceId) = explode('-', $name, 2);
+ [, $name] = \Sabre\Uri\split($path);
+ [$backendId, $resourceId] = explode('-', $name, 2);
$query = $this->db->getQueryBuilder();
$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
@@ -431,11 +452,11 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
/**
* convert database row to principal
*
- * @param String[] $row
- * @param String[] $metadata
- * @return Array
+ * @param string[] $row
+ * @param string[] $metadata
+ * @return string[]
*/
- private function rowToPrincipal(array $row, array $metadata = []):array {
+ private function rowToPrincipal(array $row, array $metadata = []): array {
return array_merge([
'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
'{DAV:}displayname' => $row['displayname'],
@@ -445,19 +466,19 @@ abstract class AbstractPrincipalBackend implements BackendInterface {
}
/**
- * @param $row
- * @param $userGroups
+ * @param array $row
+ * @param array $userGroups
* @return bool
*/
- private function isAllowedToAccessResource(array $row, array $userGroups):bool {
- if (!isset($row['group_restrictions']) ||
- $row['group_restrictions'] === null ||
- $row['group_restrictions'] === '') {
+ private function isAllowedToAccessResource(array $row, array $userGroups): bool {
+ if (!isset($row['group_restrictions'])
+ || $row['group_restrictions'] === null
+ || $row['group_restrictions'] === '') {
return true;
}
// group restrictions contains something, but not parsable, deny access and log warning
- $json = json_decode($row['group_restrictions']);
+ $json = json_decode($row['group_restrictions'], null, 512, JSON_THROW_ON_ERROR);
if (!\is_array($json)) {
$this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
return false;