/** * 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); }
public function testGetAvatarValidUser() { $this->userManager->expects($this->once())->method('get')->with('validUser')->willReturn(true); $folder = $this->getMock('\\OCP\\Files\\Folder'); $this->rootFolder->expects($this->once())->method('getUserFolder')->with('validUser')->willReturn($folder); $folder->expects($this->once())->method('getParent')->will($this->returnSelf()); $this->avatarManager->getAvatar('validUser'); }
/** * 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(); }
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(); }
/** * @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); } } }
/** * return a user specific instance of \OCP\IAvatar * @see \OCP\IAvatar * @param string $userId the ownCloud user id * @return \OCP\IAvatar * @throws \Exception In case the username is potentially dangerous * @throws NotFoundException In case there is no user folder yet */ public function getAvatar($userId) { $user = $this->userManager->get($userId); if (is_null($user)) { throw new \Exception('user does not exist'); } /* * Fix for #22119 * Basically we do not want to copy the skeleton folder */ \OC\Files\Filesystem::initMountPoints($userId); $dir = '/' . $userId; /** @var Folder $folder */ $folder = $this->rootFolder->get($dir); return new Avatar($folder, $this->l, $user, $this->logger); }
/** * 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; }
/** * 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; }
/** * delete versions for the given user * * @param string $user */ protected function deleteVersions($user) { \OC_Util::tearDownFS(); \OC_Util::setupFS($user); if ($this->rootFolder->nodeExists('/' . $user . '/files_versions')) { $this->rootFolder->get('/' . $user . '/files_versions')->delete(); } }
/** * 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); } }
/** * remove deleted files for the given user * * @param string $uid */ protected function removeDeletedFiles($uid) { \OC_Util::tearDownFS(); \OC_Util::setupFS($uid); if ($this->rootFolder->nodeExists('/' . $uid . '/files_trashbin')) { $this->rootFolder->get('/' . $uid . '/files_trashbin')->delete(); $query = $this->dbConnection->getQueryBuilder(); $query->delete('files_trash')->where($query->expr()->eq('user', $query->createParameter('uid')))->setParameter('uid', $uid); $query->execute(); } }
/** * @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 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(); }
/** * @dataProvider dataGetShare */ public function testGetShare(\OC\Share20\IShare $share, array $result) { $ocs = $this->getMockBuilder('OCA\\Files_Sharing\\API\\Share20OCS')->setConstructorArgs([$this->shareManager, $this->groupManager, $this->userManager, $this->request, $this->rootFolder, $this->urlGenerator, $this->currentUser])->setMethods(['canAccessShare'])->getMock(); $ocs->method('canAccessShare')->willReturn(true); $this->shareManager->expects($this->once())->method('getShareById')->with($share->getId())->willReturn($share); $userFolder = $this->getMock('OCP\\Files\\Folder'); $userFolder->method('getRelativePath')->will($this->returnArgument(0)); $this->rootFolder->method('getUserFolder')->with($share->getShareOwner()->getUID())->willReturn($userFolder); $this->urlGenerator->method('linkToRouteAbsolute')->willReturn('url'); $expected = new \OC_OCS_Result($result); $this->assertEquals($expected->getData(), $ocs->getShare($share->getId())->getData()); }
/** * 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]; }
/** * 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']; }
/** * @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; }
public function testCreateLinkShare() { $share = new \OC\Share20\Share(); $sharedBy = $this->getMock('OCP\\IUser'); $sharedBy->method('getUID')->willReturn('sharedBy'); $shareOwner = $this->getMock('OCP\\IUser'); $shareOwner->method('getUID')->WillReturn('shareOwner'); $this->userManager->method('get')->will($this->returnValueMap([['sharedBy', $sharedBy], ['shareOwner', $shareOwner]])); $path = $this->getMock('\\OCP\\Files\\Folder'); $path->method('getId')->willReturn(100); $path->method('getOwner')->willReturn($shareOwner); $ownerFolder = $this->getMock('OCP\\Files\\Folder'); $userFolder = $this->getMock('OCP\\Files\\Folder'); $this->rootFolder->method('getUserFolder')->will($this->returnValueMap([['sharedBy', $userFolder], ['shareOwner', $ownerFolder]])); $userFolder->method('getById')->with(100)->willReturn([$path]); $ownerFolder->method('getById')->with(100)->willReturn([$path]); $share->setShareType(\OCP\Share::SHARE_TYPE_LINK); $share->setSharedBy($sharedBy); $share->setShareOwner($shareOwner); $share->setPath($path); $share->setPermissions(1); $share->setPassword('password'); $share->setToken('token'); $expireDate = new \DateTime(); $share->setExpirationDate($expireDate); $share->setTarget('/target'); $share2 = $this->provider->create($share); $this->assertNotNull($share2->getId()); $this->assertSame('ocinternal:' . $share2->getId(), $share2->getFullId()); $this->assertSame(\OCP\Share::SHARE_TYPE_LINK, $share2->getShareType()); $this->assertSame($sharedBy, $share2->getSharedBy()); $this->assertSame($shareOwner, $share2->getShareOwner()); $this->assertSame(1, $share2->getPermissions()); $this->assertSame('/target', $share2->getTarget()); $this->assertLessThanOrEqual(time(), $share2->getSharetime()); $this->assertSame($path, $share2->getPath()); $this->assertSame('password', $share2->getPassword()); $this->assertSame('token', $share2->getToken()); $this->assertEquals($expireDate, $share2->getExpirationDate()); }
public function testGetShareByToken() { $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share')->values(['share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_LINK), 'share_with' => $qb->expr()->literal('password'), 'uid_owner' => $qb->expr()->literal('shareOwner'), 'uid_initiator' => $qb->expr()->literal('sharedBy'), 'item_type' => $qb->expr()->literal('file'), 'file_source' => $qb->expr()->literal(42), 'file_target' => $qb->expr()->literal('myTarget'), 'permissions' => $qb->expr()->literal(13), 'token' => $qb->expr()->literal('secrettoken')]); $qb->execute(); $id = $qb->getLastInsertId(); $owner = $this->getMock('\\OCP\\IUser'); $owner->method('getUID')->willReturn('shareOwner'); $initiator = $this->getMock('\\OCP\\IUser'); $initiator->method('getUID')->willReturn('sharedBy'); $this->userManager->method('get')->will($this->returnValueMap([['sharedBy', $initiator], ['shareOwner', $owner]])); $file = $this->getMock('\\OCP\\Files\\File'); $this->rootFolder->method('getUserFolder')->with('shareOwner')->will($this->returnSelf()); $this->rootFolder->method('getById')->with(42)->willReturn([$file]); $share = $this->provider->getShareByToken('secrettoken'); $this->assertEquals($id, $share->getId()); $this->assertSame($owner, $share->getShareOwner()); $this->assertSame($initiator, $share->getSharedBy()); $this->assertSame('secrettoken', $share->getToken()); $this->assertSame('password', $share->getPassword()); $this->assertSame(null, $share->getSharedWith()); }
public function testCreateShareGroup() { $share = $this->getMock('\\OC\\Share20\\IShare'); $this->shareManager->method('newShare')->willReturn($share); $ocs = $this->getMockBuilder('OCA\\Files_Sharing\\API\\Share20OCS')->setConstructorArgs([$this->shareManager, $this->groupManager, $this->userManager, $this->request, $this->rootFolder, $this->urlGenerator, $this->currentUser])->setMethods(['formatShare'])->getMock(); $this->request->method('getParam')->will($this->returnValueMap([['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], ['shareType', '-1', \OCP\Share::SHARE_TYPE_GROUP], ['shareWith', null, 'validGroup']])); $userFolder = $this->getMock('\\OCP\\Files\\Folder'); $this->rootFolder->expects($this->once())->method('getUserFolder')->with('currentUser')->willReturn($userFolder); $path = $this->getMock('\\OCP\\Files\\Folder'); $userFolder->expects($this->once())->method('get')->with('valid-path')->willReturn($path); $group = $this->getMock('\\OCP\\IGroup'); $this->groupManager->method('groupExists')->with('validGroup')->willReturn(true); $this->groupManager->method('get')->with('validGroup')->willReturn($group); $share->method('setPath')->with($path); $share->method('setPermissions')->with(\OCP\Constants::PERMISSION_ALL); $share->method('setShareType')->with(\OCP\Share::SHARE_TYPE_GROUP); $share->method('setSharedWith')->with($group); $share->method('setSharedBy')->with($this->currentUser); $expected = new \OC_OCS_Result(); $result = $ocs->createShare(); $this->assertEquals($expected->getMeta(), $result->getMeta()); $this->assertEquals($expected->getData(), $result->getData()); }
/** * @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; } }
public function testGetChildren() { $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share')->values(['share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_USER), 'share_with' => $qb->expr()->literal('sharedWith'), 'uid_owner' => $qb->expr()->literal('sharedBy'), 'item_type' => $qb->expr()->literal('file'), 'file_source' => $qb->expr()->literal(42), 'file_target' => $qb->expr()->literal('myTarget'), 'permissions' => $qb->expr()->literal(13)]); $qb->execute(); // Get the id $qb = $this->dbConn->getQueryBuilder(); $cursor = $qb->select('id')->from('share')->setMaxResults(1)->orderBy('id', 'DESC')->execute(); $id = $cursor->fetch(); $id = $id['id']; $cursor->closeCursor(); $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share')->values(['share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_USER), 'share_with' => $qb->expr()->literal('user1'), 'uid_owner' => $qb->expr()->literal('user2'), 'item_type' => $qb->expr()->literal('file'), 'file_source' => $qb->expr()->literal(1), 'file_target' => $qb->expr()->literal('myTarget1'), 'permissions' => $qb->expr()->literal(2), 'parent' => $qb->expr()->literal($id)]); $qb->execute(); $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share')->values(['share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_GROUP), 'share_with' => $qb->expr()->literal('group1'), 'uid_owner' => $qb->expr()->literal('user3'), 'item_type' => $qb->expr()->literal('folder'), 'file_source' => $qb->expr()->literal(3), 'file_target' => $qb->expr()->literal('myTarget2'), 'permissions' => $qb->expr()->literal(4), 'parent' => $qb->expr()->literal($id)]); $qb->execute(); $shareOwner = $this->getMock('OCP\\IUser'); $shareOwner->method('getUID')->willReturn('shareOwner'); $user1 = $this->getMock('OCP\\IUser'); $user2 = $this->getMock('OCP\\IUser'); $user2->method('getUID')->willReturn('user2'); $user3 = $this->getMock('OCP\\IUser'); $user3->method('getUID')->willReturn('user3'); $user2Path = $this->getMock('\\OCP\\Files\\File'); $user2Path->expects($this->once())->method('getOwner')->willReturn($shareOwner); $user2Folder = $this->getMock('\\OCP\\Files\\Folder'); $user2Folder->expects($this->once())->method('getById')->with(1)->willReturn([$user2Path]); $user3Path = $this->getMock('\\OCP\\Files\\Folder'); $user3Path->expects($this->once())->method('getOwner')->willReturn($shareOwner); $user3Folder = $this->getMock('\\OCP\\Files\\Folder'); $user3Folder->expects($this->once())->method('getById')->with(3)->willReturn([$user3Path]); $ownerPath = $this->getMock('\\OCP\\Files\\Folder'); $ownerFolder = $this->getMock('\\OCP\\Files\\Folder'); $ownerFolder->method('getById')->willReturn([$ownerPath]); $this->rootFolder->method('getUserFolder')->will($this->returnValueMap([['shareOwner', $ownerFolder], ['user2', $user2Folder], ['user3', $user3Folder]])); $this->userManager->method('get')->will($this->returnValueMap([['user1', $user1], ['user2', $user2], ['user3', $user3]])); $group1 = $this->getMock('OCP\\IGroup'); $this->groupManager->method('get')->will($this->returnValueMap([['group1', $group1]])); $share = $this->getMock('\\OC\\Share20\\IShare'); $share->method('getId')->willReturn($id); $children = $this->provider->getChildren($share); $this->assertCount(2, $children); //Child1 $this->assertEquals(\OCP\Share::SHARE_TYPE_USER, $children[0]->getShareType()); $this->assertEquals($user1, $children[0]->getSharedWith()); $this->assertEquals($user2, $children[0]->getSharedBy()); $this->assertEquals($shareOwner, $children[0]->getShareOwner()); $this->assertEquals($ownerPath, $children[0]->getPath()); $this->assertEquals(2, $children[0]->getPermissions()); $this->assertEquals(null, $children[0]->getToken()); $this->assertEquals(null, $children[0]->getExpirationDate()); $this->assertEquals('myTarget1', $children[0]->getTarget()); //Child2 $this->assertEquals(\OCP\Share::SHARE_TYPE_GROUP, $children[1]->getShareType()); $this->assertEquals($group1, $children[1]->getSharedWith()); $this->assertEquals($user3, $children[1]->getSharedBy()); $this->assertEquals($shareOwner, $children[1]->getShareOwner()); $this->assertEquals($ownerPath, $children[1]->getPath()); $this->assertEquals(4, $children[1]->getPermissions()); $this->assertEquals(null, $children[1]->getToken()); $this->assertEquals(null, $children[1]->getExpirationDate()); $this->assertEquals('myTarget2', $children[1]->getTarget()); }
/** * @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(); }