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,507 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV\Activity;
use OCA\DAV\CardDAV\Activity\Provider\Addressbook;
use OCP\Activity\IEvent;
use OCP\Activity\IManager as IActivityManager;
use OCP\App\IAppManager;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
use Sabre\CardDAV\Plugin;
use Sabre\VObject\Reader;
class Backend {
/** @var IActivityManager */
protected $activityManager;
/** @var IGroupManager */
protected $groupManager;
/** @var IUserSession */
protected $userSession;
/** @var IAppManager */
protected $appManager;
/** @var IUserManager */
protected $userManager;
public function __construct(IActivityManager $activityManager,
IGroupManager $groupManager,
IUserSession $userSession,
IAppManager $appManager,
IUserManager $userManager) {
$this->activityManager = $activityManager;
$this->groupManager = $groupManager;
$this->userSession = $userSession;
$this->appManager = $appManager;
$this->userManager = $userManager;
}
/**
* Creates activities when an addressbook was creates
*
* @param array $addressbookData
*/
public function onAddressbookCreate(array $addressbookData): void {
$this->triggerAddressbookActivity(Addressbook::SUBJECT_ADD, $addressbookData);
}
/**
* Creates activities when a calendar was updated
*
* @param array $addressbookData
* @param array $shares
* @param array $properties
*/
public function onAddressbookUpdate(array $addressbookData, array $shares, array $properties): void {
$this->triggerAddressbookActivity(Addressbook::SUBJECT_UPDATE, $addressbookData, $shares, $properties);
}
/**
* Creates activities when a calendar was deleted
*
* @param array $addressbookData
* @param array $shares
*/
public function onAddressbookDelete(array $addressbookData, array $shares): void {
$this->triggerAddressbookActivity(Addressbook::SUBJECT_DELETE, $addressbookData, $shares);
}
/**
* Creates activities for all related users when a calendar was touched
*
* @param string $action
* @param array $addressbookData
* @param array $shares
* @param array $changedProperties
*/
protected function triggerAddressbookActivity(string $action, array $addressbookData, array $shares = [], array $changedProperties = []): void {
if (!isset($addressbookData['principaluri'])) {
return;
}
$principalUri = $addressbookData['principaluri'];
// We are not interested in changes from the system addressbook
if ($principalUri === 'principals/system/system') {
return;
}
$principal = explode('/', $principalUri);
$owner = array_pop($principal);
$currentUser = $this->userSession->getUser();
if ($currentUser instanceof IUser) {
$currentUser = $currentUser->getUID();
} else {
$currentUser = $owner;
}
$event = $this->activityManager->generateEvent();
$event->setApp('dav')
->setObject('addressbook', (int) $addressbookData['id'])
->setType('contacts')
->setAuthor($currentUser);
$changedVisibleInformation = array_intersect([
'{DAV:}displayname',
'{' . Plugin::NS_CARDDAV . '}addressbook-description',
], array_keys($changedProperties));
if (empty($shares) || ($action === Addressbook::SUBJECT_UPDATE && empty($changedVisibleInformation))) {
$users = [$owner];
} else {
$users = $this->getUsersForShares($shares);
$users[] = $owner;
}
foreach ($users as $user) {
if ($action === Addressbook::SUBJECT_DELETE && !$this->userManager->userExists($user)) {
// Avoid creating addressbook_delete activities for deleted users
continue;
}
$event->setAffectedUser($user)
->setSubject(
$user === $currentUser ? $action . '_self' : $action,
[
'actor' => $currentUser,
'addressbook' => [
'id' => (int) $addressbookData['id'],
'uri' => $addressbookData['uri'],
'name' => $addressbookData['{DAV:}displayname'],
],
]
);
$this->activityManager->publish($event);
}
}
/**
* Creates activities for all related users when an addressbook was (un-)shared
*
* @param array $addressbookData
* @param array $shares
* @param array $add
* @param array $remove
*/
public function onAddressbookUpdateShares(array $addressbookData, array $shares, array $add, array $remove): void {
$principal = explode('/', $addressbookData['principaluri']);
$owner = $principal[2];
$currentUser = $this->userSession->getUser();
if ($currentUser instanceof IUser) {
$currentUser = $currentUser->getUID();
} else {
$currentUser = $owner;
}
$event = $this->activityManager->generateEvent();
$event->setApp('dav')
->setObject('addressbook', (int) $addressbookData['id'])
->setType('contacts')
->setAuthor($currentUser);
foreach ($remove as $principal) {
// principal:principals/users/test
$parts = explode(':', $principal, 2);
if ($parts[0] !== 'principal') {
continue;
}
$principal = explode('/', $parts[1]);
if ($principal[1] === 'users') {
$this->triggerActivityUser(
$principal[2],
$event,
$addressbookData,
Addressbook::SUBJECT_UNSHARE_USER,
Addressbook::SUBJECT_DELETE . '_self'
);
if ($owner !== $principal[2]) {
$parameters = [
'actor' => $event->getAuthor(),
'addressbook' => [
'id' => (int) $addressbookData['id'],
'uri' => $addressbookData['uri'],
'name' => $addressbookData['{DAV:}displayname'],
],
'user' => $principal[2],
];
if ($owner === $event->getAuthor()) {
$subject = Addressbook::SUBJECT_UNSHARE_USER . '_you';
} elseif ($principal[2] === $event->getAuthor()) {
$subject = Addressbook::SUBJECT_UNSHARE_USER . '_self';
} else {
$event->setAffectedUser($event->getAuthor())
->setSubject(Addressbook::SUBJECT_UNSHARE_USER . '_you', $parameters);
$this->activityManager->publish($event);
$subject = Addressbook::SUBJECT_UNSHARE_USER . '_by';
}
$event->setAffectedUser($owner)
->setSubject($subject, $parameters);
$this->activityManager->publish($event);
}
} elseif ($principal[1] === 'groups') {
$this->triggerActivityGroup($principal[2], $event, $addressbookData, Addressbook::SUBJECT_UNSHARE_USER);
$parameters = [
'actor' => $event->getAuthor(),
'addressbook' => [
'id' => (int) $addressbookData['id'],
'uri' => $addressbookData['uri'],
'name' => $addressbookData['{DAV:}displayname'],
],
'group' => $principal[2],
];
if ($owner === $event->getAuthor()) {
$subject = Addressbook::SUBJECT_UNSHARE_GROUP . '_you';
} else {
$event->setAffectedUser($event->getAuthor())
->setSubject(Addressbook::SUBJECT_UNSHARE_GROUP . '_you', $parameters);
$this->activityManager->publish($event);
$subject = Addressbook::SUBJECT_UNSHARE_GROUP . '_by';
}
$event->setAffectedUser($owner)
->setSubject($subject, $parameters);
$this->activityManager->publish($event);
}
}
foreach ($add as $share) {
if ($this->isAlreadyShared($share['href'], $shares)) {
continue;
}
// principal:principals/users/test
$parts = explode(':', $share['href'], 2);
if ($parts[0] !== 'principal') {
continue;
}
$principal = explode('/', $parts[1]);
if ($principal[1] === 'users') {
$this->triggerActivityUser($principal[2], $event, $addressbookData, Addressbook::SUBJECT_SHARE_USER);
if ($owner !== $principal[2]) {
$parameters = [
'actor' => $event->getAuthor(),
'addressbook' => [
'id' => (int) $addressbookData['id'],
'uri' => $addressbookData['uri'],
'name' => $addressbookData['{DAV:}displayname'],
],
'user' => $principal[2],
];
if ($owner === $event->getAuthor()) {
$subject = Addressbook::SUBJECT_SHARE_USER . '_you';
} else {
$event->setAffectedUser($event->getAuthor())
->setSubject(Addressbook::SUBJECT_SHARE_USER . '_you', $parameters);
$this->activityManager->publish($event);
$subject = Addressbook::SUBJECT_SHARE_USER . '_by';
}
$event->setAffectedUser($owner)
->setSubject($subject, $parameters);
$this->activityManager->publish($event);
}
} elseif ($principal[1] === 'groups') {
$this->triggerActivityGroup($principal[2], $event, $addressbookData, Addressbook::SUBJECT_SHARE_USER);
$parameters = [
'actor' => $event->getAuthor(),
'addressbook' => [
'id' => (int) $addressbookData['id'],
'uri' => $addressbookData['uri'],
'name' => $addressbookData['{DAV:}displayname'],
],
'group' => $principal[2],
];
if ($owner === $event->getAuthor()) {
$subject = Addressbook::SUBJECT_SHARE_GROUP . '_you';
} else {
$event->setAffectedUser($event->getAuthor())
->setSubject(Addressbook::SUBJECT_SHARE_GROUP . '_you', $parameters);
$this->activityManager->publish($event);
$subject = Addressbook::SUBJECT_SHARE_GROUP . '_by';
}
$event->setAffectedUser($owner)
->setSubject($subject, $parameters);
$this->activityManager->publish($event);
}
}
}
/**
* Checks if a calendar is already shared with a principal
*
* @param string $principal
* @param array[] $shares
* @return bool
*/
protected function isAlreadyShared(string $principal, array $shares): bool {
foreach ($shares as $share) {
if ($principal === $share['href']) {
return true;
}
}
return false;
}
/**
* Creates the given activity for all members of the given group
*
* @param string $gid
* @param IEvent $event
* @param array $properties
* @param string $subject
*/
protected function triggerActivityGroup(string $gid, IEvent $event, array $properties, string $subject): void {
$group = $this->groupManager->get($gid);
if ($group instanceof IGroup) {
foreach ($group->getUsers() as $user) {
// Exclude current user
if ($user->getUID() !== $event->getAuthor()) {
$this->triggerActivityUser($user->getUID(), $event, $properties, $subject);
}
}
}
}
/**
* Creates the given activity for the given user
*
* @param string $user
* @param IEvent $event
* @param array $properties
* @param string $subject
* @param string $subjectSelf
*/
protected function triggerActivityUser(string $user, IEvent $event, array $properties, string $subject, string $subjectSelf = ''): void {
$event->setAffectedUser($user)
->setSubject(
$user === $event->getAuthor() && $subjectSelf ? $subjectSelf : $subject,
[
'actor' => $event->getAuthor(),
'addressbook' => [
'id' => (int) $properties['id'],
'uri' => $properties['uri'],
'name' => $properties['{DAV:}displayname'],
],
]
);
$this->activityManager->publish($event);
}
/**
* Creates activities when a card was created/updated/deleted
*
* @param string $action
* @param array $addressbookData
* @param array $shares
* @param array $cardData
*/
public function triggerCardActivity(string $action, array $addressbookData, array $shares, array $cardData): void {
if (!isset($addressbookData['principaluri'])) {
return;
}
$principalUri = $addressbookData['principaluri'];
// We are not interested in changes from the system addressbook
if ($principalUri === 'principals/system/system') {
return;
}
$principal = explode('/', $principalUri);
$owner = array_pop($principal);
$currentUser = $this->userSession->getUser();
if ($currentUser instanceof IUser) {
$currentUser = $currentUser->getUID();
} else {
$currentUser = $owner;
}
$card = $this->getCardNameAndId($cardData);
$event = $this->activityManager->generateEvent();
$event->setApp('dav')
->setObject('addressbook', (int) $addressbookData['id'])
->setType('contacts')
->setAuthor($currentUser);
$users = $this->getUsersForShares($shares);
$users[] = $owner;
// Users for share can return the owner itself if the calendar is published
foreach (array_unique($users) as $user) {
$params = [
'actor' => $event->getAuthor(),
'addressbook' => [
'id' => (int) $addressbookData['id'],
'uri' => $addressbookData['uri'],
'name' => $addressbookData['{DAV:}displayname'],
],
'card' => [
'id' => $card['id'],
'name' => $card['name'],
],
];
$event->setAffectedUser($user)
->setSubject(
$user === $currentUser ? $action . '_self' : $action,
$params
);
$this->activityManager->publish($event);
}
}
/**
* @param array $cardData
* @return string[]
*/
protected function getCardNameAndId(array $cardData): array {
$vObject = Reader::read($cardData['carddata']);
return ['id' => (string) $vObject->UID, 'name' => (string) ($vObject->FN ?? '')];
}
/**
* Get all users that have access to a given calendar
*
* @param array $shares
* @return string[]
*/
protected function getUsersForShares(array $shares): array {
$users = $groups = [];
foreach ($shares as $share) {
$principal = explode('/', $share['{http://owncloud.org/ns}principal']);
if ($principal[1] === 'users') {
$users[] = $principal[2];
} elseif ($principal[1] === 'groups') {
$groups[] = $principal[2];
}
}
if (!empty($groups)) {
foreach ($groups as $gid) {
$group = $this->groupManager->get($gid);
if ($group instanceof IGroup) {
foreach ($group->getUsers() as $user) {
$users[] = $user->getUID();
}
}
}
}
return array_unique($users);
}
}
@@ -0,0 +1,86 @@
<?php
/**
* @copyright Copyright (c) 2021 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV\Activity;
use OCP\Activity\IFilter;
use OCP\IL10N;
use OCP\IURLGenerator;
class Filter implements IFilter {
/** @var IL10N */
protected $l;
/** @var IURLGenerator */
protected $url;
public function __construct(IL10N $l, IURLGenerator $url) {
$this->l = $l;
$this->url = $url;
}
/**
* @return string Lowercase a-z and underscore only identifier
*/
public function getIdentifier(): string {
return 'contacts';
}
/**
* @return string A translated string
*/
public function getName(): string {
return $this->l->t('Contacts');
}
/**
* @return int whether the filter should be rather on the top or bottom of
* the admin section. The filters are arranged in ascending order of the
* priority values. It is required to return a value between 0 and 100.
*/
public function getPriority(): int {
return 40;
}
/**
* @return string Full URL to an icon, empty string when none is given
*/
public function getIcon(): string {
return $this->url->getAbsoluteURL($this->url->imagePath('core', 'places/contacts.svg'));
}
/**
* @param string[] $types
* @return string[] An array of allowed apps from which activities should be displayed
*/
public function filterTypes(array $types): array {
return array_intersect(['contacts'], $types);
}
/**
* @return string[] An array of allowed apps from which activities should be displayed
*/
public function allowedApps(): array {
return [];
}
}
@@ -0,0 +1,191 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV\Activity\Provider;
use OCP\Activity\IEvent;
use OCP\Activity\IEventMerger;
use OCP\Activity\IManager;
use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\L10N\IFactory;
class Addressbook extends Base {
public const SUBJECT_ADD = 'addressbook_add';
public const SUBJECT_UPDATE = 'addressbook_update';
public const SUBJECT_DELETE = 'addressbook_delete';
public const SUBJECT_SHARE_USER = 'addressbook_user_share';
public const SUBJECT_SHARE_GROUP = 'addressbook_group_share';
public const SUBJECT_UNSHARE_USER = 'addressbook_user_unshare';
public const SUBJECT_UNSHARE_GROUP = 'addressbook_group_unshare';
/** @var IFactory */
protected $languageFactory;
/** @var IManager */
protected $activityManager;
/** @var IEventMerger */
protected $eventMerger;
public function __construct(IFactory $languageFactory,
IURLGenerator $url,
IManager $activityManager,
IUserManager $userManager,
IGroupManager $groupManager,
IEventMerger $eventMerger) {
parent::__construct($userManager, $groupManager, $url);
$this->languageFactory = $languageFactory;
$this->activityManager = $activityManager;
$this->eventMerger = $eventMerger;
}
/**
* @param string $language
* @param IEvent $event
* @param IEvent|null $previousEvent
* @return IEvent
* @throws \InvalidArgumentException
*/
public function parse($language, IEvent $event, IEvent $previousEvent = null): IEvent {
if ($event->getApp() !== 'dav' || $event->getType() !== 'contacts') {
throw new \InvalidArgumentException();
}
$l = $this->languageFactory->get('dav', $language);
if ($this->activityManager->getRequirePNG()) {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'places/contacts-dark.png')));
} else {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'places/contacts.svg')));
}
if ($event->getSubject() === self::SUBJECT_ADD) {
$subject = $l->t('{actor} created address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_ADD . '_self') {
$subject = $l->t('You created address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_DELETE) {
$subject = $l->t('{actor} deleted address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_DELETE . '_self') {
$subject = $l->t('You deleted address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_UPDATE) {
$subject = $l->t('{actor} updated address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_UPDATE . '_self') {
$subject = $l->t('You updated address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_SHARE_USER) {
$subject = $l->t('{actor} shared address book {addressbook} with you');
} elseif ($event->getSubject() === self::SUBJECT_SHARE_USER . '_you') {
$subject = $l->t('You shared address book {addressbook} with {user}');
} elseif ($event->getSubject() === self::SUBJECT_SHARE_USER . '_by') {
$subject = $l->t('{actor} shared address book {addressbook} with {user}');
} elseif ($event->getSubject() === self::SUBJECT_UNSHARE_USER) {
$subject = $l->t('{actor} unshared address book {addressbook} from you');
} elseif ($event->getSubject() === self::SUBJECT_UNSHARE_USER . '_you') {
$subject = $l->t('You unshared address book {addressbook} from {user}');
} elseif ($event->getSubject() === self::SUBJECT_UNSHARE_USER . '_by') {
$subject = $l->t('{actor} unshared address book {addressbook} from {user}');
} elseif ($event->getSubject() === self::SUBJECT_UNSHARE_USER . '_self') {
$subject = $l->t('{actor} unshared address book {addressbook} from themselves');
} elseif ($event->getSubject() === self::SUBJECT_SHARE_GROUP . '_you') {
$subject = $l->t('You shared address book {addressbook} with group {group}');
} elseif ($event->getSubject() === self::SUBJECT_SHARE_GROUP . '_by') {
$subject = $l->t('{actor} shared address book {addressbook} with group {group}');
} elseif ($event->getSubject() === self::SUBJECT_UNSHARE_GROUP . '_you') {
$subject = $l->t('You unshared address book {addressbook} from group {group}');
} elseif ($event->getSubject() === self::SUBJECT_UNSHARE_GROUP . '_by') {
$subject = $l->t('{actor} unshared address book {addressbook} from group {group}');
} else {
throw new \InvalidArgumentException();
}
$parsedParameters = $this->getParameters($event, $l);
$this->setSubjects($event, $subject, $parsedParameters);
$event = $this->eventMerger->mergeEvents('addressbook', $event, $previousEvent);
if ($event->getChildEvent() === null) {
if (isset($parsedParameters['user'])) {
// Couldn't group by calendar, maybe we can group by users
$event = $this->eventMerger->mergeEvents('user', $event, $previousEvent);
} elseif (isset($parsedParameters['group'])) {
// Couldn't group by calendar, maybe we can group by groups
$event = $this->eventMerger->mergeEvents('group', $event, $previousEvent);
}
}
return $event;
}
protected function getParameters(IEvent $event, IL10N $l): array {
$subject = $event->getSubject();
$parameters = $event->getSubjectParameters();
switch ($subject) {
case self::SUBJECT_ADD:
case self::SUBJECT_ADD . '_self':
case self::SUBJECT_DELETE:
case self::SUBJECT_DELETE . '_self':
case self::SUBJECT_UPDATE:
case self::SUBJECT_UPDATE . '_self':
case self::SUBJECT_SHARE_USER:
case self::SUBJECT_UNSHARE_USER:
case self::SUBJECT_UNSHARE_USER . '_self':
return [
'actor' => $this->generateUserParameter($parameters['actor']),
'addressbook' => $this->generateAddressbookParameter($parameters['addressbook'], $l),
];
case self::SUBJECT_SHARE_USER . '_you':
case self::SUBJECT_UNSHARE_USER . '_you':
return [
'addressbook' => $this->generateAddressbookParameter($parameters['addressbook'], $l),
'user' => $this->generateUserParameter($parameters['user']),
];
case self::SUBJECT_SHARE_USER . '_by':
case self::SUBJECT_UNSHARE_USER . '_by':
return [
'actor' => $this->generateUserParameter($parameters['actor']),
'addressbook' => $this->generateAddressbookParameter($parameters['addressbook'], $l),
'user' => $this->generateUserParameter($parameters['user']),
];
case self::SUBJECT_SHARE_GROUP . '_you':
case self::SUBJECT_UNSHARE_GROUP . '_you':
return [
'addressbook' => $this->generateAddressbookParameter($parameters['addressbook'], $l),
'group' => $this->generateGroupParameter($parameters['group']),
];
case self::SUBJECT_SHARE_GROUP . '_by':
case self::SUBJECT_UNSHARE_GROUP . '_by':
return [
'actor' => $this->generateUserParameter($parameters['actor']),
'addressbook' => $this->generateAddressbookParameter($parameters['addressbook'], $l),
'group' => $this->generateGroupParameter($parameters['group']),
];
}
throw new \InvalidArgumentException();
}
}
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV\Activity\Provider;
use OCA\DAV\CardDAV\CardDavBackend;
use OCP\Activity\IEvent;
use OCP\Activity\IProvider;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUserManager;
abstract class Base implements IProvider {
/** @var IUserManager */
protected $userManager;
/** @var string[] */
protected $userDisplayNames = [];
/** @var IGroupManager */
protected $groupManager;
/** @var string[] */
protected $groupDisplayNames = [];
/** @var IURLGenerator */
protected $url;
public function __construct(IUserManager $userManager,
IGroupManager $groupManager,
IURLGenerator $urlGenerator) {
$this->userManager = $userManager;
$this->groupManager = $groupManager;
$this->url = $urlGenerator;
}
protected function setSubjects(IEvent $event, string $subject, array $parameters): void {
$event->setRichSubject($subject, $parameters);
}
/**
* @param array $data
* @param IL10N $l
* @return array
*/
protected function generateAddressbookParameter(array $data, IL10N $l): array {
if ($data['uri'] === CardDavBackend::PERSONAL_ADDRESSBOOK_URI &&
$data['name'] === CardDavBackend::PERSONAL_ADDRESSBOOK_NAME) {
return [
'type' => 'addressbook',
'id' => $data['id'],
'name' => $l->t('Personal'),
];
}
return [
'type' => 'addressbook',
'id' => $data['id'],
'name' => $data['name'],
];
}
protected function generateUserParameter(string $uid): array {
return [
'type' => 'user',
'id' => $uid,
'name' => $this->userManager->getDisplayName($uid) ?? $uid,
];
}
/**
* @param string $gid
* @return array
*/
protected function generateGroupParameter(string $gid): array {
if (!isset($this->groupDisplayNames[$gid])) {
$this->groupDisplayNames[$gid] = $this->getGroupDisplayName($gid);
}
return [
'type' => 'user-group',
'id' => $gid,
'name' => $this->groupDisplayNames[$gid],
];
}
/**
* @param string $gid
* @return string
*/
protected function getGroupDisplayName(string $gid): string {
$group = $this->groupManager->get($gid);
if ($group instanceof IGroup) {
return $group->getDisplayName();
}
return $gid;
}
}
@@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV\Activity\Provider;
use OCP\Activity\IEvent;
use OCP\Activity\IEventMerger;
use OCP\Activity\IManager;
use OCP\App\IAppManager;
use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\L10N\IFactory;
class Card extends Base {
public const SUBJECT_ADD = 'card_add';
public const SUBJECT_UPDATE = 'card_update';
public const SUBJECT_DELETE = 'card_delete';
/** @var IFactory */
protected $languageFactory;
/** @var IManager */
protected $activityManager;
/** @var IEventMerger */
protected $eventMerger;
/** @var IAppManager */
protected $appManager;
public function __construct(IFactory $languageFactory,
IURLGenerator $url,
IManager $activityManager,
IUserManager $userManager,
IGroupManager $groupManager,
IEventMerger $eventMerger,
IAppManager $appManager) {
parent::__construct($userManager, $groupManager, $url);
$this->languageFactory = $languageFactory;
$this->activityManager = $activityManager;
$this->eventMerger = $eventMerger;
$this->appManager = $appManager;
}
/**
* @param string $language
* @param IEvent $event
* @param IEvent|null $previousEvent
* @return IEvent
* @throws \InvalidArgumentException
*/
public function parse($language, IEvent $event, IEvent $previousEvent = null): IEvent {
if ($event->getApp() !== 'dav' || $event->getType() !== 'contacts') {
throw new \InvalidArgumentException();
}
$l = $this->languageFactory->get('dav', $language);
if ($this->activityManager->getRequirePNG()) {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'places/contacts-dark.png')));
} else {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'places/contacts.svg')));
}
if ($event->getSubject() === self::SUBJECT_ADD) {
$subject = $l->t('{actor} created contact {card} in address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_ADD . '_self') {
$subject = $l->t('You created contact {card} in address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_DELETE) {
$subject = $l->t('{actor} deleted contact {card} from address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_DELETE . '_self') {
$subject = $l->t('You deleted contact {card} from address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_UPDATE) {
$subject = $l->t('{actor} updated contact {card} in address book {addressbook}');
} elseif ($event->getSubject() === self::SUBJECT_UPDATE . '_self') {
$subject = $l->t('You updated contact {card} in address book {addressbook}');
} else {
throw new \InvalidArgumentException();
}
$parsedParameters = $this->getParameters($event, $l);
$this->setSubjects($event, $subject, $parsedParameters);
$event = $this->eventMerger->mergeEvents('card', $event, $previousEvent);
return $event;
}
protected function getParameters(IEvent $event, IL10N $l): array {
$subject = $event->getSubject();
$parameters = $event->getSubjectParameters();
switch ($subject) {
case self::SUBJECT_ADD:
case self::SUBJECT_DELETE:
case self::SUBJECT_UPDATE:
return [
'actor' => $this->generateUserParameter($parameters['actor']),
'addressbook' => $this->generateAddressbookParameter($parameters['addressbook'], $l),
'card' => $this->generateCardParameter($parameters['card']),
];
case self::SUBJECT_ADD . '_self':
case self::SUBJECT_DELETE . '_self':
case self::SUBJECT_UPDATE . '_self':
return [
'addressbook' => $this->generateAddressbookParameter($parameters['addressbook'], $l),
'card' => $this->generateCardParameter($parameters['card']),
];
}
throw new \InvalidArgumentException();
}
private function generateCardParameter(array $cardData): array {
return [
'type' => 'addressbook-contact',
'id' => $cardData['id'],
'name' => $cardData['name'],
];
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV\Activity;
use OCA\DAV\CalDAV\Activity\Setting\CalDAVSetting;
class Setting extends CalDAVSetting {
/**
* @return string Lowercase a-z and underscore only identifier
*/
public function getIdentifier(): string {
return 'contacts';
}
/**
* @return string A translated string
*/
public function getName(): string {
return $this->l->t('A <strong>contact</strong> or <strong>address book</strong> was modified');
}
/**
* @return int whether the filter should be rather on the top or bottom of
* the admin section. The filters are arranged in ascending order of the
* priority values. It is required to return a value between 0 and 100.
*/
public function getPriority(): int {
return 50;
}
/**
* @return bool True when the option can be changed for the stream
*/
public function canChangeStream(): bool {
return true;
}
/**
* @return bool True when the option can be changed for the stream
*/
public function isDefaultEnabledStream(): bool {
return true;
}
/**
* @return bool True when the option can be changed for the mail
*/
public function canChangeMail(): bool {
return true;
}
/**
* @return bool True when the option can be changed for the stream
*/
public function isDefaultEnabledMail(): bool {
return false;
}
}
@@ -0,0 +1,274 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.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\CardDAV;
use OCA\DAV\DAV\Sharing\IShareable;
use OCA\DAV\Exception\UnsupportedLimitOnInitialSyncException;
use OCP\DB\Exception;
use OCP\IL10N;
use OCP\Server;
use Psr\Log\LoggerInterface;
use Sabre\CardDAV\Backend\BackendInterface;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\IMoveTarget;
use Sabre\DAV\INode;
use Sabre\DAV\PropPatch;
/**
* Class AddressBook
*
* @package OCA\DAV\CardDAV
* @property CardDavBackend $carddavBackend
*/
class AddressBook extends \Sabre\CardDAV\AddressBook implements IShareable, IMoveTarget {
/**
* AddressBook constructor.
*
* @param BackendInterface $carddavBackend
* @param array $addressBookInfo
* @param IL10N $l10n
*/
public function __construct(BackendInterface $carddavBackend, array $addressBookInfo, IL10N $l10n) {
parent::__construct($carddavBackend, $addressBookInfo);
if ($this->addressBookInfo['{DAV:}displayname'] === CardDavBackend::PERSONAL_ADDRESSBOOK_NAME &&
$this->getName() === CardDavBackend::PERSONAL_ADDRESSBOOK_URI) {
$this->addressBookInfo['{DAV:}displayname'] = $l10n->t('Contacts');
}
}
/**
* Updates the list of shares.
*
* The first array is a list of people that are to be added to the
* addressbook.
*
* 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
* @throws Forbidden
*/
public function updateShares(array $add, array $remove): void {
if ($this->isShared()) {
throw new Forbidden();
}
$this->carddavBackend->updateShares($this, $add, $remove);
}
/**
* Returns the list of people whom this addressbook 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 {
if ($this->isShared()) {
return [];
}
return $this->carddavBackend->getShares($this->getResourceId());
}
public function getACL() {
$acl = [
[
'privilege' => '{DAV:}read',
'principal' => $this->getOwner(),
'protected' => true,
],[
'privilege' => '{DAV:}write',
'principal' => $this->getOwner(),
'protected' => true,
],
[
'privilege' => '{DAV:}write-properties',
'principal' => '{DAV:}authenticated',
'protected' => true,
],
];
if ($this->getOwner() === 'principals/system/system') {
$acl[] = [
'privilege' => '{DAV:}read',
'principal' => '{DAV:}authenticated',
'protected' => true,
];
}
if (!$this->isShared()) {
return $acl;
}
if ($this->getOwner() !== parent::getOwner()) {
$acl[] = [
'privilege' => '{DAV:}read',
'principal' => parent::getOwner(),
'protected' => true,
];
if ($this->canWrite()) {
$acl[] = [
'privilege' => '{DAV:}write',
'principal' => parent::getOwner(),
'protected' => true,
];
}
}
$acl = $this->carddavBackend->applyShareAcl($this->getResourceId(), $acl);
$allowedPrincipals = [$this->getOwner(), parent::getOwner(), 'principals/system/system', '{DAV:}authenticated'];
return array_filter($acl, function ($rule) use ($allowedPrincipals) {
return \in_array($rule['principal'], $allowedPrincipals, true);
});
}
public function getChildACL() {
return $this->getACL();
}
public function getChild($name) {
$obj = $this->carddavBackend->getCard($this->addressBookInfo['id'], $name);
if (!$obj) {
throw new NotFound('Card not found');
}
$obj['acl'] = $this->getChildACL();
return new Card($this->carddavBackend, $this->addressBookInfo, $obj);
}
public function getChildren() {
$objs = $this->carddavBackend->getCards($this->addressBookInfo['id']);
$children = [];
foreach ($objs as $obj) {
$obj['acl'] = $this->getChildACL();
$children[] = new Card($this->carddavBackend, $this->addressBookInfo, $obj);
}
return $children;
}
public function getMultipleChildren(array $paths) {
$objs = $this->carddavBackend->getMultipleCards($this->addressBookInfo['id'], $paths);
$children = [];
foreach ($objs as $obj) {
$obj['acl'] = $this->getChildACL();
$children[] = new Card($this->carddavBackend, $this->addressBookInfo, $obj);
}
return $children;
}
public function getResourceId(): int {
return $this->addressBookInfo['id'];
}
public function getOwner(): ?string {
if (isset($this->addressBookInfo['{http://owncloud.org/ns}owner-principal'])) {
return $this->addressBookInfo['{http://owncloud.org/ns}owner-principal'];
}
return parent::getOwner();
}
public function delete() {
if (isset($this->addressBookInfo['{http://owncloud.org/ns}owner-principal'])) {
$principal = 'principal:' . parent::getOwner();
$shares = $this->carddavBackend->getShares($this->getResourceId());
$shares = array_filter($shares, function ($share) use ($principal) {
return $share['href'] === $principal;
});
if (empty($shares)) {
throw new Forbidden();
}
$this->carddavBackend->updateShares($this, [], [
$principal
]);
return;
}
parent::delete();
}
public function propPatch(PropPatch $propPatch) {
if (!isset($this->addressBookInfo['{http://owncloud.org/ns}owner-principal'])) {
parent::propPatch($propPatch);
}
}
public function getContactsGroups() {
return $this->carddavBackend->collectCardProperties($this->getResourceId(), 'CATEGORIES');
}
private function isShared(): bool {
if (!isset($this->addressBookInfo['{http://owncloud.org/ns}owner-principal'])) {
return false;
}
return $this->addressBookInfo['{http://owncloud.org/ns}owner-principal'] !== $this->addressBookInfo['principaluri'];
}
private function canWrite(): bool {
if (isset($this->addressBookInfo['{http://owncloud.org/ns}read-only'])) {
return !$this->addressBookInfo['{http://owncloud.org/ns}read-only'];
}
return true;
}
public function getChanges($syncToken, $syncLevel, $limit = null) {
if (!$syncToken && $limit) {
throw new UnsupportedLimitOnInitialSyncException();
}
return parent::getChanges($syncToken, $syncLevel, $limit);
}
/**
* @inheritDoc
*/
public function moveInto($targetName, $sourcePath, INode $sourceNode) {
if (!($sourceNode instanceof Card)) {
return false;
}
try {
return $this->carddavBackend->moveCard($sourceNode->getAddressbookId(), (int)$this->addressBookInfo['id'], $sourceNode->getUri(), $sourceNode->getOwner());
} catch (Exception $e) {
// Avoid injecting LoggerInterface everywhere
Server::get(LoggerInterface::class)->error('Could not move calendar object: ' . $e->getMessage(), ['exception' => $e]);
return false;
}
}
}
@@ -0,0 +1,351 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arne Hamann <kontakt+github@arne.email>
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Björn Schießle <bjoern@schiessle.org>
* @author call-me-matt <nextcloud@matthiasheinisch.de>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Julius Härtl <jus@bitgrid.net>
* @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\CardDAV;
use OCP\Constants;
use OCP\IAddressBook;
use OCP\IURLGenerator;
use Sabre\VObject\Component\VCard;
use Sabre\VObject\Property;
use Sabre\VObject\Reader;
use Sabre\VObject\UUIDUtil;
class AddressBookImpl implements IAddressBook {
/** @var CardDavBackend */
private $backend;
/** @var array */
private $addressBookInfo;
/** @var AddressBook */
private $addressBook;
/** @var IURLGenerator */
private $urlGenerator;
/**
* AddressBookImpl constructor.
*
* @param AddressBook $addressBook
* @param array $addressBookInfo
* @param CardDavBackend $backend
* @param IUrlGenerator $urlGenerator
*/
public function __construct(
AddressBook $addressBook,
array $addressBookInfo,
CardDavBackend $backend,
IURLGenerator $urlGenerator) {
$this->addressBook = $addressBook;
$this->addressBookInfo = $addressBookInfo;
$this->backend = $backend;
$this->urlGenerator = $urlGenerator;
}
/**
* @return string defining the technical unique key
* @since 5.0.0
*/
public function getKey() {
return $this->addressBookInfo['id'];
}
/**
* @return string defining the unique uri
* @since 16.0.0
*/
public function getUri(): string {
return $this->addressBookInfo['uri'];
}
/**
* In comparison to getKey() this function returns a human readable (maybe translated) name
*
* @return mixed
* @since 5.0.0
*/
public function getDisplayName() {
return $this->addressBookInfo['{DAV:}displayname'];
}
/**
* @param string $pattern which should match within the $searchProperties
* @param array $searchProperties defines the properties within the query pattern should match
* @param array $options Options to define the output format and search behavior
* - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
* example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => 'g@h.i']]
* - 'escape_like_param' - If set to false wildcards _ and % are not escaped
* - 'limit' - Set a numeric limit for the search results
* - 'offset' - Set the offset for the limited search results
* - 'wildcard' - Whether the search should use wildcards
* @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options
* @return array an array of contacts which are arrays of key-value-pairs
* example result:
* [
* ['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => 'a@b.c', 'GEO' => '37.386013;-122.082932'],
* ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['d@e.f', 'g@h.i']]
* ]
* @since 5.0.0
*/
public function search($pattern, $searchProperties, $options) {
$results = $this->backend->search($this->getKey(), $pattern, $searchProperties, $options);
$withTypes = \array_key_exists('types', $options) && $options['types'] === true;
$vCards = [];
foreach ($results as $result) {
$vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']), $withTypes);
}
return $vCards;
}
/**
* @param array $properties this array if key-value-pairs defines a contact
* @return array an array representing the contact just created or updated
* @since 5.0.0
*/
public function createOrUpdate($properties) {
$update = false;
if (!isset($properties['URI'])) { // create a new contact
$uid = $this->createUid();
$uri = $uid . '.vcf';
$vCard = $this->createEmptyVCard($uid);
} else { // update existing contact
$uri = $properties['URI'];
$vCardData = $this->backend->getCard($this->getKey(), $uri);
$vCard = $this->readCard($vCardData['carddata']);
$update = true;
}
foreach ($properties as $key => $value) {
if (is_array($value)) {
$vCard->remove($key);
foreach ($value as $entry) {
if (is_string($entry)) {
$property = $vCard->createProperty($key, $entry);
} else {
if (($key === "ADR" || $key === "PHOTO") && is_string($entry["value"])) {
$entry["value"] = stripslashes($entry["value"]);
$entry["value"] = explode(';', $entry["value"]);
}
$property = $vCard->createProperty($key, $entry["value"]);
if (isset($entry["type"])) {
$property->add('TYPE', $entry["type"]);
}
}
$vCard->add($property);
}
} elseif ($key !== 'URI') {
$vCard->$key = $vCard->createProperty($key, $value);
}
}
if ($update) {
$this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
} else {
$this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
}
return $this->vCard2Array($uri, $vCard);
}
/**
* @return mixed
* @since 5.0.0
*/
public function getPermissions() {
$permissions = $this->addressBook->getACL();
$result = 0;
foreach ($permissions as $permission) {
switch ($permission['privilege']) {
case '{DAV:}read':
$result |= Constants::PERMISSION_READ;
break;
case '{DAV:}write':
$result |= Constants::PERMISSION_CREATE;
$result |= Constants::PERMISSION_UPDATE;
break;
case '{DAV:}all':
$result |= Constants::PERMISSION_ALL;
break;
}
}
return $result;
}
/**
* @param int $id the unique identifier to a contact
* @return bool successful or not
* @since 5.0.0
*/
public function delete($id) {
$uri = $this->backend->getCardUri($id);
return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
}
/**
* read vCard data into a vCard object
*
* @param string $cardData
* @return VCard
*/
protected function readCard($cardData) {
return Reader::read($cardData);
}
/**
* create UID for contact
*
* @return string
*/
protected function createUid() {
do {
$uid = $this->getUid();
$contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
} while (!empty($contact));
return $uid;
}
/**
* getUid is only there for testing, use createUid instead
*/
protected function getUid() {
return UUIDUtil::getUUID();
}
/**
* create empty vcard
*
* @param string $uid
* @return VCard
*/
protected function createEmptyVCard($uid) {
$vCard = new VCard();
$vCard->UID = $uid;
return $vCard;
}
/**
* create array with all vCard properties
*
* @param string $uri
* @param VCard $vCard
* @param boolean $withTypes (optional) return the values as arrays of value/type pairs
* @return array
*/
protected function vCard2Array($uri, VCard $vCard, $withTypes = false) {
$result = [
'URI' => $uri,
];
foreach ($vCard->children() as $property) {
if ($property->name === 'PHOTO' && in_array($property->getValueType(), ['BINARY', 'URI'])) {
$url = $this->urlGenerator->getAbsoluteURL(
$this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
$url .= implode('/', [
'addressbooks',
substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
$this->addressBookInfo['uri'],
$uri
]) . '?photo';
$result['PHOTO'] = 'VALUE=uri:' . $url;
} elseif (in_array($property->name, ['URL', 'GEO', 'CLOUD', 'ADR', 'EMAIL', 'IMPP', 'TEL', 'X-SOCIALPROFILE', 'RELATED', 'LANG', 'X-ADDRESSBOOKSERVER-MEMBER'])) {
if (!isset($result[$property->name])) {
$result[$property->name] = [];
}
$type = $this->getTypeFromProperty($property);
if ($withTypes) {
$result[$property->name][] = [
'type' => $type,
'value' => $property->getValue()
];
} else {
$result[$property->name][] = $property->getValue();
}
} else {
$result[$property->name] = $property->getValue();
}
}
if ($this->isSystemAddressBook()) {
$result['isLocalSystemBook'] = true;
}
return $result;
}
/**
* Get the type of the current property
*
* @param Property $property
* @return null|string
*/
protected function getTypeFromProperty(Property $property) {
$parameters = $property->parameters();
// Type is the social network, when it's empty we don't need this.
if (isset($parameters['TYPE'])) {
/** @var \Sabre\VObject\Parameter $type */
$type = $parameters['TYPE'];
return $type->getValue();
}
return null;
}
/**
* @inheritDoc
*/
public function isShared(): bool {
if (!isset($this->addressBookInfo['{http://owncloud.org/ns}owner-principal'])) {
return false;
}
return $this->addressBookInfo['principaluri']
!== $this->addressBookInfo['{http://owncloud.org/ns}owner-principal'];
}
/**
* @inheritDoc
*/
public function isSystemAddressBook(): bool {
return $this->addressBookInfo['principaluri'] === 'principals/system/system' && (
$this->addressBookInfo['uri'] === 'system' ||
$this->addressBookInfo['{DAV:}displayname'] === $this->urlGenerator->getBaseUrl()
);
}
}
@@ -0,0 +1,80 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Anna Larch <anna.larch@gmx.net>
*
* @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\CardDAV;
use OCA\DAV\AppInfo\PluginManager;
use OCP\IGroupManager;
use OCP\IUser;
class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot {
/** @var PluginManager */
private $pluginManager;
private ?IUser $user;
private ?IGroupManager $groupManager;
/**
* @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
* @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
* @param string $principalPrefix
*/
public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend,
\Sabre\CardDAV\Backend\BackendInterface $carddavBackend,
PluginManager $pluginManager,
?IUser $user,
?IGroupManager $groupManager,
string $principalPrefix = 'principals') {
parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
$this->pluginManager = $pluginManager;
$this->user = $user;
$this->groupManager = $groupManager;
}
/**
* This method returns a node for a principal.
*
* The passed array contains principal information, and is guaranteed to
* at least contain a uri item. Other properties may or may not be
* supplied by the authentication backend.
*
* @param array $principal
*
* @return \Sabre\DAV\INode
*/
public function getChildForPrincipal(array $principal) {
return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->pluginManager, $this->user, $this->groupManager);
}
public function getName() {
if ($this->principalPrefix === 'principals') {
return parent::getName();
}
// Grabbing all the components of the principal path.
$parts = explode('/', $this->principalPrefix);
// We are only interested in the second part.
return $parts[1];
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023, Thomas Citharel <nextcloud@tcit.fr>
*
* @author Thomas Citharel <nextcloud@tcit.fr>
*
* @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\CardDAV;
class Card extends \Sabre\CardDAV\Card {
public function getId(): int {
return (int) $this->cardData['id'];
}
public function getUri(): string {
return $this->cardData['uri'];
}
protected function isShared(): bool {
if (!isset($this->cardData['{http://owncloud.org/ns}owner-principal'])) {
return false;
}
return $this->cardData['{http://owncloud.org/ns}owner-principal'] !== $this->cardData['principaluri'];
}
public function getAddressbookId(): int {
return (int)$this->cardData['addressbookid'];
}
public function getPrincipalUri(): string {
return $this->addressBookInfo['principaluri'];
}
public function getOwner(): ?string {
if (isset($this->addressBookInfo['{http://owncloud.org/ns}owner-principal'])) {
return $this->addressBookInfo['{http://owncloud.org/ns}owner-principal'];
}
return parent::getOwner();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,88 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Robin Appelman <robin@icewind.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Tobia De Koninck <tobia@ledfan.be>
*
* @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\CardDAV;
use OCP\Contacts\IManager;
use OCP\IL10N;
use OCP\IURLGenerator;
class ContactsManager {
/** @var CardDavBackend */
private $backend;
/** @var IL10N */
private $l10n;
/**
* ContactsManager constructor.
*
* @param CardDavBackend $backend
* @param IL10N $l10n
*/
public function __construct(CardDavBackend $backend, IL10N $l10n) {
$this->backend = $backend;
$this->l10n = $l10n;
}
/**
* @param IManager $cm
* @param string $userId
* @param IURLGenerator $urlGenerator
*/
public function setupContactsProvider(IManager $cm, $userId, IURLGenerator $urlGenerator) {
$addressBooks = $this->backend->getAddressBooksForUser("principals/users/$userId");
$this->register($cm, $addressBooks, $urlGenerator);
$this->setupSystemContactsProvider($cm, $urlGenerator);
}
/**
* @param IManager $cm
* @param IURLGenerator $urlGenerator
*/
public function setupSystemContactsProvider(IManager $cm, IURLGenerator $urlGenerator) {
$addressBooks = $this->backend->getAddressBooksForUser("principals/system/system");
$this->register($cm, $addressBooks, $urlGenerator);
}
/**
* @param IManager $cm
* @param $addressBooks
* @param IURLGenerator $urlGenerator
*/
private function register(IManager $cm, $addressBooks, $urlGenerator) {
foreach ($addressBooks as $addressBookInfo) {
$addressBook = new \OCA\DAV\CardDAV\AddressBook($this->backend, $addressBookInfo, $this->l10n);
$cm->registerAddressBook(
new AddressBookImpl(
$addressBook,
$addressBookInfo,
$this->backend,
$urlGenerator
)
);
}
}
}
@@ -0,0 +1,190 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @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\CardDAV;
use Exception;
use OCP\Accounts\IAccountManager;
use OCP\IImage;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use Sabre\VObject\Component\VCard;
use Sabre\VObject\Property\Text;
class Converter {
/** @var IURLGenerator */
private $urlGenerator;
/** @var IAccountManager */
private $accountManager;
private IUserManager $userManager;
public function __construct(IAccountManager $accountManager,
IUserManager $userManager, IURLGenerator $urlGenerator) {
$this->accountManager = $accountManager;
$this->userManager = $userManager;
$this->urlGenerator = $urlGenerator;
}
public function createCardFromUser(IUser $user): ?VCard {
$userProperties = $this->accountManager->getAccount($user)->getAllProperties();
$uid = $user->getUID();
$cloudId = $user->getCloudId();
$image = $this->getAvatarImage($user);
$vCard = new VCard();
$vCard->VERSION = '3.0';
$vCard->UID = $uid;
$publish = false;
foreach ($userProperties as $property) {
if ($property->getName() !== IAccountManager::PROPERTY_AVATAR && empty($property->getValue())) {
continue;
}
$scope = $property->getScope();
// Do not write private data to the system address book at all
if ($scope === IAccountManager::SCOPE_PRIVATE || empty($scope)) {
continue;
}
$publish = true;
switch ($property->getName()) {
case IAccountManager::PROPERTY_DISPLAYNAME:
$vCard->add(new Text($vCard, 'FN', $property->getValue(), ['X-NC-SCOPE' => $scope]));
$vCard->add(new Text($vCard, 'N', $this->splitFullName($property->getValue()), ['X-NC-SCOPE' => $scope]));
break;
case IAccountManager::PROPERTY_AVATAR:
if ($image !== null) {
$vCard->add('PHOTO', $image->data(), ['ENCODING' => 'b', 'TYPE' => $image->mimeType(), ['X-NC-SCOPE' => $scope]]);
}
break;
case IAccountManager::COLLECTION_EMAIL:
case IAccountManager::PROPERTY_EMAIL:
$vCard->add(new Text($vCard, 'EMAIL', $property->getValue(), ['TYPE' => 'OTHER', 'X-NC-SCOPE' => $scope]));
break;
case IAccountManager::PROPERTY_WEBSITE:
$vCard->add(new Text($vCard, 'URL', $property->getValue(), ['X-NC-SCOPE' => $scope]));
break;
case IAccountManager::PROPERTY_PROFILE_ENABLED:
if ($property->getValue()) {
$vCard->add(
new Text(
$vCard,
'X-SOCIALPROFILE',
$this->urlGenerator->linkToRouteAbsolute('core.ProfilePage.index', ['targetUserId' => $user->getUID()]),
[
'TYPE' => 'NEXTCLOUD',
'X-NC-SCOPE' => IAccountManager::SCOPE_PUBLISHED
]
)
);
}
break;
case IAccountManager::PROPERTY_PHONE:
$vCard->add(new Text($vCard, 'TEL', $property->getValue(), ['TYPE' => 'VOICE', 'X-NC-SCOPE' => $scope]));
break;
case IAccountManager::PROPERTY_ADDRESS:
// structured prop: https://www.rfc-editor.org/rfc/rfc6350.html#section-6.3.1
// post office box;extended address;street address;locality;region;postal code;country
$vCard->add(
new Text(
$vCard,
'ADR',
[ '', '', '', $property->getValue(), '', '', '' ],
[
'TYPE' => 'OTHER',
'X-NC-SCOPE' => $scope,
]
)
);
break;
case IAccountManager::PROPERTY_TWITTER:
$vCard->add(new Text($vCard, 'X-SOCIALPROFILE', $property->getValue(), ['TYPE' => 'TWITTER', 'X-NC-SCOPE' => $scope]));
break;
case IAccountManager::PROPERTY_ORGANISATION:
$vCard->add(new Text($vCard, 'ORG', $property->getValue(), ['X-NC-SCOPE' => $scope]));
break;
case IAccountManager::PROPERTY_ROLE:
$vCard->add(new Text($vCard, 'TITLE', $property->getValue(), ['X-NC-SCOPE' => $scope]));
break;
}
}
// Local properties
$managers = $user->getManagerUids();
// X-MANAGERSNAME only allows a single value, so we take the first manager
if (isset($managers[0])) {
$displayName = $this->userManager->getDisplayName($managers[0]);
// Only set the manager if a user object is found
if ($displayName !== null) {
$vCard->add(new Text($vCard, 'X-MANAGERSNAME', $displayName, [
'uid' => $managers[0],
'X-NC-SCOPE' => IAccountManager::SCOPE_LOCAL,
]));
}
}
if ($publish && !empty($cloudId)) {
$vCard->add(new Text($vCard, 'CLOUD', $cloudId));
$vCard->validate();
return $vCard;
}
return null;
}
public function splitFullName(string $fullName): array {
// Very basic western style parsing. I'm not gonna implement
// https://github.com/android/platform_packages_providers_contactsprovider/blob/master/src/com/android/providers/contacts/NameSplitter.java ;)
$elements = explode(' ', $fullName);
$result = ['', '', '', '', ''];
if (count($elements) > 2) {
$result[0] = implode(' ', array_slice($elements, count($elements) - 1));
$result[1] = $elements[0];
$result[2] = implode(' ', array_slice($elements, 1, count($elements) - 2));
} elseif (count($elements) === 2) {
$result[0] = $elements[1];
$result[1] = $elements[0];
} else {
$result[0] = $elements[0];
}
return $result;
}
private function getAvatarImage(IUser $user): ?IImage {
try {
return $user->getAvatarImage(512);
} catch (Exception $ex) {
return null;
}
}
}
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 John Molakvoæ <skjnldsv@protonmail.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV;
use Sabre\CardDAV\Card;
use Sabre\DAV\INode;
use Sabre\DAV\PropFind;
use Sabre\DAV\Server;
use Sabre\DAV\ServerPlugin;
use Sabre\VObject\Component\VCard;
use Sabre\VObject\Reader;
class HasPhotoPlugin extends ServerPlugin {
/** @var Server */
protected $server;
/**
* Initializes the plugin and registers event handlers
*
* @param Server $server
* @return void
*/
public function initialize(Server $server) {
$server->on('propFind', [$this, 'propFind']);
}
/**
* Adds all CardDAV-specific properties
*
* @param PropFind $propFind
* @param INode $node
* @return void
*/
public function propFind(PropFind $propFind, INode $node) {
$ns = '{http://nextcloud.com/ns}';
if ($node instanceof Card) {
$propFind->handle($ns . 'has-photo', function () use ($node) {
$vcard = Reader::read($node->get());
return $vcard instanceof VCard
&& $vcard->PHOTO
// Either the PHOTO is a url (doesn't start with data:) or the mimetype has to start with image/
&& (!str_starts_with($vcard->PHOTO->getValue(), 'data:')
|| str_starts_with($vcard->PHOTO->getValue(), 'data:image/'))
;
});
}
}
/**
* 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 'vcard-has-photo';
}
/**
* Returns a bunch of meta-data about the plugin.
*
* Providing this information is optional, and is mainly displayed by the
* Browser plugin.
*
* The description key in the returned array may contain html and will not
* be sanitized.
*
* @return array
*/
public function getPluginInfo() {
return [
'name' => $this->getPluginName(),
'description' => 'Return a boolean stating if the vcard have a photo property set or not.'
];
}
}
@@ -0,0 +1,116 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Jacob Neplokh <me@jacobneplokh.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @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\CardDAV;
use OCP\Files\NotFoundException;
use Sabre\CardDAV\Card;
use Sabre\DAV\Server;
use Sabre\DAV\ServerPlugin;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
class ImageExportPlugin extends ServerPlugin {
/** @var Server */
protected $server;
/** @var PhotoCache */
private $cache;
/**
* ImageExportPlugin constructor.
*
* @param PhotoCache $cache
*/
public function __construct(PhotoCache $cache) {
$this->cache = $cache;
}
/**
* Initializes the plugin and registers event handlers
*
* @param Server $server
* @return void
*/
public function initialize(Server $server) {
$this->server = $server;
$this->server->on('method:GET', [$this, 'httpGet'], 90);
}
/**
* Intercepts GET requests on addressbook urls ending with ?photo.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @return bool
*/
public function httpGet(RequestInterface $request, ResponseInterface $response) {
$queryParams = $request->getQueryParameters();
// TODO: in addition to photo we should also add logo some point in time
if (!array_key_exists('photo', $queryParams)) {
return true;
}
$size = isset($queryParams['size']) ? (int)$queryParams['size'] : -1;
$path = $request->getPath();
$node = $this->server->tree->getNodeForPath($path);
if (!($node instanceof Card)) {
return true;
}
$this->server->transactionType = 'carddav-image-export';
// Checking ACL, if available.
if ($aclPlugin = $this->server->getPlugin('acl')) {
/** @var \Sabre\DAVACL\Plugin $aclPlugin */
$aclPlugin->checkPrivileges($path, '{DAV:}read');
}
// Fetch addressbook
$addressbookpath = explode('/', $path);
array_pop($addressbookpath);
$addressbookpath = implode('/', $addressbookpath);
/** @var AddressBook $addressbook */
$addressbook = $this->server->tree->getNodeForPath($addressbookpath);
$response->setHeader('Cache-Control', 'private, max-age=3600, must-revalidate');
$response->setHeader('Etag', $node->getETag());
try {
$file = $this->cache->get($addressbook->getResourceId(), $node->getName(), $size, $node);
$response->setHeader('Content-Type', $file->getMimeType());
$fileName = $node->getName() . '.' . PhotoCache::ALLOWED_CONTENT_TYPES[$file->getMimeType()];
$response->setHeader('Content-Disposition', "attachment; filename=$fileName");
$response->setStatus(200);
$response->setBody($file->getContent());
} catch (NotFoundException $e) {
$response->setStatus(404);
}
return false;
}
}
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV\Integration;
use Sabre\CardDAV\IAddressBook;
use Sabre\DAV;
/**
* @since 19.0.0
*/
abstract class ExternalAddressBook implements IAddressBook, DAV\IProperties {
/** @var string */
private const PREFIX = 'z-app-generated';
/**
* @var string
*
* Double dash is a valid delimiter,
* because it will always split the URIs correctly:
* - our prefix contains only one dash and won't be split
* - appIds are not allowed to contain dashes as per spec:
* > must contain only lowercase ASCII characters and underscore
* - explode has a limit of three, so even if the app-generated
* URI has double dashes, it won't be split
*/
private const DELIMITER = '--';
private string $appId;
private string $uri;
public function __construct(string $appId, string $uri) {
$this->appId = $appId;
$this->uri = $uri;
}
/**
* @inheritDoc
*/
final public function getName() {
return implode(self::DELIMITER, [
self::PREFIX,
$this->appId,
$this->uri,
]);
}
/**
* @inheritDoc
*/
final public function setName($name) {
throw new DAV\Exception\MethodNotAllowed('Renaming address books is not yet supported');
}
/**
* @inheritDoc
*/
final public function createDirectory($name) {
throw new DAV\Exception\MethodNotAllowed('Creating collections in address book objects is not allowed');
}
/**
* Checks whether the address book uri is app-generated
*
* @param string $uri
*
* @return bool
*/
public static function isAppGeneratedAddressBook(string $uri): bool {
return str_starts_with($uri, self::PREFIX) && substr_count($uri, self::DELIMITER) >= 2;
}
/**
* Splits an app-generated uri into appId and uri
*
* @param string $uri
*
* @return array
*/
public static function splitAppGeneratedAddressBookUri(string $uri): array {
$array = array_slice(explode(self::DELIMITER, $uri, 3), 1);
// Check the array has expected amount of elements
// and none of them is an empty string
if (\count($array) !== 2 || \in_array('', $array, true)) {
throw new \InvalidArgumentException('Provided address book uri was not app-generated');
}
return $array;
}
/**
* Checks whether a address book name the user wants to create violates
* the reserved name for URIs
*
* @param string $uri
*
* @return bool
*/
public static function doesViolateReservedName(string $uri): bool {
return str_starts_with($uri, self::PREFIX);
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV\Integration;
/**
* @since 19.0.0
*/
interface IAddressBookProvider {
/**
* Provides the appId of the plugin
*
* @since 19.0.0
* @return string AppId
*/
public function getAppId(): string;
/**
* Fetches all address books for a given principal uri
*
* @since 19.0.0
* @param string $principalUri E.g. principals/users/user1
* @return ExternalAddressBook[] Array of all address books
*/
public function fetchAllForAddressBookHome(string $principalUri): array;
/**
* Checks whether plugin has an address book for a given principalUri and URI
*
* @since 19.0.0
* @param string $principalUri E.g. principals/users/user1
* @param string $uri E.g. personal
* @return bool True if address book for principalUri and URI exists, false otherwise
*/
public function hasAddressBookInAddressBookHome(string $principalUri, string $uri): bool;
/**
* Fetches an address book for a given principalUri and URI
* Returns null if address book does not exist
*
* @param string $principalUri E.g. principals/users/user1
* @param string $uri E.g. personal
*
* @return ExternalAddressBook|null address book if it exists, null otherwise
*@since 19.0.0
*/
public function getAddressBookInAddressBookHome(string $principalUri, string $uri): ?ExternalAddressBook;
}
@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 John Molakvoæ <skjnldsv@protonmail.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV;
use Sabre\DAV;
use Sabre\DAV\Server;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
class MultiGetExportPlugin extends DAV\ServerPlugin {
/** @var Server */
protected $server;
/**
* Initializes the plugin and registers event handlers
*
* @param Server $server
* @return void
*/
public function initialize(Server $server) {
$this->server = $server;
$this->server->on('afterMethod:REPORT', [$this, 'httpReport'], 90);
}
/**
* Intercepts REPORT requests
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @return bool
*/
public function httpReport(RequestInterface $request, ResponseInterface $response) {
$queryParams = $request->getQueryParameters();
if (!array_key_exists('export', $queryParams)) {
return;
}
// Only handling xml
$contentType = (string) $response->getHeader('Content-Type');
if (!str_contains($contentType, 'application/xml') && !str_contains($contentType, 'text/xml')) {
return;
}
$this->server->transactionType = 'vcf-multi-get-intercept-and-export';
// Get the xml response
$responseBody = $response->getBodyAsString();
$responseXml = $this->server->xml->parse($responseBody);
// Reduce the vcards into one string
$output = array_reduce($responseXml->getResponses(), function ($vcf, $card) {
$vcf .= $card->getResponseProperties()[200]['{urn:ietf:params:xml:ns:carddav}address-data'] . PHP_EOL;
return $vcf;
}, '');
// Build and override the response
$filename = 'vcfexport-' . date('Y-m-d') . '.vcf';
$response->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
$response->setHeader('Content-Type', 'text/vcard');
$response->setStatus(200);
$response->setBody($output);
return true;
}
/**
* 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 'vcf-multi-get-intercept-and-export';
}
/**
* Returns a bunch of meta-data about the plugin.
*
* Providing this information is optional, and is mainly displayed by the
* Browser plugin.
*
* The description key in the returned array may contain html and will not
* be sanitized.
*
* @return array
*/
public function getPluginInfo() {
return [
'name' => $this->getPluginName(),
'description' => 'Intercept a multi-get request and return a single vcf file instead.'
];
}
}
@@ -0,0 +1,291 @@
<?php
/**
* @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Jacob Neplokh <me@jacobneplokh.com>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @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/>.
*
*/
namespace OCA\DAV\CardDAV;
use OCP\Files\IAppData;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\Files\SimpleFS\ISimpleFile;
use OCP\Files\SimpleFS\ISimpleFolder;
use Psr\Log\LoggerInterface;
use Sabre\CardDAV\Card;
use Sabre\VObject\Document;
use Sabre\VObject\Parameter;
use Sabre\VObject\Property\Binary;
use Sabre\VObject\Reader;
class PhotoCache {
/** @var array */
public const ALLOWED_CONTENT_TYPES = [
'image/png' => 'png',
'image/jpeg' => 'jpg',
'image/gif' => 'gif',
'image/vnd.microsoft.icon' => 'ico',
];
protected IAppData $appData;
protected LoggerInterface $logger;
/**
* PhotoCache constructor.
*/
public function __construct(IAppData $appData, LoggerInterface $logger) {
$this->appData = $appData;
$this->logger = $logger;
}
/**
* @throws NotFoundException
*/
public function get(int $addressBookId, string $cardUri, int $size, Card $card): ISimpleFile {
$folder = $this->getFolder($addressBookId, $cardUri);
if ($this->isEmpty($folder)) {
$this->init($folder, $card);
}
if (!$this->hasPhoto($folder)) {
throw new NotFoundException();
}
if ($size !== -1) {
$size = 2 ** ceil(log($size) / log(2));
}
return $this->getFile($folder, $size);
}
private function isEmpty(ISimpleFolder $folder): bool {
return $folder->getDirectoryListing() === [];
}
/**
* @throws NotPermittedException
*/
private function init(ISimpleFolder $folder, Card $card): void {
$data = $this->getPhoto($card);
if ($data === false || !isset($data['Content-Type'])) {
$folder->newFile('nophoto', '');
return;
}
$contentType = $data['Content-Type'];
$extension = self::ALLOWED_CONTENT_TYPES[$contentType] ?? null;
if ($extension === null) {
$folder->newFile('nophoto', '');
return;
}
$file = $folder->newFile('photo.' . $extension);
$file->putContent($data['body']);
}
private function hasPhoto(ISimpleFolder $folder): bool {
return !$folder->fileExists('nophoto');
}
/**
* @param float|-1 $size
*/
private function getFile(ISimpleFolder $folder, $size): ISimpleFile {
$ext = $this->getExtension($folder);
if ($size === -1) {
$path = 'photo.' . $ext;
} else {
$path = 'photo.' . $size . '.' . $ext;
}
try {
$file = $folder->getFile($path);
} catch (NotFoundException $e) {
if ($size <= 0) {
throw new NotFoundException;
}
$photo = new \OCP\Image();
/** @var ISimpleFile $file */
$file = $folder->getFile('photo.' . $ext);
$photo->loadFromData($file->getContent());
$ratio = $photo->width() / $photo->height();
if ($ratio < 1) {
$ratio = 1 / $ratio;
}
$size = (int) ($size * $ratio);
if ($size !== -1) {
$photo->resize($size);
}
try {
$file = $folder->newFile($path);
$file->putContent($photo->data());
} catch (NotPermittedException $e) {
}
}
return $file;
}
/**
* @throws NotFoundException
* @throws NotPermittedException
*/
private function getFolder(int $addressBookId, string $cardUri, bool $createIfNotExists = true): ISimpleFolder {
$hash = md5($addressBookId . ' ' . $cardUri);
try {
return $this->appData->getFolder($hash);
} catch (NotFoundException $e) {
if ($createIfNotExists) {
return $this->appData->newFolder($hash);
} else {
throw $e;
}
}
}
/**
* Get the extension of the avatar. If there is no avatar throw Exception
*
* @throws NotFoundException
*/
private function getExtension(ISimpleFolder $folder): string {
foreach (self::ALLOWED_CONTENT_TYPES as $extension) {
if ($folder->fileExists('photo.' . $extension)) {
return $extension;
}
}
throw new NotFoundException('Avatar not found');
}
/**
* @param Card $node
* @return false|array{body: string, Content-Type: string}
*/
private function getPhoto(Card $node) {
try {
$vObject = $this->readCard($node->get());
return $this->getPhotoFromVObject($vObject);
} catch (\Exception $e) {
$this->logger->error('Exception during vcard photo parsing', [
'exception' => $e
]);
}
return false;
}
/**
* @return false|array{body: string, Content-Type: string}
*/
public function getPhotoFromVObject(Document $vObject) {
try {
if (!$vObject->PHOTO) {
return false;
}
$photo = $vObject->PHOTO;
$val = $photo->getValue();
// handle data URI. e.g PHOTO;VALUE=URI:data:image/jpeg;base64,/9j/4AAQSkZJRgABAQE
if ($photo->getValueType() === 'URI') {
$parsed = \Sabre\URI\parse($val);
// only allow data://
if ($parsed['scheme'] !== 'data') {
return false;
}
if (substr_count($parsed['path'], ';') === 1) {
[$type] = explode(';', $parsed['path']);
}
$val = file_get_contents($val);
} else {
// get type if binary data
$type = $this->getBinaryType($photo);
}
if (empty($type) || !isset(self::ALLOWED_CONTENT_TYPES[$type])) {
$type = 'application/octet-stream';
}
return [
'Content-Type' => $type,
'body' => $val
];
} catch (\Exception $e) {
$this->logger->error('Exception during vcard photo parsing', [
'exception' => $e
]);
}
return false;
}
private function readCard(string $cardData): Document {
return Reader::read($cardData);
}
/**
* @param Binary $photo
* @return string
*/
private function getBinaryType(Binary $photo) {
$params = $photo->parameters();
if (isset($params['TYPE']) || isset($params['MEDIATYPE'])) {
/** @var Parameter $typeParam */
$typeParam = isset($params['TYPE']) ? $params['TYPE'] : $params['MEDIATYPE'];
$type = (string) $typeParam->getValue();
if (str_starts_with($type, 'image/')) {
return $type;
} else {
return 'image/' . strtolower($type);
}
}
return '';
}
/**
* @param int $addressBookId
* @param string $cardUri
* @throws NotPermittedException
*/
public function delete($addressBookId, $cardUri) {
try {
$folder = $this->getFolder($addressBookId, $cardUri, false);
$folder->delete();
} catch (NotFoundException $e) {
// that's OK, nothing to do
}
}
}
@@ -0,0 +1,74 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @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\CardDAV;
use OCA\DAV\CardDAV\Xml\Groups;
use Sabre\DAV\INode;
use Sabre\DAV\PropFind;
use Sabre\DAV\Server;
class Plugin extends \Sabre\CardDAV\Plugin {
public function initialize(Server $server) {
$server->on('propFind', [$this, 'propFind']);
parent::initialize($server);
}
/**
* Returns the addressbook home for a given principal
*
* @param string $principal
* @return string|null
*/
protected function getAddressbookHomeForPrincipal($principal) {
if (strrpos($principal, 'principals/users', -strlen($principal)) !== false) {
[, $principalId] = \Sabre\Uri\split($principal);
return self::ADDRESSBOOK_ROOT . '/users/' . $principalId;
}
if (strrpos($principal, 'principals/groups', -strlen($principal)) !== false) {
[, $principalId] = \Sabre\Uri\split($principal);
return self::ADDRESSBOOK_ROOT . '/groups/' . $principalId;
}
if (strrpos($principal, 'principals/system', -strlen($principal)) !== false) {
[, $principalId] = \Sabre\Uri\split($principal);
return self::ADDRESSBOOK_ROOT . '/system/' . $principalId;
}
}
/**
* Adds all CardDAV-specific properties
*
* @param PropFind $propFind
* @param INode $node
* @return void
*/
public function propFind(PropFind $propFind, INode $node) {
$ns = '{http://owncloud.org/ns}';
if ($node instanceof AddressBook) {
$propFind->handle($ns . 'groups', function () use ($node) {
return new Groups($node->getContactsGroups());
});
}
}
}
@@ -0,0 +1,302 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Thomas Citharel <nextcloud@tcit.fr>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Anna Larch <anna.larch@gmx.net>
*
* @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\CardDAV;
use OCP\AppFramework\Db\TTransactional;
use OCP\AppFramework\Http;
use OCP\IDBConnection;
use OCP\IUser;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;
use Sabre\DAV\Client;
use Sabre\DAV\Xml\Response\MultiStatus;
use Sabre\DAV\Xml\Service;
use Sabre\HTTP\ClientHttpException;
use Sabre\VObject\Reader;
use function is_null;
class SyncService {
use TTransactional;
private CardDavBackend $backend;
private IUserManager $userManager;
private IDBConnection $dbConnection;
private LoggerInterface $logger;
private ?array $localSystemAddressBook = null;
private Converter $converter;
protected string $certPath;
public function __construct(CardDavBackend $backend,
IUserManager $userManager,
IDBConnection $dbConnection,
LoggerInterface $logger,
Converter $converter) {
$this->backend = $backend;
$this->userManager = $userManager;
$this->logger = $logger;
$this->converter = $converter;
$this->certPath = '';
$this->dbConnection = $dbConnection;
}
/**
* @throws \Exception
*/
public function syncRemoteAddressBook(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken, string $targetBookHash, string $targetPrincipal, array $targetProperties): string {
// 1. create addressbook
$book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookHash, $targetProperties);
$addressBookId = $book['id'];
// 2. query changes
try {
$response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
} catch (ClientHttpException $ex) {
if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
// remote server revoked access to the address book, remove it
$this->backend->deleteAddressBook($addressBookId);
$this->logger->error('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
throw $ex;
}
$this->logger->error('Client exception:', ['app' => 'dav', 'exception' => $ex]);
throw $ex;
}
// 3. apply changes
// TODO: use multi-get for download
foreach ($response['response'] as $resource => $status) {
$cardUri = basename($resource);
if (isset($status[200])) {
$vCard = $this->download($url, $userName, $sharedSecret, $resource);
$this->atomic(function () use ($addressBookId, $cardUri, $vCard) {
$existingCard = $this->backend->getCard($addressBookId, $cardUri);
if ($existingCard === false) {
$this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
} else {
$this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
}
}, $this->dbConnection);
} else {
$this->backend->deleteCard($addressBookId, $cardUri);
}
}
return $response['token'];
}
/**
* @throws \Sabre\DAV\Exception\BadRequest
*/
public function ensureSystemAddressBookExists(string $principal, string $uri, array $properties): ?array {
return $this->atomic(function () use ($principal, $uri, $properties) {
$book = $this->backend->getAddressBooksByUri($principal, $uri);
if (!is_null($book)) {
return $book;
}
$this->backend->createAddressBook($principal, $uri, $properties);
return $this->backend->getAddressBooksByUri($principal, $uri);
}, $this->dbConnection);
}
/**
* Check if there is a valid certPath we should use
*/
protected function getCertPath(): string {
// we already have a valid certPath
if ($this->certPath !== '') {
return $this->certPath;
}
$certManager = \OC::$server->getCertificateManager();
$certPath = $certManager->getAbsoluteBundlePath();
if (file_exists($certPath)) {
$this->certPath = $certPath;
}
return $this->certPath;
}
protected function getClient(string $url, string $userName, string $sharedSecret): Client {
$settings = [
'baseUri' => $url . '/',
'userName' => $userName,
'password' => $sharedSecret,
];
$client = new Client($settings);
$certPath = $this->getCertPath();
$client->setThrowExceptions(true);
if ($certPath !== '' && !str_starts_with($url, 'http://')) {
$client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
}
return $client;
}
protected function requestSyncReport(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken): array {
$client = $this->getClient($url, $userName, $sharedSecret);
$body = $this->buildSyncCollectionRequestBody($syncToken);
$response = $client->request('REPORT', $addressBookUrl, $body, [
'Content-Type' => 'application/xml'
]);
return $this->parseMultiStatus($response['body']);
}
protected function download(string $url, string $userName, string $sharedSecret, string $resourcePath): array {
$client = $this->getClient($url, $userName, $sharedSecret);
return $client->request('GET', $resourcePath);
}
private function buildSyncCollectionRequestBody(?string $syncToken): string {
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$root = $dom->createElementNS('DAV:', 'd:sync-collection');
$sync = $dom->createElement('d:sync-token', $syncToken);
$prop = $dom->createElement('d:prop');
$cont = $dom->createElement('d:getcontenttype');
$etag = $dom->createElement('d:getetag');
$prop->appendChild($cont);
$prop->appendChild($etag);
$root->appendChild($sync);
$root->appendChild($prop);
$dom->appendChild($root);
return $dom->saveXML();
}
/**
* @param string $body
* @return array
* @throws \Sabre\Xml\ParseException
*/
private function parseMultiStatus($body) {
$xml = new Service();
/** @var MultiStatus $multiStatus */
$multiStatus = $xml->expect('{DAV:}multistatus', $body);
$result = [];
foreach ($multiStatus->getResponses() as $response) {
$result[$response->getHref()] = $response->getResponseProperties();
}
return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
}
/**
* @param IUser $user
*/
public function updateUser(IUser $user): void {
$systemAddressBook = $this->getLocalSystemAddressBook();
$addressBookId = $systemAddressBook['id'];
$cardId = self::getCardUri($user);
if ($user->isEnabled()) {
$this->atomic(function () use ($addressBookId, $cardId, $user) {
$card = $this->backend->getCard($addressBookId, $cardId);
if ($card === false) {
$vCard = $this->converter->createCardFromUser($user);
if ($vCard !== null) {
$this->backend->createCard($addressBookId, $cardId, $vCard->serialize(), false);
}
} else {
$vCard = $this->converter->createCardFromUser($user);
if (is_null($vCard)) {
$this->backend->deleteCard($addressBookId, $cardId);
} else {
$this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
}
}
}, $this->dbConnection);
} else {
$this->backend->deleteCard($addressBookId, $cardId);
}
}
/**
* @param IUser|string $userOrCardId
*/
public function deleteUser($userOrCardId) {
$systemAddressBook = $this->getLocalSystemAddressBook();
if ($userOrCardId instanceof IUser) {
$userOrCardId = self::getCardUri($userOrCardId);
}
$this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
}
/**
* @return array|null
*/
public function getLocalSystemAddressBook() {
if (is_null($this->localSystemAddressBook)) {
$systemPrincipal = "principals/system/system";
$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
]);
}
return $this->localSystemAddressBook;
}
public function syncInstance(\Closure $progressCallback = null) {
$systemAddressBook = $this->getLocalSystemAddressBook();
$this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback) {
$this->updateUser($user);
if (!is_null($progressCallback)) {
$progressCallback();
}
});
// remove no longer existing
$allCards = $this->backend->getCards($systemAddressBook['id']);
foreach ($allCards as $card) {
$vCard = Reader::read($card['carddata']);
$uid = $vCard->UID->getValue();
// load backend and see if user exists
if (!$this->userManager->userExists($uid)) {
$this->deleteUser($card['uri']);
}
}
}
/**
* @param IUser $user
* @return string
*/
public static function getCardUri(IUser $user): string {
return $user->getBackendClassName() . ':' . $user->getUID() . '.vcf';
}
}
@@ -0,0 +1,374 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Anna Larch <anna.larch@gmx.net>
*
* @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/>.
*
*/
namespace OCA\DAV\CardDAV;
use OCA\DAV\Exception\UnsupportedLimitOnInitialSyncException;
use OCA\Federation\TrustedServers;
use OCP\Accounts\IAccountManager;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IRequest;
use OCP\IUserSession;
use Sabre\CardDAV\Backend\BackendInterface;
use Sabre\CardDAV\Backend\SyncSupport;
use Sabre\CardDAV\Card;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\VObject\Component\VCard;
use Sabre\VObject\Reader;
use function array_filter;
use function array_intersect;
use function array_unique;
use function in_array;
class SystemAddressbook extends AddressBook {
public const URI_SHARED = 'z-server-generated--system';
/** @var IConfig */
private $config;
private IUserSession $userSession;
private ?TrustedServers $trustedServers;
private ?IRequest $request;
private ?IGroupManager $groupManager;
public function __construct(BackendInterface $carddavBackend,
array $addressBookInfo,
IL10N $l10n,
IConfig $config,
IUserSession $userSession,
?IRequest $request = null,
?TrustedServers $trustedServers = null,
?IGroupManager $groupManager = null) {
parent::__construct($carddavBackend, $addressBookInfo, $l10n);
$this->config = $config;
$this->userSession = $userSession;
$this->request = $request;
$this->trustedServers = $trustedServers;
$this->groupManager = $groupManager;
$this->addressBookInfo['{DAV:}displayname'] = $l10n->t('Accounts');
$this->addressBookInfo['{' . Plugin::NS_CARDDAV . '}addressbook-description'] = $l10n->t('System address book which holds all accounts');
}
/**
* No checkbox checked -> Show only the same user
* 'Allow username autocompletion in share dialog' -> show everyone
* 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users within the same groups' -> show only users in intersecting groups
* 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users based on phone number integration' -> show only the same user
* 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users within the same groups' + 'Allow username autocompletion to users based on phone number integration' -> show only users in intersecting groups
*/
public function getChildren() {
$shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
$shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
$shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
$user = $this->userSession->getUser();
if (!$user) {
// Should never happen because we don't allow anonymous access
return [];
}
if ($user->getBackendClassName() === 'Guests' || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
$name = SyncService::getCardUri($user);
try {
return [parent::getChild($name)];
} catch (NotFound $e) {
return [];
}
}
if ($shareEnumerationGroup) {
if ($this->groupManager === null) {
// Group manager is not available, so we can't determine which data is safe
return [];
}
$groups = $this->groupManager->getUserGroups($user);
$names = [];
foreach ($groups as $group) {
$users = $group->getUsers();
foreach ($users as $groupUser) {
if ($groupUser->getBackendClassName() === 'Guests') {
continue;
}
$names[] = SyncService::getCardUri($groupUser);
}
}
return parent::getMultipleChildren(array_unique($names));
}
$children = parent::getChildren();
return array_filter($children, function (Card $child) {
// check only for URIs that begin with Guests:
return !str_starts_with($child->getName(), 'Guests:');
});
}
/**
* @param array $paths
* @return Card[]
* @throws NotFound
*/
public function getMultipleChildren($paths): array {
$shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
$shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
$shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
$user = $this->userSession->getUser();
if (($user !== null && $user->getBackendClassName() === 'Guests') || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
// No user or cards with no access
if ($user === null || !in_array(SyncService::getCardUri($user), $paths, true)) {
return [];
}
// Only return the own card
try {
return [parent::getChild(SyncService::getCardUri($user))];
} catch (NotFound $e) {
return [];
}
}
if ($shareEnumerationGroup) {
if ($this->groupManager === null || $user === null) {
// Group manager or user is not available, so we can't determine which data is safe
return [];
}
$groups = $this->groupManager->getUserGroups($user);
$allowedNames = [];
foreach ($groups as $group) {
$users = $group->getUsers();
foreach ($users as $groupUser) {
if ($groupUser->getBackendClassName() === 'Guests') {
continue;
}
$allowedNames[] = SyncService::getCardUri($groupUser);
}
}
return parent::getMultipleChildren(array_intersect($paths, $allowedNames));
}
if (!$this->isFederation()) {
return parent::getMultipleChildren($paths);
}
$objs = $this->carddavBackend->getMultipleCards($this->addressBookInfo['id'], $paths);
$children = [];
/** @var array $obj */
foreach ($objs as $obj) {
if (empty($obj)) {
continue;
}
$carddata = $this->extractCarddata($obj);
if (empty($carddata)) {
continue;
} else {
$obj['carddata'] = $carddata;
}
$children[] = new Card($this->carddavBackend, $this->addressBookInfo, $obj);
}
return $children;
}
/**
* @param string $name
* @return Card
* @throws NotFound
* @throws Forbidden
*/
public function getChild($name): Card {
$user = $this->userSession->getUser();
$shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
$shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
$shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
if (($user !== null && $user->getBackendClassName() === 'Guests') || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
$ownName = $user !== null ? SyncService::getCardUri($user) : null;
if ($ownName === $name) {
return parent::getChild($name);
}
throw new Forbidden();
}
if ($shareEnumerationGroup) {
if ($user === null || $this->groupManager === null) {
// Group manager is not available, so we can't determine which data is safe
throw new Forbidden();
}
$groups = $this->groupManager->getUserGroups($user);
foreach ($groups as $group) {
foreach ($group->getUsers() as $groupUser) {
if ($groupUser->getBackendClassName() === 'Guests') {
continue;
}
$otherName = SyncService::getCardUri($groupUser);
if ($otherName === $name) {
return parent::getChild($name);
}
}
}
throw new Forbidden();
}
if (!$this->isFederation()) {
return parent::getChild($name);
}
$obj = $this->carddavBackend->getCard($this->addressBookInfo['id'], $name);
if (!$obj) {
throw new NotFound('Card not found');
}
$carddata = $this->extractCarddata($obj);
if (empty($carddata)) {
throw new Forbidden();
} else {
$obj['carddata'] = $carddata;
}
return new Card($this->carddavBackend, $this->addressBookInfo, $obj);
}
/**
* @throws UnsupportedLimitOnInitialSyncException
*/
public function getChanges($syncToken, $syncLevel, $limit = null) {
if (!$syncToken && $limit) {
throw new UnsupportedLimitOnInitialSyncException();
}
if (!$this->carddavBackend instanceof SyncSupport) {
return null;
}
if (!$this->isFederation()) {
return parent::getChanges($syncToken, $syncLevel, $limit);
}
$changed = $this->carddavBackend->getChangesForAddressBook(
$this->addressBookInfo['id'],
$syncToken,
$syncLevel,
$limit
);
if (empty($changed)) {
return $changed;
}
$added = $modified = $deleted = [];
foreach ($changed['added'] as $uri) {
try {
$this->getChild($uri);
$added[] = $uri;
} catch (NotFound | Forbidden $e) {
$deleted[] = $uri;
}
}
foreach ($changed['modified'] as $uri) {
try {
$this->getChild($uri);
$modified[] = $uri;
} catch (NotFound | Forbidden $e) {
$deleted[] = $uri;
}
}
$changed['added'] = $added;
$changed['modified'] = $modified;
$changed['deleted'] = $deleted;
return $changed;
}
private function isFederation(): bool {
if ($this->trustedServers === null || $this->request === null) {
return false;
}
/** @psalm-suppress NoInterfaceProperties */
$server = $this->request->server;
if (!isset($server['PHP_AUTH_USER']) || $server['PHP_AUTH_USER'] !== 'system') {
return false;
}
/** @psalm-suppress NoInterfaceProperties */
$sharedSecret = $server['PHP_AUTH_PW'] ?? null;
if ($sharedSecret === null) {
return false;
}
$servers = $this->trustedServers->getServers();
$trusted = array_filter($servers, function ($trustedServer) use ($sharedSecret) {
return $trustedServer['shared_secret'] === $sharedSecret;
});
// Authentication is fine, but it's not for a federated share
if (empty($trusted)) {
return false;
}
return true;
}
/**
* If the validation doesn't work the card is "not found" so we
* return empty carddata even if the carddata might exist in the local backend.
* This can happen when a user sets the required properties
* FN, N to a local scope only but the request is from
* a federated share.
*
* @see https://github.com/nextcloud/server/issues/38042
*
* @param array $obj
* @return string|null
*/
private function extractCarddata(array $obj): ?string {
$obj['acl'] = $this->getChildACL();
$cardData = $obj['carddata'];
/** @var VCard $vCard */
$vCard = Reader::read($cardData);
foreach ($vCard->children() as $child) {
$scope = $child->offsetGet('X-NC-SCOPE');
if ($scope !== null && $scope->getValue() === IAccountManager::SCOPE_LOCAL) {
$vCard->remove($child);
}
}
$messages = $vCard->validate();
if (!empty($messages)) {
return null;
}
return $vCard->serialize();
}
/**
* @return mixed
* @throws Forbidden
*/
public function delete() {
if ($this->isFederation()) {
parent::delete();
}
throw new Forbidden();
}
public function getACL() {
return array_filter(parent::getACL(), function ($acl) {
if (in_array($acl['privilege'], ['{DAV:}write', '{DAV:}all'], true)) {
return false;
}
return true;
});
}
}
@@ -0,0 +1,170 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Anna Larch <anna.larch@gmx.net>
*
* @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\CardDAV;
use OCA\DAV\AppInfo\PluginManager;
use OCA\DAV\CardDAV\Integration\ExternalAddressBook;
use OCA\DAV\CardDAV\Integration\IAddressBookProvider;
use OCA\Federation\TrustedServers;
use OCP\AppFramework\QueryException;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IRequest;
use OCP\IUser;
use OCP\IUserSession;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Sabre\CardDAV\Backend;
use Sabre\CardDAV\IAddressBook;
use Sabre\DAV\Exception\MethodNotAllowed;
use Sabre\DAV\MkCol;
use function array_map;
class UserAddressBooks extends \Sabre\CardDAV\AddressBookHome {
/** @var IL10N */
protected $l10n;
/** @var IConfig */
protected $config;
/** @var PluginManager */
private $pluginManager;
private ?IUser $user;
private ?IGroupManager $groupManager;
public function __construct(Backend\BackendInterface $carddavBackend,
string $principalUri,
PluginManager $pluginManager,
?IUser $user,
?IGroupManager $groupManager) {
parent::__construct($carddavBackend, $principalUri);
$this->pluginManager = $pluginManager;
$this->user = $user;
$this->groupManager = $groupManager;
}
/**
* Returns a list of address books
*
* @return IAddressBook[]
*/
public function getChildren() {
if ($this->l10n === null) {
$this->l10n = \OC::$server->getL10N('dav');
}
if ($this->config === null) {
$this->config = \OC::$server->getConfig();
}
/** @var string|array $principal */
$principal = $this->principalUri;
$addressBooks = $this->carddavBackend->getAddressBooksForUser($this->principalUri);
// add the system address book
$systemAddressBook = null;
$systemAddressBookExposed = $this->config->getAppValue('dav', 'system_addressbook_exposed', 'yes') === 'yes';
if ($systemAddressBookExposed && is_string($principal) && $principal !== 'principals/system/system' && $this->carddavBackend instanceof CardDavBackend) {
$systemAddressBook = $this->carddavBackend->getAddressBooksByUri('principals/system/system', 'system');
if ($systemAddressBook !== null) {
$systemAddressBook['uri'] = SystemAddressbook::URI_SHARED;
}
}
if (!is_null($systemAddressBook)) {
$addressBooks[] = $systemAddressBook;
}
$objects = [];
if (!empty($addressBooks)) {
/** @var IAddressBook[] $objects */
$objects = array_map(function (array $addressBook) {
$trustedServers = null;
$request = null;
try {
$trustedServers = \OC::$server->get(TrustedServers::class);
$request = \OC::$server->get(IRequest::class);
} catch (QueryException | NotFoundExceptionInterface | ContainerExceptionInterface $e) {
// nothing to do, the request / trusted servers don't exist
}
if ($addressBook['principaluri'] === 'principals/system/system') {
return new SystemAddressbook(
$this->carddavBackend,
$addressBook,
$this->l10n,
$this->config,
\OCP\Server::get(IUserSession::class),
$request,
$trustedServers,
$this->groupManager
);
}
return new AddressBook($this->carddavBackend, $addressBook, $this->l10n);
}, $addressBooks);
}
/** @var IAddressBook[][] $objectsFromPlugins */
$objectsFromPlugins = array_map(function (IAddressBookProvider $plugin): array {
return $plugin->fetchAllForAddressBookHome($this->principalUri);
}, $this->pluginManager->getAddressBookPlugins());
return array_merge($objects, ...$objectsFromPlugins);
}
public function createExtendedCollection($name, MkCol $mkCol) {
if (ExternalAddressBook::doesViolateReservedName($name)) {
throw new MethodNotAllowed('The resource you tried to create has a reserved name');
}
parent::createExtendedCollection($name, $mkCol);
}
/**
* Returns a list of ACE's for this node.
*
* Each ACE has the following properties:
* * 'privilege', a string such as {DAV:}read or {DAV:}write. These are
* currently the only supported privileges
* * 'principal', a url to the principal who owns the node
* * 'protected' (optional), indicating that this ACE is not allowed to
* be updated.
*
* @return array
*/
public function getACL() {
$acl = parent::getACL();
if ($this->principalUri === 'principals/system/system') {
$acl[] = [
'privilege' => '{DAV:}read',
'principal' => '{DAV:}authenticated',
'protected' => true,
];
}
return $acl;
}
}
@@ -0,0 +1,47 @@
<?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\CardDAV\Xml;
use Sabre\Xml\Writer;
use Sabre\Xml\XmlSerializable;
class Groups implements XmlSerializable {
public const NS_OWNCLOUD = 'http://owncloud.org/ns';
/** @var string[] of TYPE:CHECKSUM */
private $groups;
/**
* @param string $groups
*/
public function __construct($groups) {
$this->groups = $groups;
}
public function xmlSerialize(Writer $writer) {
foreach ($this->groups as $group) {
$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
}
}
}