diff options
Diffstat (limited to 'apps/dav/lib')
-rw-r--r-- | apps/dav/lib/CalDAV/CalDavBackend.php | 17 | ||||
-rw-r--r-- | apps/dav/lib/CardDAV/AddressBookImpl.php | 9 | ||||
-rw-r--r-- | apps/dav/lib/CardDAV/PhotoCache.php | 64 | ||||
-rw-r--r-- | apps/dav/lib/Command/ListCalendars.php | 108 | ||||
-rw-r--r-- | apps/dav/lib/Command/MoveCalendar.php | 185 | ||||
-rw-r--r-- | apps/dav/lib/Connector/Sabre/File.php | 17 | ||||
-rw-r--r-- | apps/dav/lib/Migration/RemoveClassifiedEventActivity.php | 2 | ||||
-rw-r--r-- | apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php | 94 | ||||
-rw-r--r-- | apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php | 91 | ||||
-rw-r--r-- | apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php | 267 | ||||
-rw-r--r-- | apps/dav/lib/RootCollection.php | 10 | ||||
-rw-r--r-- | apps/dav/lib/Server.php | 12 |
12 files changed, 840 insertions, 36 deletions
diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 187ba4ecdcf..88ee778e82c 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -2522,6 +2522,23 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription } /** + * Move a calendar from one user to another + * + * @param string $uriName + * @param string $uriOrigin + * @param string $uriDestination + */ + public function moveCalendar($uriName, $uriOrigin, $uriDestination) + { + $query = $this->db->getQueryBuilder(); + $query->update('calendars') + ->set('principaluri', $query->createNamedParameter($uriDestination)) + ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin))) + ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName))) + ->execute(); + } + + /** * read VCalendar data into a VCalendar object * * @param string $objectData diff --git a/apps/dav/lib/CardDAV/AddressBookImpl.php b/apps/dav/lib/CardDAV/AddressBookImpl.php index 1aedd5d5643..ae727b8544f 100644 --- a/apps/dav/lib/CardDAV/AddressBookImpl.php +++ b/apps/dav/lib/CardDAV/AddressBookImpl.php @@ -76,6 +76,15 @@ class AddressBookImpl implements IAddressBook { } /** + * @return string defining the unique uri + * @since 16.0.0 + * @return string + */ + public function getUri(): string { + return $this->addressBookInfo['uri']; + } + + /** * In comparison to getKey() this function returns a human readable (maybe translated) name * * @return mixed diff --git a/apps/dav/lib/CardDAV/PhotoCache.php b/apps/dav/lib/CardDAV/PhotoCache.php index fa244857e39..eed11f1e939 100644 --- a/apps/dav/lib/CardDAV/PhotoCache.php +++ b/apps/dav/lib/CardDAV/PhotoCache.php @@ -35,6 +35,14 @@ use Sabre\VObject\Reader; class PhotoCache { + /** @var array */ + protected const ALLOWED_CONTENT_TYPES = [ + 'image/png' => 'png', + 'image/jpeg' => 'jpg', + 'image/gif' => 'gif', + 'image/vnd.microsoft.icon' => 'ico', + ]; + /** @var IAppData */ protected $appData; @@ -90,27 +98,26 @@ class PhotoCache { /** * @param ISimpleFolder $folder * @param Card $card + * @throws NotPermittedException */ - private function init(ISimpleFolder $folder, Card $card) { + private function init(ISimpleFolder $folder, Card $card): void { $data = $this->getPhoto($card); - if ($data === false) { + if ($data === false || !isset($data['Content-Type'])) { $folder->newFile('nophoto'); - } else { - switch ($data['Content-Type']) { - case 'image/png': - $ext = 'png'; - break; - case 'image/jpeg': - $ext = 'jpg'; - break; - case 'image/gif': - $ext = 'gif'; - break; - } - $file = $folder->newFile('photo.' . $ext); - $file->putContent($data['body']); + 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) { @@ -147,7 +154,7 @@ class PhotoCache { if ($size !== -1) { $photo->resize($size); } - + try { $file = $folder->newFile($path); $file->putContent($photo->data()); @@ -180,15 +187,14 @@ class PhotoCache { * @return string * @throws NotFoundException */ - private function getExtension(ISimpleFolder $folder) { - if ($folder->fileExists('photo.jpg')) { - return 'jpg'; - } elseif ($folder->fileExists('photo.png')) { - return 'png'; - } elseif ($folder->fileExists('photo.gif')) { - return 'gif'; + private function getExtension(ISimpleFolder $folder): string { + foreach (self::ALLOWED_CONTENT_TYPES as $extension) { + if ($folder->fileExists('photo.' . $extension)) { + return $extension; + } } - throw new NotFoundException; + + throw new NotFoundException('Avatar not found'); } private function getPhoto(Card $node) { @@ -218,13 +224,7 @@ class PhotoCache { $type = $this->getBinaryType($photo); } - $allowedContentTypes = [ - 'image/png', - 'image/jpeg', - 'image/gif', - ]; - - if (!in_array($type, $allowedContentTypes, true)) { + if (empty($type) || !isset(self::ALLOWED_CONTENT_TYPES[$type])) { $type = 'application/octet-stream'; } diff --git a/apps/dav/lib/Command/ListCalendars.php b/apps/dav/lib/Command/ListCalendars.php new file mode 100644 index 00000000000..6c2f5bdb506 --- /dev/null +++ b/apps/dav/lib/Command/ListCalendars.php @@ -0,0 +1,108 @@ +<?php +/** + * @copyright Copyright (c) 2018, Georg Ehrke + * + * @author Georg Ehrke <oc.list@georgehrke.com> + * @author Thomas Citharel <tcit@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\Command; + +use OCA\DAV\CalDAV\BirthdayService; +use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\Connector\Sabre\Principal; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Share\IManager; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Helper\Table; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class ListCalendars extends Command { + + /** @var IUserManager */ + protected $userManager; + + /** @var CalDavBackend */ + private $caldav; + + /** + * @param IUserManager $userManager + * @param CalDavBackend $caldav + */ + function __construct(IUserManager $userManager, CalDavBackend $caldav) { + parent::__construct(); + $this->userManager = $userManager; + $this->caldav = $caldav; + } + + protected function configure() { + $this + ->setName('dav:list-calendars') + ->setDescription('List all calendars of a user') + ->addArgument('uid', + InputArgument::REQUIRED, + 'User for whom all calendars will be listed'); + } + + protected function execute(InputInterface $input, OutputInterface $output) { + $user = $input->getArgument('uid'); + if (!$this->userManager->userExists($user)) { + throw new \InvalidArgumentException("User <$user> is unknown."); + } + + $calendars = $this->caldav->getCalendarsForUser("principals/users/$user"); + + $calendarTableData = []; + foreach($calendars as $calendar) { + // skip birthday calendar + if ($calendar['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI) { + continue; + } + + $readOnly = false; + $readOnlyIndex = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only'; + if (isset($calendar[$readOnlyIndex])) { + $readOnly = $calendar[$readOnlyIndex]; + } + + $calendarTableData[] = [ + $calendar['uri'], + $calendar['{DAV:}displayname'], + $calendar['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal'], + $calendar['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname'], + $readOnly ? ' x ' : ' ✓ ', + ]; + } + + if (count($calendarTableData) > 0) { + $table = new Table($output); + $table->setHeaders(['uri', 'displayname', 'owner\'s userid', 'owner\'s displayname', 'writable']) + ->setRows($calendarTableData); + + $table->render(); + } else { + $output->writeln("<info>User <$user> has no calendars</info>"); + } + } + +} diff --git a/apps/dav/lib/Command/MoveCalendar.php b/apps/dav/lib/Command/MoveCalendar.php new file mode 100644 index 00000000000..a2c7ca8c4d8 --- /dev/null +++ b/apps/dav/lib/Command/MoveCalendar.php @@ -0,0 +1,185 @@ +<?php +/** + * @author Thomas Citharel <tcit@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\Command; + +use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\CalDAV\Calendar; +use OCA\DAV\Connector\Sabre\Principal; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IL10N; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Share\IManager as IShareManager; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; + +class MoveCalendar extends Command { + + /** @var IUserManager */ + private $userManager; + + /** @var IGroupManager */ + private $groupManager; + + /** @var IShareManager */ + private $shareManager; + + /** @var IConfig $config */ + private $config; + + /** @var IL10N */ + private $l10n; + + /** @var SymfonyStyle */ + private $io; + + /** @var CalDavBackend */ + private $calDav; + + const URI_USERS = 'principals/users/'; + + /** + * @param IUserManager $userManager + * @param IGroupManager $groupManager + * @param IShareManager $shareManager + * @param IConfig $config + * @param IL10N $l10n + * @param CalDavBackend $calDav + */ + function __construct( + IUserManager $userManager, + IGroupManager $groupManager, + IShareManager $shareManager, + IConfig $config, + IL10N $l10n, + CalDavBackend $calDav + ) { + parent::__construct(); + $this->userManager = $userManager; + $this->groupManager = $groupManager; + $this->shareManager = $shareManager; + $this->config = $config; + $this->l10n = $l10n; + $this->calDav = $calDav; + } + + protected function configure() { + $this + ->setName('dav:move-calendar') + ->setDescription('Move a calendar from an user to another') + ->addArgument('name', + InputArgument::REQUIRED, + 'Name of the calendar to move') + ->addArgument('sourceuid', + InputArgument::REQUIRED, + 'User who currently owns the calendar') + ->addArgument('destinationuid', + InputArgument::REQUIRED, + 'User who will receive the calendar') + ->addOption('force', 'f', InputOption::VALUE_NONE, "Force the migration by removing existing shares"); + } + + protected function execute(InputInterface $input, OutputInterface $output) { + $userOrigin = $input->getArgument('sourceuid'); + $userDestination = $input->getArgument('destinationuid'); + + $this->io = new SymfonyStyle($input, $output); + + if (!$this->userManager->userExists($userOrigin)) { + throw new \InvalidArgumentException("User <$userOrigin> is unknown."); + } + + if (!$this->userManager->userExists($userDestination)) { + throw new \InvalidArgumentException("User <$userDestination> is unknown."); + } + + $name = $input->getArgument('name'); + + $calendar = $this->calDav->getCalendarByUri(self::URI_USERS . $userOrigin, $name); + + if (null === $calendar) { + throw new \InvalidArgumentException("User <$userOrigin> has no calendar named <$name>. You can run occ dav:list-calendars to list calendars URIs for this user."); + } + + if (null !== $this->calDav->getCalendarByUri(self::URI_USERS . $userDestination, $name)) { + throw new \InvalidArgumentException("User <$userDestination> already has a calendar named <$name>."); + } + + $this->checkShares($calendar, $userOrigin, $userDestination, $input->getOption('force')); + + $this->calDav->moveCalendar($name, self::URI_USERS . $userOrigin, self::URI_USERS . $userDestination); + + $this->io->success("Calendar <$name> was moved from user <$userOrigin> to <$userDestination>"); + } + + /** + * Check that moving the calendar won't break shares + * + * @param array $calendar + * @param string $userOrigin + * @param string $userDestination + * @param bool $force + */ + private function checkShares(array $calendar, string $userOrigin, string $userDestination, bool $force = false) + { + $shares = $this->calDav->getShares($calendar['id']); + foreach ($shares as $share) { + list(, $prefix, $userOrGroup) = explode('/', $share['href'], 3); + + /** + * Check that user destination is member of the groups which whom the calendar was shared + * If we ask to force the migration, the share with the group is dropped + */ + if ($this->shareManager->shareWithGroupMembersOnly() === true && 'groups' === $prefix && !$this->groupManager->isInGroup($userDestination, $userOrGroup)) { + if ($force) { + $this->calDav->updateShares(new Calendar($this->calDav, $calendar, $this->l10n, $this->config), [], ['href' => 'principal:principals/groups/' . $userOrGroup]); + } else { + throw new \InvalidArgumentException("User <$userDestination> is not part of the group <$userOrGroup> with whom the calendar <" . $calendar['uri'] . "> was shared. You may use -f to move the calendar while deleting this share."); + } + } + + /** + * Check that calendar isn't already shared with user destination + */ + if ($userOrGroup === $userDestination) { + if ($force) { + $this->calDav->updateShares(new Calendar($this->calDav, $calendar, $this->l10n, $this->config), [], ['href' => 'principal:principals/users/' . $userOrGroup]); + } else { + throw new \InvalidArgumentException("The calendar <" . $calendar['uri'] . "> is already shared to user <$userDestination>.You may use -f to move the calendar while deleting this share."); + } + } + } + /** + * Warn that share links have changed if there are shares + */ + if (count($shares) > 0) { + $this->io->note([ + "Please note that moving calendar " . $calendar['uri'] . " from user <$userOrigin> to <$userDestination> has caused share links to change.", + "Sharees will need to change \"example.com/remote.php/dav/calendars/uid/" . $calendar['uri'] . "_shared_by_$userOrigin\" to \"example.com/remote.php/dav/calendars/uid/" . $calendar['uri'] . "_shared_by_$userDestination\"" + ]); + } + } +} diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index f948f0f552d..388bcff9206 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -36,6 +36,7 @@ namespace OCA\DAV\Connector\Sabre; +use Icewind\Streams\CallbackWrapper; use OC\AppFramework\Http\Request; use OC\Files\Filesystem; use OC\Files\View; @@ -166,10 +167,22 @@ class File extends Node implements IFile { } if ($partStorage->instanceOfStorage(Storage\IWriteStreamStorage::class)) { - $count = $partStorage->writeStream($internalPartPath, $data); + + if (!is_resource($data)) { + $data = fopen('php://temp', 'r+'); + fwrite($data, 'foobar'); + rewind($data); + } + + $isEOF = false; + $wrappedData = CallbackWrapper::wrap($data, null, null, null, null, function($stream) use (&$isEOF) { + $isEOF = feof($stream); + }); + + $count = $partStorage->writeStream($internalPartPath, $wrappedData); $result = $count > 0; if ($result === false) { - $result = feof($data); + $result = $isEOF; } } else { diff --git a/apps/dav/lib/Migration/RemoveClassifiedEventActivity.php b/apps/dav/lib/Migration/RemoveClassifiedEventActivity.php index ad840d8100e..1829f57237a 100644 --- a/apps/dav/lib/Migration/RemoveClassifiedEventActivity.php +++ b/apps/dav/lib/Migration/RemoveClassifiedEventActivity.php @@ -127,6 +127,6 @@ class RemoveClassifiedEventActivity implements IRepairStep { protected function getPrincipal(string $principalUri): string { $uri = explode('/', $principalUri); - return $uri[2]; + return array_pop($uri); } } diff --git a/apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php b/apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php new file mode 100644 index 00000000000..17643587904 --- /dev/null +++ b/apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php @@ -0,0 +1,94 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2019 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\Migration; + +use OCA\DAV\CalDAV\CalDavBackend; +use OCP\DB\QueryBuilder\IQueryBuilder; +use OCP\IDBConnection; +use OCP\Migration\IOutput; +use OCP\Migration\IRepairStep; + +class RemoveOrphanEventsAndContacts implements IRepairStep { + + /** @var IDBConnection */ + private $connection; + + public function __construct(IDBConnection $connection) { + $this->connection = $connection; + } + + /** + * @inheritdoc + */ + public function getName(): string { + return 'Clean up orphan event and contact data'; + } + + /** + * @inheritdoc + */ + public function run(IOutput $output) { + $orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendars', 'calendarid'); + $output->info(sprintf('%d events without a calendar have been cleaned up', $orphanItems)); + $orphanItems = $this->removeOrphanChildren('calendarobjects_props', 'calendarobjects', 'objectid'); + $output->info(sprintf('%d properties without an events have been cleaned up', $orphanItems)); + $orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendars', 'calendarid'); + $output->info(sprintf('%d changes without a calendar have been cleaned up', $orphanItems)); + + $orphanItems = $this->removeOrphanChildren('cards', 'addressbooks', 'addressbookid'); + $output->info(sprintf('%d contacts without an addressbook have been cleaned up', $orphanItems)); + $orphanItems = $this->removeOrphanChildren('cards_properties', 'cards', 'cardid'); + $output->info(sprintf('%d properties without a contact have been cleaned up', $orphanItems)); + $orphanItems = $this->removeOrphanChildren('addressbookchanges', 'addressbooks', 'addressbookid'); + $output->info(sprintf('%d changes without an addressbook have been cleaned up', $orphanItems)); + } + + protected function removeOrphanChildren($childTable, $parentTable, $parentId): int { + $qb = $this->connection->getQueryBuilder(); + + $qb->select('c.id') + ->from($childTable, 'c') + ->leftJoin('c', $parentTable, 'p', $qb->expr()->eq('c.' . $parentId, 'p.id')) + ->where($qb->expr()->isNull('p.id')); + $result = $qb->execute(); + + $orphanItems = array(); + while ($row = $result->fetch()) { + $orphanItems[] = (int) $row['id']; + } + $result->closeCursor(); + + if (!empty($orphanItems)) { + $qb->delete($childTable) + ->where($qb->expr()->in('id', $qb->createParameter('ids'))); + + $orphanItemsBatch = array_chunk($orphanItems, 200); + foreach ($orphanItemsBatch as $items) { + $qb->setParameter('ids', $items, IQueryBuilder::PARAM_INT_ARRAY); + $qb->execute(); + } + } + + return count($orphanItems); + } +} diff --git a/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php b/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php new file mode 100644 index 00000000000..adc28c83429 --- /dev/null +++ b/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php @@ -0,0 +1,91 @@ +<?php +/** + * @copyright 2018, Georg Ehrke <oc.list@georgehrke.com> + * + * @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\Provisioning\Apple; + +use OCP\AppFramework\Utility\ITimeFactory; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\INode; +use Sabre\DAV\IProperties; +use Sabre\DAV\PropPatch; + +class AppleProvisioningNode implements INode, IProperties { + + const FILENAME = 'apple-provisioning.mobileconfig'; + + protected $timeFactory; + + /** + * @param ITimeFactory $timeFactory + */ + public function __construct(ITimeFactory $timeFactory) { + $this->timeFactory = $timeFactory; + } + + /** + * @return string + */ + public function getName() { + return self::FILENAME; + } + + + public function setName($name) { + throw new Forbidden('Renaming ' . self::FILENAME . ' is forbidden'); + } + + /** + * @return null + */ + public function getLastModified() { + return null; + } + + /** + * @throws Forbidden + */ + public function delete() { + throw new Forbidden(self::FILENAME . ' may not be deleted.'); + } + + /** + * @param array $properties + * @return array + */ + public function getProperties($properties) { + $datetime = $this->timeFactory->getDateTime(); + + return [ + '{DAV:}getcontentlength' => 42, + '{DAV:}getlastmodified' => $datetime->format(\DateTime::RFC2822), + ]; + } + + /** + * @param PropPatch $propPatch + * @throws Forbidden + */ + public function propPatch(PropPatch $propPatch) { + throw new Forbidden(self::FILENAME . '\'s properties may not be altered.'); + } +} diff --git a/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php b/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php new file mode 100644 index 00000000000..55c352d98ba --- /dev/null +++ b/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php @@ -0,0 +1,267 @@ +<?php +/** + * @copyright 2018, Georg Ehrke <oc.list@georgehrke.com> + * + * @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\Provisioning\Apple; + +use OCP\IL10N; +use OCP\IRequest; +use OCP\IURLGenerator; +use OCP\IUserSession; +use Sabre\DAV\Server; +use Sabre\DAV\ServerPlugin; +use Sabre\HTTP\RequestInterface; +use Sabre\HTTP\ResponseInterface; + +class AppleProvisioningPlugin extends ServerPlugin { + + /** + * @var Server + */ + protected $server; + + /** + * @var IURLGenerator + */ + protected $urlGenerator; + + /** + * @var IUserSession + */ + protected $userSession; + + /** + * @var \OC_Defaults + */ + protected $themingDefaults; + + /** + * @var IRequest + */ + protected $request; + + /** + * @var IL10N + */ + protected $l10n; + + /** + * @var \closure + */ + protected $uuidClosure; + + /** + * AppleProvisioningPlugin constructor. + * + * @param IUserSession $userSession + * @param IURLGenerator $urlGenerator + * @param \OC_Defaults $themingDefaults + * @param IRequest $request + * @param IL10N $l10n + * @param \closure $uuidClosure + */ + public function __construct(IUserSession $userSession, IURLGenerator $urlGenerator, + \OC_Defaults $themingDefaults, IRequest $request, + IL10N $l10n, \closure $uuidClosure) { + $this->userSession = $userSession; + $this->urlGenerator = $urlGenerator; + $this->themingDefaults = $themingDefaults; + $this->request = $request; + $this->l10n = $l10n; + $this->uuidClosure = $uuidClosure; + } + + /** + * @param Server $server + */ + public function initialize(Server $server) { + $this->server = $server; + $this->server->on('method:GET', [$this, 'httpGet'], 90); + } + + /** + * @param RequestInterface $request + * @param ResponseInterface $response + * @return boolean + */ + public function httpGet(RequestInterface $request, ResponseInterface $response):bool { + if ($request->getPath() !== 'provisioning/' . AppleProvisioningNode::FILENAME) { + return true; + } + + $user = $this->userSession->getUser(); + if (!$user) { + return true; + } + + $serverProtocol = $this->request->getServerProtocol(); + $useSSL = ($serverProtocol === 'https'); + + if (!$useSSL) { + $response->setStatus(200); + $response->setHeader('Content-Type', 'text/plain; charset=utf-8'); + $response->setBody($this->l10n->t('Your %s needs to be configured to use HTTPS in order to use CalDAV and CardDAV with iOS/macOS.', [$this->themingDefaults->getName()])); + + return false; + } + + $absoluteURL = $request->getAbsoluteUrl(); + $parsedUrl = parse_url($absoluteURL); + if (isset($parsedUrl['port'])) { + $serverPort = (int) $parsedUrl['port']; + } else { + $serverPort = 443; + } + $server_url = $parsedUrl['host']; + + $description = $this->themingDefaults->getName(); + $userId = $user->getUID(); + + $reverseDomain = implode('.', array_reverse(explode('.', $parsedUrl['host']))); + + $caldavUUID = call_user_func($this->uuidClosure); + $carddavUUID = call_user_func($this->uuidClosure); + $profileUUID = call_user_func($this->uuidClosure); + + $caldavIdentifier = $reverseDomain . '.' . $caldavUUID; + $carddavIdentifier = $reverseDomain . '.' . $carddavUUID; + $profileIdentifier = $reverseDomain . '.' . $profileUUID; + + $caldavDescription = $this->l10n->t('Configures a CalDAV account'); + $caldavDisplayname = $description . ' CalDAV'; + $carddavDescription = $this->l10n->t('Configures a CardDAV account'); + $carddavDisplayname = $description . ' CardDAV'; + + $filename = $userId . '-' . AppleProvisioningNode::FILENAME; + + $xmlSkeleton = $this->getTemplate(); + $body = vsprintf($xmlSkeleton, array_map(function($v) { + return \htmlspecialchars($v, ENT_XML1, 'UTF-8'); + }, [ + $description, + $server_url, + $userId, + $serverPort, + $caldavDescription, + $caldavDisplayname, + $caldavIdentifier, + $caldavUUID, + $description, + $server_url, + $userId, + $serverPort, + $carddavDescription, + $carddavDisplayname, + $carddavIdentifier, + $carddavUUID, + $description, + $profileIdentifier, + $profileUUID + ] + )); + + $response->setStatus(200); + $response->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"'); + $response->setHeader('Content-Type', 'application/xml; charset=utf-8'); + $response->setBody($body); + + return false; + } + + /** + * @return string + */ + private function getTemplate():string { + return <<<EOF +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>PayloadContent</key> + <array> + <dict> + <key>CalDAVAccountDescription</key> + <string>%s</string> + <key>CalDAVHostName</key> + <string>%s</string> + <key>CalDAVUsername</key> + <string>%s</string> + <key>CalDAVUseSSL</key> + <true/> + <key>CalDAVPort</key> + <integer>%s</integer> + <key>PayloadDescription</key> + <string>%s</string> + <key>PayloadDisplayName</key> + <string>%s</string> + <key>PayloadIdentifier</key> + <string>%s</string> + <key>PayloadType</key> + <string>com.apple.caldav.account</string> + <key>PayloadUUID</key> + <string>%s</string> + <key>PayloadVersion</key> + <integer>1</integer> + </dict> + <dict> + <key>CardDAVAccountDescription</key> + <string>%s</string> + <key>CardDAVHostName</key> + <string>%s</string> + <key>CardDAVUsername</key> + <string>%s</string> + <key>CardDAVUseSSL</key> + <true/> + <key>CardDAVPort</key> + <integer>%s</integer> + <key>PayloadDescription</key> + <string>%s</string> + <key>PayloadDisplayName</key> + <string>%s</string> + <key>PayloadIdentifier</key> + <string>%s</string> + <key>PayloadType</key> + <string>com.apple.carddav.account</string> + <key>PayloadUUID</key> + <string>%s</string> + <key>PayloadVersion</key> + <integer>1</integer> + </dict> + </array> + <key>PayloadDisplayName</key> + <string>%s</string> + <key>PayloadIdentifier</key> + <string>%s</string> + <key>PayloadRemovalDisallowed</key> + <false/> + <key>PayloadType</key> + <string>Configuration</string> + <key>PayloadUUID</key> + <string>%s</string> + <key>PayloadVersion</key> + <integer>1</integer> +</dict> +</plist> + +EOF; + } +} diff --git a/apps/dav/lib/RootCollection.php b/apps/dav/lib/RootCollection.php index adf9d7b99c7..9ad1ea5221e 100644 --- a/apps/dav/lib/RootCollection.php +++ b/apps/dav/lib/RootCollection.php @@ -35,7 +35,9 @@ use OCA\DAV\Connector\Sabre\Principal; use OCA\DAV\DAV\GroupPrincipalBackend; use OCA\DAV\DAV\SystemPrincipalBackend; use OCA\DAV\CalDAV\Principal\Collection; +use OCA\DAV\Provisioning\Apple\AppleProvisioningNode; use OCA\DAV\Upload\CleanupService; +use OCP\AppFramework\Utility\ITimeFactory; use Sabre\DAV\SimpleCollection; class RootCollection extends SimpleCollection { @@ -130,6 +132,9 @@ class RootCollection extends SimpleCollection { $avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users'); $avatarCollection->disableListing = $disableListing; + $appleProvisioning = new AppleProvisioningNode( + \OC::$server->query(ITimeFactory::class)); + $children = [ new SimpleCollection('principals', [ $userPrincipals, @@ -151,7 +156,10 @@ class RootCollection extends SimpleCollection { $systemTagRelationsCollection, $commentsCollection, $uploadCollection, - $avatarCollection + $avatarCollection, + new SimpleCollection('provisioning', [ + $appleProvisioning + ]) ]; parent::__construct('root', $children); diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index c2c903fa198..5335db98fce 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -55,6 +55,7 @@ use OCA\DAV\Connector\Sabre\QuotaPlugin; use OCA\DAV\Files\BrowserErrorPagePlugin; use OCA\DAV\Connector\Sabre\AnonymousOptionsPlugin; use OCA\DAV\Files\LazySearchBackend; +use OCA\DAV\Provisioning\Apple\AppleProvisioningPlugin; use OCA\DAV\SystemTag\SystemTagPlugin; use OCA\DAV\Upload\ChunkingPlugin; use OCP\IRequest; @@ -62,6 +63,7 @@ use OCP\SabrePluginEvent; use Sabre\CardDAV\VCFExportPlugin; use Sabre\DAV\Auth\Plugin; use OCA\DAV\Connector\Sabre\TagsPlugin; +use Sabre\DAV\UUIDUtil; use SearchDAV\DAV\SearchPlugin; use OCA\DAV\AppInfo\PluginManager; @@ -281,6 +283,16 @@ class Server { \OC::$server->getConfig(), \OC::$server->query(BirthdayService::class) )); + $this->server->addPlugin(new AppleProvisioningPlugin( + \OC::$server->getUserSession(), + \OC::$server->getURLGenerator(), + \OC::$server->getThemingDefaults(), + \OC::$server->getRequest(), + \OC::$server->getL10N('dav'), + function() { + return UUIDUtil::getUUID(); + } + )); } // register plugins from apps |