migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
@@ -0,0 +1,502 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
* @copyright Copyright (c) 2017, Georg Ehrke <oc.list@georgehrke.com>
*
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Robin Appelman <robin@icewind.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV;
use Exception;
use OCA\DAV\Connector\Sabre\Directory;
use OCA\DAV\Connector\Sabre\FilesPlugin;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\IUser;
use Sabre\DAV\PropertyStorage\Backend\BackendInterface;
use Sabre\DAV\PropFind;
use Sabre\DAV\PropPatch;
use Sabre\DAV\Tree;
use Sabre\DAV\Xml\Property\Complex;
use function array_intersect;
class CustomPropertiesBackend implements BackendInterface {
/** @var string */
private const TABLE_NAME = 'properties';
/**
* Value is stored as string.
*/
public const PROPERTY_TYPE_STRING = 1;
/**
* Value is stored as XML fragment.
*/
public const PROPERTY_TYPE_XML = 2;
/**
* Value is stored as a property object.
*/
public const PROPERTY_TYPE_OBJECT = 3;
/**
* Ignored properties
*
* @var string[]
*/
private const IGNORED_PROPERTIES = [
'{DAV:}getcontentlength',
'{DAV:}getcontenttype',
'{DAV:}getetag',
'{DAV:}quota-used-bytes',
'{DAV:}quota-available-bytes',
'{http://owncloud.org/ns}permissions',
'{http://owncloud.org/ns}downloadURL',
'{http://owncloud.org/ns}dDC',
'{http://owncloud.org/ns}size',
'{http://nextcloud.org/ns}is-encrypted',
// Currently, returning null from any propfind handler would still trigger the backend,
// so we add all known Nextcloud custom properties in here to avoid that
// text app
'{http://nextcloud.org/ns}rich-workspace',
'{http://nextcloud.org/ns}rich-workspace-file',
// groupfolders
'{http://nextcloud.org/ns}acl-enabled',
'{http://nextcloud.org/ns}acl-can-manage',
'{http://nextcloud.org/ns}acl-list',
'{http://nextcloud.org/ns}inherited-acl-list',
'{http://nextcloud.org/ns}group-folder-id',
// files_lock
'{http://nextcloud.org/ns}lock',
'{http://nextcloud.org/ns}lock-owner-type',
'{http://nextcloud.org/ns}lock-owner',
'{http://nextcloud.org/ns}lock-owner-displayname',
'{http://nextcloud.org/ns}lock-owner-editor',
'{http://nextcloud.org/ns}lock-time',
'{http://nextcloud.org/ns}lock-timeout',
'{http://nextcloud.org/ns}lock-token',
];
/**
* Properties set by one user, readable by all others
*
* @var string[]
*/
private const PUBLISHED_READ_ONLY_PROPERTIES = [
'{urn:ietf:params:xml:ns:caldav}calendar-availability',
];
/**
* @var Tree
*/
private $tree;
/**
* @var IDBConnection
*/
private $connection;
/**
* @var IUser
*/
private $user;
/**
* Properties cache
*
* @var array
*/
private $userCache = [];
/**
* @param Tree $tree node tree
* @param IDBConnection $connection database connection
* @param IUser $user owner of the tree and properties
*/
public function __construct(
Tree $tree,
IDBConnection $connection,
IUser $user,
) {
$this->tree = $tree;
$this->connection = $connection;
$this->user = $user;
}
/**
* Fetches properties for a path.
*
* @param string $path
* @param PropFind $propFind
* @return void
*/
public function propFind($path, PropFind $propFind) {
$requestedProps = $propFind->get404Properties();
// these might appear
$requestedProps = array_diff(
$requestedProps,
self::IGNORED_PROPERTIES,
);
$requestedProps = array_filter(
$requestedProps,
fn ($prop) => !str_starts_with($prop, FilesPlugin::FILE_METADATA_PREFIX),
);
// substr of calendars/ => path is inside the CalDAV component
// two '/' => this a calendar (no calendar-home nor calendar object)
if (substr($path, 0, 10) === 'calendars/' && substr_count($path, '/') === 2) {
$allRequestedProps = $propFind->getRequestedProperties();
$customPropertiesForShares = [
'{DAV:}displayname',
'{urn:ietf:params:xml:ns:caldav}calendar-description',
'{urn:ietf:params:xml:ns:caldav}calendar-timezone',
'{http://apple.com/ns/ical/}calendar-order',
'{http://apple.com/ns/ical/}calendar-color',
'{urn:ietf:params:xml:ns:caldav}schedule-calendar-transp',
];
foreach ($customPropertiesForShares as $customPropertyForShares) {
if (in_array($customPropertyForShares, $allRequestedProps)) {
$requestedProps[] = $customPropertyForShares;
}
}
}
// substr of addressbooks/ => path is inside the CardDAV component
// three '/' => this a addressbook (no addressbook-home nor contact object)
if (str_starts_with($path, 'addressbooks/') && substr_count($path, '/') === 3) {
$allRequestedProps = $propFind->getRequestedProperties();
$customPropertiesForShares = [
'{DAV:}displayname',
];
foreach ($customPropertiesForShares as $customPropertyForShares) {
if (in_array($customPropertyForShares, $allRequestedProps, true)) {
$requestedProps[] = $customPropertyForShares;
}
}
}
if (empty($requestedProps)) {
return;
}
$node = $this->tree->getNodeForPath($path);
if ($node instanceof Directory && $propFind->getDepth() !== 0) {
$this->cacheDirectory($path, $node);
}
// First fetch the published properties (set by another user), then get the ones set by
// the current user. If both are set then the latter as priority.
foreach ($this->getPublishedProperties($path, $requestedProps) as $propName => $propValue) {
$propFind->set($propName, $propValue);
}
foreach ($this->getUserProperties($path, $requestedProps) as $propName => $propValue) {
$propFind->set($propName, $propValue);
}
}
/**
* Updates properties for a path
*
* @param string $path
* @param PropPatch $propPatch
*
* @return void
*/
public function propPatch($path, PropPatch $propPatch) {
$propPatch->handleRemaining(function ($changedProps) use ($path) {
return $this->updateProperties($path, $changedProps);
});
}
/**
* This method is called after a node is deleted.
*
* @param string $path path of node for which to delete properties
*/
public function delete($path) {
$statement = $this->connection->prepare(
'DELETE FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?'
);
$statement->execute([$this->user->getUID(), $this->formatPath($path)]);
$statement->closeCursor();
unset($this->userCache[$path]);
}
/**
* This method is called after a successful MOVE
*
* @param string $source
* @param string $destination
*
* @return void
*/
public function move($source, $destination) {
$statement = $this->connection->prepare(
'UPDATE `*PREFIX*properties` SET `propertypath` = ?' .
' WHERE `userid` = ? AND `propertypath` = ?'
);
$statement->execute([$this->formatPath($destination), $this->user->getUID(), $this->formatPath($source)]);
$statement->closeCursor();
}
/**
* @param string $path
* @param string[] $requestedProperties
*
* @return array
*/
private function getPublishedProperties(string $path, array $requestedProperties): array {
$allowedProps = array_intersect(self::PUBLISHED_READ_ONLY_PROPERTIES, $requestedProperties);
if (empty($allowedProps)) {
return [];
}
$qb = $this->connection->getQueryBuilder();
$qb->select('*')
->from(self::TABLE_NAME)
->where($qb->expr()->eq('propertypath', $qb->createNamedParameter($path)));
$result = $qb->executeQuery();
$props = [];
while ($row = $result->fetch()) {
$props[$row['propertyname']] = $this->decodeValueFromDatabase($row['propertyvalue'], $row['valuetype']);
}
$result->closeCursor();
return $props;
}
/**
* prefetch all user properties in a directory
*/
private function cacheDirectory(string $path, Directory $node): void {
$prefix = ltrim($path . '/', '/');
$query = $this->connection->getQueryBuilder();
$query->select('name', 'propertypath', 'propertyname', 'propertyvalue', 'valuetype')
->from('filecache', 'f')
->leftJoin('f', 'properties', 'p', $query->expr()->andX(
$query->expr()->eq('propertypath', $query->func()->concat(
$query->createNamedParameter($prefix),
'name'
)),
$query->expr()->eq('userid', $query->createNamedParameter($this->user->getUID()))
))
->where($query->expr()->eq('parent', $query->createNamedParameter($node->getInternalFileId(), IQueryBuilder::PARAM_INT)));
$result = $query->executeQuery();
$propsByPath = [];
while ($row = $result->fetch()) {
$childPath = $prefix . $row['name'];
if (!isset($propsByPath[$childPath])) {
$propsByPath[$childPath] = [];
}
if (isset($row['propertyname'])) {
$propsByPath[$childPath][$row['propertyname']] = $this->decodeValueFromDatabase($row['propertyvalue'], $row['valuetype']);
}
}
$this->userCache = array_merge($this->userCache, $propsByPath);
}
/**
* Returns a list of properties for the given path and current user
*
* @param string $path
* @param array $requestedProperties requested properties or empty array for "all"
* @return array
* @note The properties list is a list of propertynames the client
* requested, encoded as xmlnamespace#tagName, for example:
* http://www.example.org/namespace#author If the array is empty, all
* properties should be returned
*/
private function getUserProperties(string $path, array $requestedProperties) {
if (isset($this->userCache[$path])) {
return $this->userCache[$path];
}
// TODO: chunking if more than 1000 properties
$sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?';
$whereValues = [$this->user->getUID(), $this->formatPath($path)];
$whereTypes = [null, null];
if (!empty($requestedProperties)) {
// request only a subset
$sql .= ' AND `propertyname` in (?)';
$whereValues[] = $requestedProperties;
$whereTypes[] = \Doctrine\DBAL\Connection::PARAM_STR_ARRAY;
}
$result = $this->connection->executeQuery(
$sql,
$whereValues,
$whereTypes
);
$props = [];
while ($row = $result->fetch()) {
$props[$row['propertyname']] = $this->decodeValueFromDatabase($row['propertyvalue'], $row['valuetype']);
}
$result->closeCursor();
$this->userCache[$path] = $props;
return $props;
}
/**
* @throws Exception
*/
private function updateProperties(string $path, array $properties): bool {
// TODO: use "insert or update" strategy ?
$existing = $this->getUserProperties($path, []);
try {
$this->connection->beginTransaction();
foreach ($properties as $propertyName => $propertyValue) {
// common parameters for all queries
$dbParameters = [
'userid' => $this->user->getUID(),
'propertyPath' => $this->formatPath($path),
'propertyName' => $propertyName,
];
// If it was null, we need to delete the property
if (is_null($propertyValue)) {
if (array_key_exists($propertyName, $existing)) {
$deleteQuery = $deleteQuery ?? $this->createDeleteQuery();
$deleteQuery
->setParameters($dbParameters)
->executeStatement();
}
} else {
[$value, $valueType] = $this->encodeValueForDatabase($propertyValue);
$dbParameters['propertyValue'] = $value;
$dbParameters['valueType'] = $valueType;
if (!array_key_exists($propertyName, $existing)) {
$insertQuery = $insertQuery ?? $this->createInsertQuery();
$insertQuery
->setParameters($dbParameters)
->executeStatement();
} else {
$updateQuery = $updateQuery ?? $this->createUpdateQuery();
$updateQuery
->setParameters($dbParameters)
->executeStatement();
}
}
}
$this->connection->commit();
unset($this->userCache[$path]);
} catch (Exception $e) {
$this->connection->rollBack();
throw $e;
}
return true;
}
/**
* long paths are hashed to ensure they fit in the database
*
* @param string $path
* @return string
*/
private function formatPath(string $path): string {
if (strlen($path) > 250) {
return sha1($path);
}
return $path;
}
/**
* @param mixed $value
* @return array
*/
private function encodeValueForDatabase($value): array {
if (is_scalar($value)) {
$valueType = self::PROPERTY_TYPE_STRING;
} elseif ($value instanceof Complex) {
$valueType = self::PROPERTY_TYPE_XML;
$value = $value->getXml();
} else {
$valueType = self::PROPERTY_TYPE_OBJECT;
$value = serialize($value);
}
return [$value, $valueType];
}
/**
* @return mixed|Complex|string
*/
private function decodeValueFromDatabase(string $value, int $valueType) {
switch ($valueType) {
case self::PROPERTY_TYPE_XML:
return new Complex($value);
case self::PROPERTY_TYPE_OBJECT:
return unserialize($value);
case self::PROPERTY_TYPE_STRING:
default:
return $value;
}
}
private function createDeleteQuery(): IQueryBuilder {
$deleteQuery = $this->connection->getQueryBuilder();
$deleteQuery->delete('properties')
->where($deleteQuery->expr()->eq('userid', $deleteQuery->createParameter('userid')))
->andWhere($deleteQuery->expr()->eq('propertypath', $deleteQuery->createParameter('propertyPath')))
->andWhere($deleteQuery->expr()->eq('propertyname', $deleteQuery->createParameter('propertyName')));
return $deleteQuery;
}
private function createInsertQuery(): IQueryBuilder {
$insertQuery = $this->connection->getQueryBuilder();
$insertQuery->insert('properties')
->values([
'userid' => $insertQuery->createParameter('userid'),
'propertypath' => $insertQuery->createParameter('propertyPath'),
'propertyname' => $insertQuery->createParameter('propertyName'),
'propertyvalue' => $insertQuery->createParameter('propertyValue'),
'valuetype' => $insertQuery->createParameter('valueType'),
]);
return $insertQuery;
}
private function createUpdateQuery(): IQueryBuilder {
$updateQuery = $this->connection->getQueryBuilder();
$updateQuery->update('properties')
->set('propertyvalue', $updateQuery->createParameter('propertyValue'))
->set('valuetype', $updateQuery->createParameter('valueType'))
->where($updateQuery->expr()->eq('userid', $updateQuery->createParameter('userid')))
->andWhere($updateQuery->expr()->eq('propertypath', $updateQuery->createParameter('propertyPath')))
->andWhere($updateQuery->expr()->eq('propertyname', $updateQuery->createParameter('propertyName')));
return $updateQuery;
}
}
@@ -0,0 +1,348 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
* @copyright Copyright (c) 2018, Georg Ehrke
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Citharel <nextcloud@tcit.fr>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV;
use OCP\Constants;
use OCP\IConfig;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Share\IManager as IShareManager;
use Sabre\DAV\Exception;
use Sabre\DAV\PropPatch;
use Sabre\DAVACL\PrincipalBackend\BackendInterface;
class GroupPrincipalBackend implements BackendInterface {
public const PRINCIPAL_PREFIX = 'principals/groups';
/** @var IGroupManager */
private $groupManager;
/** @var IUserSession */
private $userSession;
/** @var IShareManager */
private $shareManager;
/** @var IConfig */
private $config;
/**
* @param IGroupManager $IGroupManager
* @param IUserSession $userSession
* @param IShareManager $shareManager
*/
public function __construct(
IGroupManager $IGroupManager,
IUserSession $userSession,
IShareManager $shareManager,
IConfig $config
) {
$this->groupManager = $IGroupManager;
$this->userSession = $userSession;
$this->shareManager = $shareManager;
$this->config = $config;
}
/**
* Returns a list of principals based on a prefix.
*
* This prefix will often contain something like 'principals'. You are only
* expected to return principals that are in this base path.
*
* You are expected to return at least a 'uri' for every user, you can
* return any additional properties if you wish so. Common properties are:
* {DAV:}displayname
*
* @param string $prefixPath
* @return string[]
*/
public function getPrincipalsByPrefix($prefixPath) {
$principals = [];
if ($prefixPath === self::PRINCIPAL_PREFIX) {
foreach ($this->groupManager->search('') as $user) {
$principals[] = $this->groupToPrincipal($user);
}
}
return $principals;
}
/**
* Returns a specific principal, specified by it's path.
* The returned structure should be the exact same as from
* getPrincipalsByPrefix.
*
* @param string $path
* @return array
*/
public function getPrincipalByPath($path) {
$elements = explode('/', $path, 3);
if ($elements[0] !== 'principals') {
return null;
}
if ($elements[1] !== 'groups') {
return null;
}
$name = urldecode($elements[2]);
$group = $this->groupManager->get($name);
if (!is_null($group)) {
return $this->groupToPrincipal($group);
}
return null;
}
/**
* Returns the list of members for a group-principal
*
* @param string $principal
* @return array
* @throws Exception
*/
public function getGroupMemberSet($principal) {
$elements = explode('/', $principal);
if ($elements[0] !== 'principals') {
return [];
}
if ($elements[1] !== 'groups') {
return [];
}
$name = $elements[2];
$group = $this->groupManager->get($name);
if (is_null($group)) {
return [];
}
return array_map(function ($user) {
return $this->userToPrincipal($user);
}, $group->getUsers());
}
/**
* Returns the list of groups a principal is a member of
*
* @param string $principal
* @return array
* @throws Exception
*/
public function getGroupMembership($principal) {
return [];
}
/**
* Updates the list of group members for a group principal.
*
* The principals should be passed as a list of uri's.
*
* @param string $principal
* @param string[] $members
* @throws Exception
*/
public function setGroupMemberSet($principal, array $members) {
throw new Exception('Setting members of the group is not supported yet');
}
/**
* @param string $path
* @param PropPatch $propPatch
* @return int
*/
public function updatePrincipal($path, PropPatch $propPatch) {
return 0;
}
/**
* @param string $prefixPath
* @param array $searchProperties
* @param string $test
* @return array
*/
public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
$results = [];
if (\count($searchProperties) === 0) {
return [];
}
if ($prefixPath !== self::PRINCIPAL_PREFIX) {
return [];
}
// If sharing or group sharing is disabled, return the empty array
if (!$this->groupSharingEnabled()) {
return [];
}
// If sharing is restricted to group members only,
// return only members that have groups in common
$restrictGroups = false;
if ($this->shareManager->shareWithGroupMembersOnly()) {
$user = $this->userSession->getUser();
if (!$user) {
return [];
}
$restrictGroups = $this->groupManager->getUserGroupIds($user);
}
$searchLimit = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
if ($searchLimit <= 0) {
$searchLimit = null;
}
foreach ($searchProperties as $prop => $value) {
switch ($prop) {
case '{DAV:}displayname':
$groups = $this->groupManager->search($value, $searchLimit);
$results[] = array_reduce($groups, function (array $carry, IGroup $group) use ($restrictGroups) {
$gid = $group->getGID();
// is sharing restricted to groups only?
if ($restrictGroups !== false) {
if (!\in_array($gid, $restrictGroups, true)) {
return $carry;
}
}
$carry[] = self::PRINCIPAL_PREFIX . '/' . urlencode($gid);
return $carry;
}, []);
break;
case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
// If you add support for more search properties that qualify as a user-address,
// please also add them to the array below
$results[] = $this->searchPrincipals(self::PRINCIPAL_PREFIX, [
], 'anyof');
break;
default:
$results[] = [];
break;
}
}
// results is an array of arrays, so this is not the first search result
// but the results of the first searchProperty
if (count($results) === 1) {
return $results[0];
}
switch ($test) {
case 'anyof':
return array_values(array_unique(array_merge(...$results)));
case 'allof':
default:
return array_values(array_intersect(...$results));
}
}
/**
* @param string $uri
* @param string $principalPrefix
* @return string
*/
public function findByUri($uri, $principalPrefix) {
// If sharing is disabled, return the empty array
if (!$this->groupSharingEnabled()) {
return null;
}
// If sharing is restricted to group members only,
// return only members that have groups in common
$restrictGroups = false;
if ($this->shareManager->shareWithGroupMembersOnly()) {
$user = $this->userSession->getUser();
if (!$user) {
return null;
}
$restrictGroups = $this->groupManager->getUserGroupIds($user);
}
if (str_starts_with($uri, 'principal:principals/groups/')) {
$name = urlencode(substr($uri, 28));
if ($restrictGroups !== false && !\in_array($name, $restrictGroups, true)) {
return null;
}
return substr($uri, 10);
}
return null;
}
/**
* @param IGroup $group
* @return array
*/
protected function groupToPrincipal($group) {
$groupId = $group->getGID();
// getDisplayName returns UID if none
$displayName = $group->getDisplayName();
return [
'uri' => 'principals/groups/' . urlencode($groupId),
'{DAV:}displayname' => $displayName,
'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'GROUP',
];
}
/**
* @param IUser $user
* @return array
*/
protected function userToPrincipal($user) {
$userId = $user->getUID();
// getDisplayName returns UID if none
$displayName = $user->getDisplayName();
$principal = [
'uri' => 'principals/users/' . $userId,
'{DAV:}displayname' => $displayName,
'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
];
$email = $user->getSystemEMailAddress();
if (!empty($email)) {
$principal['{http://sabredav.org/ns}email-address'] = $email;
}
return $principal;
}
/**
* @return bool
*/
private function groupSharingEnabled(): bool {
return $this->shareManager->shareApiEnabled() && $this->shareManager->allowGroupSharing();
}
}
@@ -0,0 +1,93 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV;
use Sabre\DAV\Auth\Backend\BackendInterface;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
class PublicAuth implements BackendInterface {
/** @var string[] */
private $publicURLs;
public function __construct() {
$this->publicURLs = [
'public-calendars',
'principals/system/public'
];
}
/**
* When this method is called, the backend must check if authentication was
* successful.
*
* The returned value must be one of the following
*
* [true, "principals/username"]
* [false, "reason for failure"]
*
* If authentication was successful, it's expected that the authentication
* backend returns a so-called principal url.
*
* Examples of a principal url:
*
* principals/admin
* principals/user1
* principals/users/joe
* principals/uid/123457
*
* If you don't use WebDAV ACL (RFC3744) we recommend that you simply
* return a string such as:
*
* principals/users/[username]
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @return array
*/
public function check(RequestInterface $request, ResponseInterface $response) {
if ($this->isRequestPublic($request)) {
return [true, "principals/system/public"];
}
return [false, "No public access to this resource."];
}
/**
* @inheritdoc
*/
public function challenge(RequestInterface $request, ResponseInterface $response) {
}
/**
* @param RequestInterface $request
* @return bool
*/
private function isRequestPublic(RequestInterface $request) {
$url = $request->getPath();
$matchingUrls = array_filter($this->publicURLs, function ($publicUrl) use ($url) {
return str_starts_with($url, $publicUrl);
});
return !empty($matchingUrls);
}
}
@@ -0,0 +1,280 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Citharel <nextcloud@tcit.fr>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV\Sharing;
use OCA\DAV\Connector\Sabre\Principal;
use OCP\AppFramework\Db\TTransactional;
use OCP\Cache\CappedMemoryCache;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\IGroupManager;
use OCP\IUserManager;
class Backend {
use TTransactional;
private IDBConnection $db;
private IUserManager $userManager;
private IGroupManager $groupManager;
private Principal $principalBackend;
private string $resourceType;
public const ACCESS_OWNER = 1;
public const ACCESS_READ_WRITE = 2;
public const ACCESS_READ = 3;
private CappedMemoryCache $shareCache;
public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, string $resourceType) {
$this->db = $db;
$this->userManager = $userManager;
$this->groupManager = $groupManager;
$this->principalBackend = $principalBackend;
$this->resourceType = $resourceType;
$this->shareCache = new CappedMemoryCache();
}
/**
* @param list<array{href: string, commonName: string, readOnly: bool}> $add
* @param list<string> $remove
*/
public function updateShares(IShareable $shareable, array $add, array $remove): void {
$this->shareCache->clear();
$this->atomic(function () use ($shareable, $add, $remove) {
foreach ($add as $element) {
$principal = $this->principalBackend->findByUri($element['href'], '');
if ($principal !== '') {
$this->shareWith($shareable, $element);
}
}
foreach ($remove as $element) {
$principal = $this->principalBackend->findByUri($element, '');
if ($principal !== '') {
$this->unshare($shareable, $element);
}
}
}, $this->db);
}
/**
* @param array{href: string, commonName: string, readOnly: bool} $element
*/
private function shareWith(IShareable $shareable, array $element): void {
$this->shareCache->clear();
$user = $element['href'];
$parts = explode(':', $user, 2);
if ($parts[0] !== 'principal') {
return;
}
// don't share with owner
if ($shareable->getOwner() === $parts[1]) {
return;
}
$principal = explode('/', $parts[1], 3);
if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
// Invalid principal
return;
}
$principal[2] = urldecode($principal[2]);
if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
// User or group does not exist
return;
}
// remove the share if it already exists
$this->unshare($shareable, $element['href']);
$access = self::ACCESS_READ;
if (isset($element['readOnly'])) {
$access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
}
$query = $this->db->getQueryBuilder();
$query->insert('dav_shares')
->values([
'principaluri' => $query->createNamedParameter($parts[1]),
'type' => $query->createNamedParameter($this->resourceType),
'access' => $query->createNamedParameter($access),
'resourceid' => $query->createNamedParameter($shareable->getResourceId())
]);
$query->executeStatement();
}
public function deleteAllShares(int $resourceId): void {
$this->shareCache->clear();
$query = $this->db->getQueryBuilder();
$query->delete('dav_shares')
->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
->executeStatement();
}
public function deleteAllSharesByUser(string $principaluri): void {
$this->shareCache->clear();
$query = $this->db->getQueryBuilder();
$query->delete('dav_shares')
->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
->executeStatement();
}
private function unshare(IShareable $shareable, string $element): void {
$this->shareCache->clear();
$parts = explode(':', $element, 2);
if ($parts[0] !== 'principal') {
return;
}
// don't share with owner
if ($shareable->getOwner() === $parts[1]) {
return;
}
$query = $this->db->getQueryBuilder();
$query->delete('dav_shares')
->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
;
$query->executeStatement();
}
/**
* Returns the list of people whom this resource is shared with.
*
* Every element in this array should have the following properties:
* * href - Often a mailto: address
* * commonName - Optional, for example a first + last name
* * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
* * readOnly - boolean
*
* @param int $resourceId
* @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
*/
public function getShares(int $resourceId): array {
$cached = $this->shareCache->get($resourceId);
if ($cached) {
return $cached;
}
$query = $this->db->getQueryBuilder();
$result = $query->select(['principaluri', 'access'])
->from('dav_shares')
->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId, IQueryBuilder::PARAM_INT)))
->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
->groupBy(['principaluri', 'access'])
->executeQuery();
$shares = [];
while ($row = $result->fetch()) {
$p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
$shares[] = [
'href' => "principal:{$row['principaluri']}",
'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
'status' => 1,
'readOnly' => (int) $row['access'] === self::ACCESS_READ,
'{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
'{http://owncloud.org/ns}group-share' => isset($p['uri']) ? str_starts_with($p['uri'], 'principals/groups') : false
];
}
$this->shareCache->set((string)$resourceId, $shares);
return $shares;
}
public function preloadShares(array $resourceIds): void {
$resourceIds = array_filter($resourceIds, function (int $resourceId) {
return !isset($this->shareCache[$resourceId]);
});
if (count($resourceIds) === 0) {
return;
}
$query = $this->db->getQueryBuilder();
$result = $query->select(['resourceid', 'principaluri', 'access'])
->from('dav_shares')
->where($query->expr()->in('resourceid', $query->createNamedParameter($resourceIds, IQueryBuilder::PARAM_INT_ARRAY)))
->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
->groupBy(['principaluri', 'access', 'resourceid'])
->executeQuery();
$sharesByResource = array_fill_keys($resourceIds, []);
while ($row = $result->fetch()) {
$resourceId = (int)$row['resourceid'];
$p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
$sharesByResource[$resourceId][] = [
'href' => "principal:{$row['principaluri']}",
'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
'status' => 1,
'readOnly' => (int) $row['access'] === self::ACCESS_READ,
'{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
'{http://owncloud.org/ns}group-share' => isset($p['uri']) ? str_starts_with($p['uri'], 'principals/groups') : false
];
}
foreach ($resourceIds as $resourceId) {
$this->shareCache->set($resourceId, $sharesByResource[$resourceId]);
}
}
/**
* For shared resources the sharee is set in the ACL of the resource
*
* @param int $resourceId
* @param list<array{privilege: string, principal: string, protected: bool}> $acl
* @return list<array{privilege: string, principal: string, protected: bool}>
*/
public function applyShareAcl(int $resourceId, array $acl): array {
$shares = $this->getShares($resourceId);
foreach ($shares as $share) {
$acl[] = [
'privilege' => '{DAV:}read',
'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
'protected' => true,
];
if (!$share['readOnly']) {
$acl[] = [
'privilege' => '{DAV:}write',
'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
'protected' => true,
];
} elseif ($this->resourceType === 'calendar') {
// Allow changing the properties of read only calendars,
// so users can change the visibility.
$acl[] = [
'privilege' => '{DAV:}write-properties',
'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
'protected' => true,
];
}
}
return $acl;
}
}
@@ -0,0 +1,71 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV\Sharing;
use Sabre\DAV\INode;
/**
* This interface represents a dav resource that can be shared with other users.
*
*/
interface IShareable extends INode {
/**
* Updates the list of shares.
*
* The first array is a list of people that are to be added to the
* resource.
*
* Every element in the add array has the following properties:
* * href - A url. Usually a mailto: address
* * commonName - Usually a first and last name, or false
* * readOnly - A boolean value
*
* Every element in the remove array is just the address string.
*
* @param list<array{href: string, commonName: string, readOnly: bool}> $add
* @param list<string> $remove
*/
public function updateShares(array $add, array $remove): void;
/**
* Returns the list of people whom this resource is shared with.
*
* Every element in this array should have the following properties:
* * href - Often a mailto: address
* * commonName - Optional, for example a first + last name
* * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
* * readOnly - boolean
*
* @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
*/
public function getShares(): array;
public function getResourceId(): int;
/**
* @return ?string
*/
public function getOwner();
}
@@ -0,0 +1,228 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV\Sharing;
use OCA\DAV\CalDAV\CalDavBackend;
use OCA\DAV\CalDAV\CalendarHome;
use OCA\DAV\Connector\Sabre\Auth;
use OCA\DAV\DAV\Sharing\Xml\Invite;
use OCA\DAV\DAV\Sharing\Xml\ShareRequest;
use OCP\IConfig;
use OCP\IRequest;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\INode;
use Sabre\DAV\PropFind;
use Sabre\DAV\Server;
use Sabre\DAV\ServerPlugin;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
class Plugin extends ServerPlugin {
public const NS_OWNCLOUD = 'http://owncloud.org/ns';
public const NS_NEXTCLOUD = 'http://nextcloud.com/ns';
/** @var Auth */
private $auth;
/** @var IRequest */
private $request;
/** @var IConfig */
private $config;
/**
* Plugin constructor.
*
* @param Auth $authBackEnd
* @param IRequest $request
* @param IConfig $config
*/
public function __construct(Auth $authBackEnd, IRequest $request, IConfig $config) {
$this->auth = $authBackEnd;
$this->request = $request;
$this->config = $config;
}
/**
* Reference to SabreDAV server object.
*
* @var \Sabre\DAV\Server
*/
protected $server;
/**
* This method should return a list of server-features.
*
* This is for example 'versioning' and is added to the DAV: header
* in an OPTIONS response.
*
* @return string[]
*/
public function getFeatures() {
return ['oc-resource-sharing'];
}
/**
* Returns a plugin name.
*
* Using this name other plugins will be able to access other plugins
* using Sabre\DAV\Server::getPlugin
*
* @return string
*/
public function getPluginName() {
return 'oc-resource-sharing';
}
/**
* This initializes the plugin.
*
* This function is called by Sabre\DAV\Server, after
* addPlugin is called.
*
* This method should set up the required event subscriptions.
*
* @param Server $server
* @return void
*/
public function initialize(Server $server) {
$this->server = $server;
$this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}share'] = ShareRequest::class;
$this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = Invite::class;
$this->server->on('method:POST', [$this, 'httpPost']);
$this->server->on('propFind', [$this, 'propFind']);
}
/**
* We intercept this to handle POST requests on a dav resource.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @return null|false
*/
public function httpPost(RequestInterface $request, ResponseInterface $response) {
$path = $request->getPath();
// Only handling xml
$contentType = (string) $request->getHeader('Content-Type');
if (!str_contains($contentType, 'application/xml') && !str_contains($contentType, 'text/xml')) {
return;
}
// Making sure the node exists
try {
$node = $this->server->tree->getNodeForPath($path);
} catch (NotFound $e) {
return;
}
$requestBody = $request->getBodyAsString();
// If this request handler could not deal with this POST request, it
// will return 'null' and other plugins get a chance to handle the
// request.
//
// However, we already requested the full body. This is a problem,
// because a body can only be read once. This is why we preemptively
// re-populated the request body with the existing data.
$request->setBody($requestBody);
$message = $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
switch ($documentType) {
// Dealing with the 'share' document, which modified invitees on a
// calendar.
case '{' . self::NS_OWNCLOUD . '}share':
// We can only deal with IShareableCalendar objects
if (!$node instanceof IShareable) {
return;
}
$this->server->transactionType = 'post-oc-resource-share';
// Getting ACL info
$acl = $this->server->getPlugin('acl');
// If there's no ACL support, we allow everything
if ($acl) {
/** @var \Sabre\DAVACL\Plugin $acl */
$acl->checkPrivileges($path, '{DAV:}write');
$limitSharingToOwner = $this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes';
$isOwner = $acl->getCurrentUserPrincipal() === $node->getOwner();
if ($limitSharingToOwner && !$isOwner) {
return;
}
}
$node->updateShares($message->set, $message->remove);
$response->setStatus(200);
// Adding this because sending a response body may cause issues,
// and I wanted some type of indicator the response was handled.
$response->setHeader('X-Sabre-Status', 'everything-went-well');
// Breaking the event chain
return false;
}
}
/**
* This event is triggered when properties are requested for a certain
* node.
*
* This allows us to inject any properties early.
*
* @param PropFind $propFind
* @param INode $node
* @return void
*/
public function propFind(PropFind $propFind, INode $node) {
if ($node instanceof CalendarHome && $propFind->getDepth() === 1) {
$backend = $node->getCalDAVBackend();
if ($backend instanceof CalDavBackend) {
$calendars = $node->getChildren();
$calendars = array_filter($calendars, function (INode $node) {
return $node instanceof IShareable;
});
/** @var int[] $resourceIds */
$resourceIds = array_map(function (IShareable $node) {
return $node->getResourceId();
}, $calendars);
$backend->preloadShares($resourceIds);
}
}
if ($node instanceof IShareable) {
$propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', function () use ($node) {
return new Invite(
$node->getShares()
);
});
}
}
}
@@ -0,0 +1,163 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
* @copyright Copyright (C) fruux GmbH (https://fruux.com/)
* @copyright Copyright (C) fruux GmbH (https://fruux.com/)
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Robin Appelman <robin@icewind.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV\Sharing\Xml;
use OCA\DAV\DAV\Sharing\Plugin;
use Sabre\Xml\Writer;
use Sabre\Xml\XmlSerializable;
/**
* Invite property
*
* This property encodes the 'invite' property, as defined by
* the 'caldav-sharing-02' spec, in the http://calendarserver.org/ns/
* namespace.
*
* @see https://trac.calendarserver.org/browser/CalendarServer/trunk/doc/Extensions/caldav-sharing-02.txt
* @copyright Copyright (C) fruux GmbH (https://fruux.com/)
* @author Evert Pot (http://evertpot.com/)
* @license http://sabre.io/license/ Modified BSD License
*/
class Invite implements XmlSerializable {
/**
* The list of users a calendar has been shared to.
*
* @var array
*/
protected $users;
/**
* The organizer contains information about the person who shared the
* object.
*
* @var array|null
*/
protected $organizer;
/**
* Creates the property.
*
* Users is an array. Each element of the array has the following
* properties:
*
* * href - Often a mailto: address
* * commonName - Optional, for example a first and lastname for a user.
* * status - One of the SharingPlugin::STATUS_* constants.
* * readOnly - true or false
* * summary - Optional, description of the share
*
* The organizer key is optional to specify. It's only useful when a
* 'sharee' requests the sharing information.
*
* The organizer may have the following properties:
* * href - Often a mailto: address.
* * commonName - Optional human-readable name.
* * firstName - Optional first name.
* * lastName - Optional last name.
*
* If you wonder why these two structures are so different, I guess a
* valid answer is that the current spec is still a draft.
*
* @param array $users
*/
public function __construct(array $users, array $organizer = null) {
$this->users = $users;
$this->organizer = $organizer;
}
/**
* Returns the list of users, as it was passed to the constructor.
*
* @return array
*/
public function getValue() {
return $this->users;
}
/**
* The xmlSerialize method is called during xml writing.
*
* Use the $writer argument to write its own xml serialization.
*
* An important note: do _not_ create a parent element. Any element
* implementing XmlSerializble should only ever write what's considered
* its 'inner xml'.
*
* The parent of the current element is responsible for writing a
* containing element.
*
* This allows serializers to be re-used for different element names.
*
* If you are opening new elements, you must also close them again.
*
* @param Writer $writer
* @return void
*/
public function xmlSerialize(Writer $writer) {
$cs = '{' . Plugin::NS_OWNCLOUD . '}';
if (!is_null($this->organizer)) {
$writer->startElement($cs . 'organizer');
$writer->writeElement('{DAV:}href', $this->organizer['href']);
if (isset($this->organizer['commonName']) && $this->organizer['commonName']) {
$writer->writeElement($cs . 'common-name', $this->organizer['commonName']);
}
if (isset($this->organizer['firstName']) && $this->organizer['firstName']) {
$writer->writeElement($cs . 'first-name', $this->organizer['firstName']);
}
if (isset($this->organizer['lastName']) && $this->organizer['lastName']) {
$writer->writeElement($cs . 'last-name', $this->organizer['lastName']);
}
$writer->endElement(); // organizer
}
foreach ($this->users as $user) {
$writer->startElement($cs . 'user');
$writer->writeElement('{DAV:}href', $user['href']);
if (isset($user['commonName']) && $user['commonName']) {
$writer->writeElement($cs . 'common-name', $user['commonName']);
}
$writer->writeElement($cs . 'invite-accepted');
$writer->startElement($cs . 'access');
if ($user['readOnly']) {
$writer->writeElement($cs . 'read');
} else {
$writer->writeElement($cs . 'read-write');
}
$writer->endElement(); // access
if (isset($user['summary']) && $user['summary']) {
$writer->writeElement($cs . 'summary', $user['summary']);
}
$writer->endElement(); //user
}
}
}
@@ -0,0 +1,80 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV\Sharing\Xml;
use OCA\DAV\DAV\Sharing\Plugin;
use Sabre\Xml\Reader;
use Sabre\Xml\XmlDeserializable;
class ShareRequest implements XmlDeserializable {
public $set = [];
public $remove = [];
/**
* Constructor
*
* @param array $set
* @param array $remove
*/
public function __construct(array $set, array $remove) {
$this->set = $set;
$this->remove = $remove;
}
public static function xmlDeserialize(Reader $reader) {
$elements = $reader->parseInnerTree([
'{' . Plugin::NS_OWNCLOUD. '}set' => 'Sabre\\Xml\\Element\\KeyValue',
'{' . Plugin::NS_OWNCLOUD . '}remove' => 'Sabre\\Xml\\Element\\KeyValue',
]);
$set = [];
$remove = [];
foreach ($elements as $elem) {
switch ($elem['name']) {
case '{' . Plugin::NS_OWNCLOUD . '}set':
$sharee = $elem['value'];
$sumElem = '{' . Plugin::NS_OWNCLOUD . '}summary';
$commonName = '{' . Plugin::NS_OWNCLOUD . '}common-name';
$set[] = [
'href' => $sharee['{DAV:}href'],
'commonName' => $sharee[$commonName] ?? null,
'summary' => $sharee[$sumElem] ?? null,
'readOnly' => !array_key_exists('{' . Plugin::NS_OWNCLOUD . '}read-write', $sharee),
];
break;
case '{' . Plugin::NS_OWNCLOUD . '}remove':
$remove[] = $elem['value']['{DAV:}href'];
break;
}
}
return new self($set, $remove);
}
}
@@ -0,0 +1,189 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV;
use Sabre\DAVACL\PrincipalBackend\AbstractBackend;
class SystemPrincipalBackend extends AbstractBackend {
/**
* Returns a list of principals based on a prefix.
*
* This prefix will often contain something like 'principals'. You are only
* expected to return principals that are in this base path.
*
* You are expected to return at least a 'uri' for every user, you can
* return any additional properties if you wish so. Common properties are:
* {DAV:}displayname
* {http://sabredav.org/ns}email-address - This is a custom SabreDAV
* field that's actually injected in a number of other properties. If
* you have an email address, use this property.
*
* @param string $prefixPath
* @return array
*/
public function getPrincipalsByPrefix($prefixPath) {
$principals = [];
if ($prefixPath === 'principals/system') {
$principals[] = [
'uri' => 'principals/system/system',
'{DAV:}displayname' => 'system',
];
$principals[] = [
'uri' => 'principals/system/public',
'{DAV:}displayname' => 'public',
];
}
return $principals;
}
/**
* Returns a specific principal, specified by its path.
* The returned structure should be the exact same as from
* getPrincipalsByPrefix.
*
* @param string $path
* @return array
*/
public function getPrincipalByPath($path) {
if ($path === 'principals/system/system') {
$principal = [
'uri' => 'principals/system/system',
'{DAV:}displayname' => 'system',
];
return $principal;
}
if ($path === 'principals/system/public') {
$principal = [
'uri' => 'principals/system/public',
'{DAV:}displayname' => 'public',
];
return $principal;
}
return null;
}
/**
* Updates one or more webdav properties on a principal.
*
* The list of mutations is stored in a Sabre\DAV\PropPatch object.
* To do the actual updates, you must tell this object which properties
* you're going to process with the handle() method.
*
* Calling the handle method is like telling the PropPatch object "I
* promise I can handle updating this property".
*
* Read the PropPatch documentation for more info and examples.
*
* @param string $path
* @param \Sabre\DAV\PropPatch $propPatch
* @return void
*/
public function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) {
}
/**
* This method is used to search for principals matching a set of
* properties.
*
* This search is specifically used by RFC3744's principal-property-search
* REPORT.
*
* The actual search should be a unicode-non-case-sensitive search. The
* keys in searchProperties are the WebDAV property names, while the values
* are the property values to search on.
*
* By default, if multiple properties are submitted to this method, the
* various properties should be combined with 'AND'. If $test is set to
* 'anyof', it should be combined using 'OR'.
*
* This method should simply return an array with full principal uri's.
*
* If somebody attempted to search on a property the backend does not
* support, you should simply return 0 results.
*
* You can also just return 0 results if you choose to not support
* searching at all, but keep in mind that this may stop certain features
* from working.
*
* @param string $prefixPath
* @param array $searchProperties
* @param string $test
* @return array
*/
public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
return [];
}
/**
* Returns the list of members for a group-principal
*
* @param string $principal
* @return array
*/
public function getGroupMemberSet($principal) {
// TODO: for now the group principal has only one member, the user itself
$principal = $this->getPrincipalByPath($principal);
if (!$principal) {
throw new \Sabre\DAV\Exception('Principal not found');
}
return [$principal['uri']];
}
/**
* Returns the list of groups a principal is a member of
*
* @param string $principal
* @return array
*/
public function getGroupMembership($principal) {
[$prefix, ] = \Sabre\Uri\split($principal);
if ($prefix === 'principals/system') {
$principal = $this->getPrincipalByPath($principal);
if (!$principal) {
throw new \Sabre\DAV\Exception('Principal not found');
}
return [];
}
return [];
}
/**
* Updates the list of group members for a group principal.
*
* The principals should be passed as a list of uri's.
*
* @param string $principal
* @param array $members
* @return void
*/
public function setGroupMemberSet($principal, array $members) {
throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet');
}
}
@@ -0,0 +1,120 @@
<?php
/**
* @author Piotr Mrowczynski piotr@owncloud.com
*
* @copyright Copyright (c) 2019, ownCloud GmbH
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\DAV;
use OCA\DAV\Connector\Sabre\Exception\Forbidden;
use OCA\DAV\Connector\Sabre\File as DavFile;
use OCA\Files_Versions\Sabre\VersionFile;
use OCP\Files\Folder;
use OCP\Files\NotFoundException;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\Server;
use Sabre\DAV\ServerPlugin;
use Sabre\HTTP\RequestInterface;
/**
* Sabre plugin for restricting file share receiver download:
*/
class ViewOnlyPlugin extends ServerPlugin {
private ?Server $server = null;
private ?Folder $userFolder;
public function __construct(
?Folder $userFolder,
) {
$this->userFolder = $userFolder;
}
/**
* This initializes the plugin.
*
* This function is called by Sabre\DAV\Server, after
* addPlugin is called.
*
* This method should set up the required event subscriptions.
*/
public function initialize(Server $server): void {
$this->server = $server;
//priority 90 to make sure the plugin is called before
//Sabre\DAV\CorePlugin::httpGet
$this->server->on('method:GET', [$this, 'checkViewOnly'], 90);
$this->server->on('method:COPY', [$this, 'checkViewOnly'], 90);
}
/**
* Disallow download via DAV Api in case file being received share
* and having special permission
*
* @throws Forbidden
* @throws NotFoundException
*/
public function checkViewOnly(RequestInterface $request): bool {
$path = $request->getPath();
try {
assert($this->server !== null);
$davNode = $this->server->tree->getNodeForPath($path);
if ($davNode instanceof DavFile) {
// Restrict view-only to nodes which are shared
$node = $davNode->getNode();
} elseif ($davNode instanceof VersionFile) {
$node = $davNode->getVersion()->getSourceFile();
$currentUserId = $this->userFolder?->getOwner()?->getUID();
// The version source file is relative to the owner storage.
// But we need the node from the current user perspective.
if ($node->getOwner()->getUID() !== $currentUserId) {
$nodes = $this->userFolder->getById($node->getId());
$node = array_pop($nodes);
if (!$node) {
throw new NotFoundException("Version file not accessible by current user");
}
}
} else {
return true;
}
$storage = $node->getStorage();
if (!$storage->instanceOfStorage(\OCA\Files_Sharing\SharedStorage::class)) {
return true;
}
// Extract extra permissions
/** @var \OCA\Files_Sharing\SharedStorage $storage */
$share = $storage->getShare();
$attributes = $share->getAttributes();
if ($attributes === null) {
return true;
}
// Check if read-only and on whether permission can download is both set and disabled.
$canDownload = $attributes->getAttribute('permissions', 'download');
if ($canDownload !== null && !$canDownload) {
throw new Forbidden('Access to this resource has been denied because it is in view-only mode.');
}
} catch (NotFound $e) {
// File not found
}
return true;
}
}