/** * return a user specific instance of \OCP\IAvatar * @see \OCP\IAvatar * @param string $user the ownCloud user id * @return \OCP\IAvatar * @throws \Exception In case the username is potentially dangerous */ public function getAvatar($user) { if (!$this->userManager->userExists($user)) { throw new \Exception('user does not exist'); } return new Avatar($this->rootFolder->getUserFolder($user)->getParent(), $this->l); }
/** * return a user specific instance of \OCP\IAvatar * @see \OCP\IAvatar * @param string $user the ownCloud user id * @return \OCP\IAvatar * @throws \Exception In case the username is potentially dangerous */ public function getAvatar($userId) { $user = $this->userManager->get($userId); if (is_null($user)) { throw new \Exception('user does not exist'); } return new Avatar($this->rootFolder->getUserFolder($userId)->getParent(), $this->l, $user); }
/** * initializes the collection. At this point of time, we need the logged in * user. Since it is not the case when the instance is created, we cannot * have this in the constructor. * * @throws NotAuthenticated */ protected function initCollections() { if (!empty($this->entityTypeCollections)) { return; } $user = $this->userSession->getUser(); if (is_null($user)) { throw new NotAuthenticated(); } $userFolder = $this->rootFolder->getUserFolder($user->getUID()); $this->entityTypeCollections['files'] = new EntityTypeCollection('files', $this->commentsManager, $userFolder, $this->userManager, $this->logger); }
/** * @param IOutput $output */ private function removeRootShares(IOutput $output) { $function = function (IUser $user) use($output) { $userFolder = $this->rootFolder->getUserFolder($user->getUID()); $fileId = $userFolder->getId(); $qb = $this->connection->getQueryBuilder(); $qb->delete('share')->where($qb->expr()->eq('file_source', $qb->createNamedParameter($fileId)))->andWhere($qb->expr()->orX($qb->expr()->eq('item_type', $qb->expr()->literal('file')), $qb->expr()->eq('item_type', $qb->expr()->literal('folder')))); $qb->execute(); $output->advance(); }; $userCount = $this->countUsers(); $output->startProgress($userCount); $this->userManager->callForAllUsers($function); $output->finishProgress(); }
/** * @param MapperEvent $event */ public function mapperEvent(MapperEvent $event) { $tagIds = $event->getTags(); if ($event->getObjectType() !== 'files' || empty($tagIds) || !in_array($event->getEvent(), [MapperEvent::EVENT_ASSIGN, MapperEvent::EVENT_UNASSIGN]) || !$this->appManager->isInstalled('activity')) { // System tags not for files, no tags, not (un-)assigning or no activity-app enabled (save the energy) return; } try { $tags = $this->tagManager->getTagsByIds($tagIds); } catch (TagNotFoundException $e) { // User assigned/unassigned a non-existing tag, ignore... return; } if (empty($tags)) { return; } // Get all mount point owners $cache = $this->mountCollection->getMountCache(); $mounts = $cache->getMountsForFileId($event->getObjectId()); if (empty($mounts)) { return; } $users = []; foreach ($mounts as $mount) { $owner = $mount->getUser()->getUID(); $ownerFolder = $this->rootFolder->getUserFolder($owner); $nodes = $ownerFolder->getById($event->getObjectId()); if (!empty($nodes)) { /** @var Node $node */ $node = array_shift($nodes); $path = $node->getPath(); if (strpos($path, '/' . $owner . '/files/') === 0) { $path = substr($path, strlen('/' . $owner . '/files')); } // Get all users that have access to the mount point $users = array_merge($users, Share::getUsersSharingFile($path, $owner, true, true)); } } $actor = $this->session->getUser(); if ($actor instanceof IUser) { $actor = $actor->getUID(); } else { $actor = ''; } $activity = $this->activityManager->generateEvent(); $activity->setApp(Extension::APP_NAME)->setType(Extension::APP_NAME)->setAuthor($actor)->setObject($event->getObjectType(), $event->getObjectId()); foreach ($users as $user => $path) { $activity->setAffectedUser($user); foreach ($tags as $tag) { if ($event->getEvent() === MapperEvent::EVENT_ASSIGN) { $activity->setSubject(Extension::ASSIGN_TAG, [$actor, $path, $this->prepareTagAsParameter($tag)]); } else { if ($event->getEvent() === MapperEvent::EVENT_UNASSIGN) { $activity->setSubject(Extension::UNASSIGN_TAG, [$actor, $path, $this->prepareTagAsParameter($tag)]); } } $this->activityManager->publish($activity); } } }
/** * Create a share object from an database row * * @param mixed[] $data * @return Share */ private function createShare($data) { $share = new Share(); $share->setId((int) $data['id'])->setShareType((int) $data['share_type'])->setPermissions((int) $data['permissions'])->setTarget($data['file_target'])->setShareTime((int) $data['stime'])->setMailSend((bool) $data['mail_send']); if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { $share->setSharedWith($this->userManager->get($data['share_with'])); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $share->setSharedWith($this->groupManager->get($data['share_with'])); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $share->setPassword($data['share_with']); $share->setToken($data['token']); } else { $share->setSharedWith($data['share_with']); } } } $share->setSharedBy($this->userManager->get($data['uid_owner'])); // TODO: getById can return an array. How to handle this properly?? $folder = $this->rootFolder->getUserFolder($share->getSharedBy()->getUID()); $path = $folder->getById((int) $data['file_source'])[0]; $owner = $path->getOwner(); $share->setShareOwner($owner); $path = $this->rootFolder->getUserFolder($owner->getUID())->getById((int) $data['file_source'])[0]; $share->setPath($path); if ($data['expiration'] !== null) { $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']); $share->setExpirationDate($expiration); } return $share; }
public function testRun() { //Add test user $user1 = $this->userManager->createUser('test1', 'test1'); $userFolder = $this->rootFolder->getUserFolder('test1'); $fileId = $userFolder->getId(); //Now insert cyclic share $qb = $this->connection->getQueryBuilder(); $qb->insert('share')->values(['share_type' => $qb->createNamedParameter(0), 'share_with' => $qb->createNamedParameter('foo'), 'uid_owner' => $qb->createNamedParameter('owner'), 'item_type' => $qb->createNamedParameter('file'), 'item_source' => $qb->createNamedParameter($fileId), 'item_target' => $qb->createNamedParameter('/target'), 'file_source' => $qb->createNamedParameter($fileId), 'file_target' => $qb->createNamedParameter('/target'), 'permissions' => $qb->createNamedParameter(1)]); $qb->execute(); //Add test user $user2 = $this->userManager->createUser('test2', 'test2'); $userFolder = $this->rootFolder->getUserFolder('test2'); $folder = $userFolder->newFolder('foo'); $fileId = $folder->getId(); //Now insert cyclic share $qb = $this->connection->getQueryBuilder(); $qb->insert('share')->values(['share_type' => $qb->createNamedParameter(0), 'share_with' => $qb->createNamedParameter('foo'), 'uid_owner' => $qb->createNamedParameter('owner'), 'item_type' => $qb->createNamedParameter('file'), 'item_source' => $qb->createNamedParameter($fileId), 'item_target' => $qb->createNamedParameter('/target'), 'file_source' => $qb->createNamedParameter($fileId), 'file_target' => $qb->createNamedParameter('/target'), 'permissions' => $qb->createNamedParameter(1)]); $qb->execute(); $this->repair->run($this->outputMock); //Verify $qb = $this->connection->getQueryBuilder(); $qb->selectAlias($qb->createFunction('COUNT(*)'), 'count')->from('share'); $cursor = $qb->execute(); $data = $cursor->fetch(); $cursor->closeCursor(); $count = (int) $data['count']; $this->assertEquals(1, $count); $user1->delete(); $user2->delete(); }
/** * Convert an IShare to an array for OCS output * * @param IShare $share * @return array */ protected function formatShare($share) { $result = ['id' => $share->getId(), 'share_type' => $share->getShareType(), 'uid_owner' => $share->getSharedBy()->getUID(), 'displayname_owner' => $share->getSharedBy()->getDisplayName(), 'permissions' => $share->getPermissions(), 'stime' => $share->getShareTime(), 'parent' => $share->getParent(), 'expiration' => null, 'token' => null]; $path = $share->getPath(); $result['path'] = $this->rootFolder->getUserFolder($share->getShareOwner()->getUID())->getRelativePath($path->getPath()); if ($path instanceof \OCP\Files\Folder) { $result['item_type'] = 'folder'; } else { $result['item_type'] = 'file'; } $result['storage_id'] = $path->getStorage()->getId(); $result['storage'] = \OC\Files\Cache\Storage::getNumericStorageId($path->getStorage()->getId()); $result['item_source'] = $path->getId(); $result['file_source'] = $path->getId(); $result['file_parent'] = $path->getParent()->getId(); $result['file_target'] = $share->getTarget(); if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { $sharedWith = $share->getSharedWith(); $result['share_with'] = $sharedWith->getUID(); $result['share_with_displayname'] = $sharedWith->getDisplayName(); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $sharedWith = $share->getSharedWith(); $result['share_with'] = $sharedWith->getGID(); $result['share_with_displayname'] = $sharedWith->getGID(); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $result['share_with'] = $share->getPassword(); $result['share_with_displayname'] = $share->getPassword(); $result['token'] = $share->getToken(); $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]); $expiration = $share->getExpirationDate(); if ($expiration !== null) { $result['expiration'] = $expiration->format('Y-m-d 00:00:00'); } } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) { $result['share_with'] = $share->getSharedWith(); $result['share_with_displayname'] = $share->getSharedWith(); $result['token'] = $share->getToken(); } } } } $result['mail_send'] = $share->getMailSend() ? 1 : 0; return $result; }
/** * Update a share * * @param \OCP\Share\IShare $share * @return \OCP\Share\IShare The share object * @throws \InvalidArgumentException */ public function updateShare(\OCP\Share\IShare $share) { $expirationDateUpdated = false; if (!$this->canShare($share)) { throw new \Exception('The Share API is disabled'); } $originalShare = $this->getShareById($share->getFullId()); // We can't change the share type! if ($share->getShareType() !== $originalShare->getShareType()) { throw new \InvalidArgumentException('Can\'t change share type'); } // We can only change the recipient on user shares if ($share->getSharedWith() !== $originalShare->getSharedWith() && $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) { throw new \InvalidArgumentException('Can only update recipient on user shares'); } // Cannot share with the owner if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() === $share->getShareOwner()) { throw new \InvalidArgumentException('Can\'t share with the share owner'); } $this->generalCreateChecks($share); if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { $this->userCreateChecks($share); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $this->groupCreateChecks($share); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $this->linkCreateChecks($share); // Password updated. if ($share->getPassword() !== $originalShare->getPassword()) { //Verify the password $this->verifyPassword($share->getPassword()); // If a password is set. Hash it! if ($share->getPassword() !== null) { $share->setPassword($this->hasher->hash($share->getPassword())); } } if ($share->getExpirationDate() !== $originalShare->getExpirationDate()) { //Verify the expiration date $this->validateExpirationDate($share); $expirationDateUpdated = true; } } } } $this->pathCreateChecks($share->getNode()); // Now update the share! $provider = $this->factory->getProviderForType($share->getShareType()); $share = $provider->update($share); if ($expirationDateUpdated === true) { \OC_Hook::emit('OCP\\Share', 'post_set_expiration_date', ['itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'date' => $share->getExpirationDate(), 'uidOwner' => $share->getSharedBy()]); } if ($share->getPermissions() !== $originalShare->getPermissions()) { $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); \OC_Hook::emit('OCP\\Share', 'post_update_permissions', array('itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), 'shareWith' => $share->getSharedWith(), 'uidOwner' => $share->getSharedBy(), 'permissions' => $share->getPermissions(), 'path' => $userFolder->getRelativePath($share->getNode()->getPath()))); } return $share; }
/** * @param int $type The share type * @param string $path The path to share relative to $initiators root * @param string $initiator * @param string $recipient * @param int $permissions * @return \OCP\Share\IShare */ protected function share($type, $path, $initiator, $recipient, $permissions) { $userFolder = $this->rootFolder->getUserFolder($initiator); $node = $userFolder->get($path); $share = $this->shareManager->newShare(); $share->setShareType($type)->setSharedWith($recipient)->setSharedBy($initiator)->setNode($node)->setPermissions($permissions); $share = $this->shareManager->createShare($share); return $share; }
/** * @param CommentsEvent $event */ public function commentEvent(CommentsEvent $event) { if ($event->getComment()->getObjectType() !== 'files' || !in_array($event->getEvent(), [CommentsEvent::EVENT_ADD]) || !$this->appManager->isInstalled('activity')) { // Comment not for file, not adding a comment or no activity-app enabled (save the energy) return; } // Get all mount point owners $cache = $this->mountCollection->getMountCache(); $mounts = $cache->getMountsForFileId($event->getComment()->getObjectId()); if (empty($mounts)) { return; } $users = []; foreach ($mounts as $mount) { $owner = $mount->getUser()->getUID(); $ownerFolder = $this->rootFolder->getUserFolder($owner); $nodes = $ownerFolder->getById($event->getComment()->getObjectId()); if (!empty($nodes)) { /** @var Node $node */ $node = array_shift($nodes); $path = $node->getPath(); if (strpos($path, '/' . $owner . '/files/') === 0) { $path = substr($path, strlen('/' . $owner . '/files')); } // Get all users that have access to the mount point $users = array_merge($users, Share::getUsersSharingFile($path, $owner, true, true)); } } $actor = $this->session->getUser(); if ($actor instanceof IUser) { $actor = $actor->getUID(); } else { $actor = ''; } $activity = $this->activityManager->generateEvent(); $activity->setApp(Extension::APP_NAME)->setType(Extension::APP_NAME)->setAuthor($actor)->setObject($event->getComment()->getObjectType(), $event->getComment()->getObjectId())->setMessage(Extension::ADD_COMMENT_MESSAGE, [$event->getComment()->getId()]); foreach ($users as $user => $path) { $activity->setAffectedUser($user); $activity->setSubject(Extension::ADD_COMMENT_SUBJECT, [$actor, $path]); $this->activityManager->publish($activity); } }
/** * Creates the environment based on the share the token links to * * @param IShare $share */ public function setTokenBasedEnv($share) { $origShareOwnerId = $share->getShareOwner(); $this->userFolder = $this->rootFolder->getUserFolder($origShareOwnerId); $this->sharedNodeId = $share->getNodeId(); $this->sharedNode = $share->getNode(); $this->fromRootToFolder = $this->buildFromRootToFolder($this->sharedNodeId); $this->folderName = $share->getTarget(); $this->userId = $origShareOwnerId; $this->sharePassword = $share->getPassword(); }
/** * @param string $name */ function childExists($name) { // TODO: make this more abstract if ($this->objectType === 'files') { // make sure the object is reachable for the current user $userId = $this->userSession->getUser()->getUID(); $nodes = $this->fileRoot->getUserFolder($userId)->getById(intval($name)); return !empty($nodes); } return true; }
/** * Creates the environment based on the linkItem the token links to * * @param array $linkItem */ public function setTokenBasedEnv($linkItem) { // Resolves reshares down to the last real share $rootLinkItem = Share::resolveReShare($linkItem); $origShareOwner = $rootLinkItem['uid_owner']; $this->userFolder = $this->rootFolder->getUserFolder($origShareOwner); // This is actually the node ID $this->sharedNodeId = $linkItem['file_source']; $this->fromRootToFolder = $this->buildFromRootToFolder($this->sharedNodeId); $this->folderName = $linkItem['file_target']; $this->userId = $rootLinkItem['uid_owner']; $this->sharePassword = $linkItem['share_with']; }
/** * Get the node with file $id for $user * * @param string $userId * @param int $id * @return \OCP\Files\File|\OCP\Files\Folder * @throws InvalidShare */ private function getNode($userId, $id) { try { $userFolder = $this->rootFolder->getUserFolder($userId); } catch (NotFoundException $e) { throw new InvalidShare(); } $nodes = $userFolder->getById($id); if (empty($nodes)) { throw new InvalidShare(); } return $nodes[0]; }
/** * @inheritdoc */ public function getNode() { if ($this->node === null) { if ($this->shareOwner === null || $this->fileId === null) { throw new NotFoundException(); } $userFolder = $this->rootFolder->getUserFolder($this->shareOwner); $nodes = $userFolder->getById($this->fileId); if (empty($nodes)) { throw new NotFoundException(); } $this->node = $nodes[0]; } return $this->node; }
/** * The getShares function. * * - Get shares by the current user * - Get shares by the current user and reshares (?reshares=true) * - Get shares with the current user (?shared_with_me=true) * - Get shares for a specific path (?path=...) * - Get all shares in a folder (?subfiles=true&path=..) * * @return \OC_OCS_Result */ public function getShares() { $sharedWithMe = $this->request->getParam('shared_with_me', null); $reshares = $this->request->getParam('reshares', null); $subfiles = $this->request->getParam('subfiles'); $path = $this->request->getParam('path', null); if ($path !== null) { $userFolder = $this->rootFolder->getUserFolder($this->currentUser->getUID()); try { $path = $userFolder->get($path); } catch (\OCP\Files\NotFoundException $e) { return new \OC_OCS_Result(null, 404, 'wrong path, file/folder doesn\'t exist'); } } if ($sharedWithMe === 'true') { return $this->getSharedWithMe($path); } if ($subfiles === 'true') { return $this->getSharesInDir($path); } if ($reshares === 'true') { $reshares = true; } else { $reshares = false; } // Get all shares $userShares = $this->shareManager->getSharesBy($this->currentUser->getUID(), \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0); $groupShares = $this->shareManager->getSharesBy($this->currentUser->getUID(), \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0); $linkShares = $this->shareManager->getSharesBy($this->currentUser->getUID(), \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0); $shares = array_merge($userShares, $groupShares, $linkShares); if ($this->shareManager->outgoingServer2ServerSharesAllowed()) { $federatedShares = $this->shareManager->getSharesBy($this->currentUser->getUID(), \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0); $shares = array_merge($shares, $federatedShares); } $formatted = []; foreach ($shares as $share) { try { $formatted[] = $this->formatShare($share); } catch (NotFoundException $e) { //Ignore share } } return new \OC_OCS_Result($formatted); }
/** * @inheritdoc */ public function getNode() { if ($this->node === null) { if ($this->shareOwner === null || $this->fileId === null) { throw new NotFoundException(); } // for federated shares the owner can be a remote user, in this // case we use the initiator if ($this->userManager->userExists($this->shareOwner)) { $userFolder = $this->rootFolder->getUserFolder($this->shareOwner); } else { $userFolder = $this->rootFolder->getUserFolder($this->sharedBy); } $nodes = $userFolder->getById($this->fileId); if (empty($nodes)) { throw new NotFoundException(); } $this->node = $nodes[0]; } return $this->node; }
/** * @return \OC_OCS_Result */ public function createShare() { $share = $this->shareManager->newShare(); // Verify path $path = $this->request->getParam('path', null); if ($path === null) { return new \OC_OCS_Result(null, 404, 'please specify a file or folder path'); } $userFolder = $this->rootFolder->getUserFolder($this->currentUser->getUID()); try { $path = $userFolder->get($path); } catch (\OCP\Files\NotFoundException $e) { return new \OC_OCS_Result(null, 404, 'wrong path, file/folder doesn\'t exist'); } $share->setPath($path); // Parse permissions (if available) $permissions = $this->request->getParam('permissions', null); if ($permissions === null) { $permissions = \OCP\Constants::PERMISSION_ALL; } else { $permissions = (int) $permissions; } if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) { return new \OC_OCS_Result(null, 404, 'invalid permissions'); } // Shares always require read permissions $permissions |= \OCP\Constants::PERMISSION_READ; if ($path instanceof \OCP\Files\File) { // Single file shares should never have delete or create permissions $permissions &= ~\OCP\Constants::PERMISSION_DELETE; $permissions &= ~\OCP\Constants::PERMISSION_CREATE; } $shareWith = $this->request->getParam('shareWith', null); $shareType = (int) $this->request->getParam('shareType', '-1'); if ($shareType === \OCP\Share::SHARE_TYPE_USER) { // Valid user is required to share if ($shareWith === null || !$this->userManager->userExists($shareWith)) { return new \OC_OCS_Result(null, 404, 'please specify a valid user'); } $share->setSharedWith($this->userManager->get($shareWith)); $share->setPermissions($permissions); } else { if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) { // Valid group is required to share if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) { return new \OC_OCS_Result(null, 404, 'please specify a valid group'); } $share->setSharedWith($this->groupManager->get($shareWith)); $share->setPermissions($permissions); } else { if ($shareType === \OCP\Share::SHARE_TYPE_LINK) { //Can we even share links? if (!$this->shareManager->shareApiAllowLinks()) { return new \OC_OCS_Result(null, 404, 'public link sharing is disabled by the administrator'); } $publicUpload = $this->request->getParam('publicUpload', null); if ($publicUpload === 'true') { // Check if public upload is allowed if (!$this->shareManager->shareApiLinkAllowPublicUpload()) { return new \OC_OCS_Result(null, 403, '"public upload disabled by the administrator'); } // Public upload can only be set for folders if ($path instanceof \OCP\Files\File) { return new \OC_OCS_Result(null, 404, '"public upload is only possible for public shared folders'); } $share->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE); } else { $share->setPermissions(\OCP\Constants::PERMISSION_READ); } // Set password $share->setPassword($this->request->getParam('password', null)); //Expire date $expireDate = $this->request->getParam('expireDate', null); if ($expireDate !== null) { try { $expireDate = $this->parseDate($expireDate); $share->setExpirationDate($expireDate); } catch (\Exception $e) { return new \OC_OCS_Result(null, 404, 'Invalid Date. Format must be YYYY-MM-DD.'); } } } else { if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) { //fixme Remote shares are handled by old code path for now return \OCA\Files_Sharing\API\Local::createShare([]); } else { return new \OC_OCS_Result(null, 400, "unknown share type"); } } } } $share->setShareType($shareType); $share->setSharedBy($this->currentUser); try { $share = $this->shareManager->createShare($share); } catch (\OC\HintException $e) { $code = $e->getCode() === 0 ? 403 : $e->getCode(); return new \OC_OCS_Result(null, $code, $e->getHint()); } catch (\Exception $e) { return new \OC_OCS_Result(null, 403, $e->getMessage()); } $share = $this->formatShare($share); return new \OC_OCS_Result($share); }
/** * @PublicPage * @NoCSRFRequired * * @param string $token * @param string $files * @param string $path * @param string $downloadStartSecret * @return void|RedirectResponse */ public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') { \OC_User::setIncognitoMode(true); $share = $this->shareManager->getShareByToken($token); // Share is password protected - check whether the user is permitted to access the share if ($share->getPassword() !== null && !$this->linkShareAuth($share)) { return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', ['token' => $token])); } $files_list = null; if (!is_null($files)) { // download selected files $files_list = json_decode($files); // in case we get only a single file if ($files_list === null) { $files_list = [$files]; } } $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()->getUID()); $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath()); // Single file share if ($share->getNode() instanceof \OCP\Files\File) { // Single file download $event = $this->activityManager->generateEvent(); $event->setApp('files_sharing')->setType(Activity::TYPE_PUBLIC_LINKS)->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($share->getNode()->getPath())])->setAffectedUser($share->getShareOwner()->getUID())->setObject('files', $share->getNode()->getId(), $userFolder->getRelativePath($share->getNode()->getPath())); $this->activityManager->publish($event); } else { /** @var \OCP\Files\Folder $node */ $node = $share->getNode(); // Try to get the path if ($path !== '') { try { $node = $node->get($path); } catch (NotFoundException $e) { return new NotFoundResponse(); } } $originalSharePath = $userFolder->getRelativePath($node->getPath()); if ($node instanceof \OCP\Files\File) { // Single file download $event = $this->activityManager->generateEvent(); $event->setApp('files_sharing')->setType(Activity::TYPE_PUBLIC_LINKS)->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])->setAffectedUser($share->getShareOwner()->getUID())->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath())); $this->activityManager->publish($event); } else { if (!empty($files_list)) { /** @var \OCP\Files\Folder $node */ // Subset of files is downloaded foreach ($files_list as $file) { $subNode = $node->get($file); $event = $this->activityManager->generateEvent(); $event->setApp('files_sharing')->setType(Activity::TYPE_PUBLIC_LINKS)->setAffectedUser($share->getShareOwner()->getUID())->setObject('files', $subNode->getId(), $userFolder->getRelativePath($subNode->getPath())); if ($subNode instanceof \OCP\Files\File) { $event->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($subNode->getPath())]); } else { $event->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($subNode->getPath())]); } $this->activityManager->publish($event); } } else { // The folder is downloaded $event = $this->activityManager->generateEvent(); $event->setApp('files_sharing')->setType(Activity::TYPE_PUBLIC_LINKS)->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])->setAffectedUser($share->getShareOwner()->getUID())->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath())); $this->activityManager->publish($event); } } } /* FIXME: We should do this all nicely in OCP */ OC_Util::tearDownFS(); OC_Util::setupFS($share->getShareOwner()->getUID()); /** * this sets a cookie to be able to recognize the start of the download * the content must not be longer than 32 characters and must only contain * alphanumeric characters */ if (!empty($downloadStartSecret) && !isset($downloadStartSecret[32]) && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) { // FIXME: set on the response once we use an actual app framework response setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/'); } // download selected files if (!is_null($files)) { // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well // after dispatching the request which results in a "Cannot modify header information" notice. OC_Files::get($originalSharePath, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD'); exit; } else { // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well // after dispatching the request which results in a "Cannot modify header information" notice. OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $_SERVER['REQUEST_METHOD'] == 'HEAD'); exit; } }
/** * @param $path path to file * @return int id of the file */ public function getFileId($path) { $userFolder = $this->rootFolder->getUserFolder(); $file = $userFolder->get($path); return $file->getId(); }