protected function tearDown() { foreach ($this->users as $user) { $user->delete(); } $this->groupManager->get('admin')->delete(); parent::tearDown(); }
/** * @param string $id * @return DataResponse */ public function destroy($id) { $group = $this->groupManager->get($id); if ($group) { if ($group->delete()) { return new DataResponse(array('status' => 'success', 'data' => array('groupname' => $id)), Http::STATUS_NO_CONTENT); } } return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Unable to delete group.'))), Http::STATUS_FORBIDDEN); }
protected function execute(InputInterface $input, OutputInterface $output) { $uid = $input->getArgument('uid'); if ($this->userManager->userExists($uid)) { $output->writeln('<error>The user "' . $uid . '" already exists.</error>'); return 1; } if ($input->getOption('password-from-env')) { $password = getenv('OC_PASS'); if (!$password) { $output->writeln('<error>--password-from-env given, but OC_PASS is empty!</error>'); return 1; } } elseif ($input->isInteractive()) { /** @var $dialog \Symfony\Component\Console\Helper\DialogHelper */ $dialog = $this->getHelperSet()->get('dialog'); $password = $dialog->askHiddenResponse($output, '<question>Enter password: </question>', false); $confirm = $dialog->askHiddenResponse($output, '<question>Confirm password: </question>', false); if ($password !== $confirm) { $output->writeln("<error>Passwords did not match!</error>"); return 1; } } else { $output->writeln("<error>Interactive input or --password-from-env is needed for entering a password!</error>"); return 1; } $user = $this->userManager->createUser($input->getArgument('uid'), $password); if ($user instanceof IUser) { $output->writeln('<info>The user "' . $user->getUID() . '" was created successfully</info>'); } else { $output->writeln('<error>An error occurred while creating the user</error>'); return 1; } if ($input->getOption('display-name')) { $user->setDisplayName($input->getOption('display-name')); $output->writeln('Display name set to "' . $user->getDisplayName() . '"'); } foreach ($input->getOption('group') as $groupName) { $group = $this->groupManager->get($groupName); if (!$group) { $this->groupManager->createGroup($groupName); $group = $this->groupManager->get($groupName); $output->writeln('Created group "' . $group->getGID() . '"'); } $group->addUser($user); $output->writeln('User "' . $user->getUID() . '" added to group "' . $group->getGID() . '"'); } }
/** * @NoAdminRequired * * @param string $username * @param string $password * @param array $groups * @param string $email * @return DataResponse */ public function create($username, $password, array $groups = array(), $email = '') { if ($email !== '' && !$this->mail->validateAddress($email)) { return new DataResponse(array('message' => (string) $this->l10n->t('Invalid mail address')), Http::STATUS_UNPROCESSABLE_ENTITY); } if (!$this->isAdmin) { $userId = $this->userSession->getUser()->getUID(); if (!empty($groups)) { foreach ($groups as $key => $group) { if (!$this->subAdminFactory->isGroupAccessible($userId, $group)) { unset($groups[$key]); } } } if (empty($groups)) { $groups = $this->subAdminFactory->getSubAdminsOfGroups($userId); } } if ($this->userManager->userExists($username)) { return new DataResponse(array('message' => (string) $this->l10n->t('A user with that name already exists.')), Http::STATUS_CONFLICT); } try { $user = $this->userManager->createUser($username, $password); } catch (\Exception $exception) { return new DataResponse(array('message' => (string) $this->l10n->t('Unable to create user.')), Http::STATUS_FORBIDDEN); } if ($user instanceof User) { if ($groups !== null) { foreach ($groups as $groupName) { $group = $this->groupManager->get($groupName); if (empty($group)) { $group = $this->groupManager->createGroup($groupName); } $group->addUser($user); } } /** * Send new user mail only if a mail is set */ if ($email !== '') { $this->config->setUserValue($username, 'settings', 'email', $email); // data for the mail template $mailData = array('username' => $username, 'url' => $this->urlGenerator->getAbsoluteURL('/')); $mail = new TemplateResponse('settings', 'email.new_user', $mailData, 'blank'); $mailContent = $mail->render(); $mail = new TemplateResponse('settings', 'email.new_user_plain_text', $mailData, 'blank'); $plainTextMailContent = $mail->render(); $subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]); try { $this->mail->send($email, $username, $subject, $mailContent, $this->fromMailAddress, $this->defaults->getName(), 1, $plainTextMailContent); } catch (\Exception $e) { $this->log->error("Can't send new user mail to {$email}: " . $e->getMessage(), array('app' => 'settings')); } } // fetch users groups $userGroups = $this->groupManager->getUserGroupIds($user); return new DataResponse($this->formatUserForIndex($user, $userGroups), Http::STATUS_CREATED); } return new DataResponse(array('message' => (string) $this->l10n->t('Unable to create user.')), Http::STATUS_FORBIDDEN); }
public function testIsUserAccessibleAdmin() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); $this->groupManager->get('admin')->addUser($this->users[1]); $this->assertFalse($subAdmin->isUserAccessible($this->users[0], $this->users[1])); }
/** * Sharing a file or folder with a group * * @param string $shareWith * @param int $fileSource File ID that is being shared * @param string $itemType File type that is being shared (file or folder) * @param string $fileTarget File path * @param int $shareId The Share ID of this share * @param bool $isSharing True if sharing, false if unsharing */ protected function shareFileOrFolderWithGroup($shareWith, $fileSource, $itemType, $fileTarget, $shareId, $isSharing) { if ($isSharing) { $actionSharer = 'shared_group_self'; $actionOwner = 'reshared_group_by'; $actionUser = '******'; } else { $actionSharer = 'unshared_group_self'; $actionOwner = 'unshared_group_by'; $actionUser = '******'; } // Members of the new group $group = $this->groupManager->get($shareWith); if (!$group instanceof IGroup) { return; } // User performing the share $this->shareNotificationForSharer($actionSharer, $shareWith, $fileSource, $itemType); $this->shareNotificationForOriginalOwners($this->currentUser, $actionOwner, $shareWith, $fileSource, $itemType); $offset = 0; $users = $group->searchUsers('', self::USER_BATCH_SIZE, $offset); while (!empty($users)) { $this->addNotificationsForGroupUsers($users, $actionUser, $fileSource, $itemType, $fileTarget, $shareId); $offset += self::USER_BATCH_SIZE; $users = $group->searchUsers('', self::USER_BATCH_SIZE, $offset); } }
/** * Count all unique users visible for the current admin/subadmin. * * @NoAdminRequired * * @return DataResponse */ public function stats() { $userCount = 0; if ($this->isAdmin) { $countByBackend = $this->userManager->countUsers(); if (!empty($countByBackend)) { foreach ($countByBackend as $count) { $userCount += $count; } } } else { $groupNames = $this->subAdminFactory->getSubAdminsOfGroups($this->userSession->getUser()->getUID()); $uniqueUsers = []; foreach ($groupNames as $groupName) { $group = $this->groupManager->get($groupName); if (!is_null($group)) { foreach ($group->getUsers() as $uid => $displayName) { $uniqueUsers[$uid] = true; } } } $userCount = count($uniqueUsers); } return new DataResponse(['totalUsers' => $userCount]); }
/** * Sharing a file or folder with a group * * @param string $shareWith * @param int $fileSource File ID that is being shared * @param string $itemType File type that is being shared (file or folder) * @param string $fileTarget File path * @param int $shareId The Share ID of this share */ protected function shareFileOrFolderWithGroup($shareWith, $fileSource, $itemType, $fileTarget, $shareId) { // Members of the new group $affectedUsers = array(); $group = $this->groupManager->get($shareWith); if (!$group instanceof \OCP\IGroup) { return; } // User performing the share $this->shareNotificationForSharer('shared_group_self', $shareWith, $fileSource, $itemType); $this->shareNotificationForOriginalOwners($this->currentUser, 'reshared_group_by', $shareWith, $fileSource, $itemType); $usersInGroup = $group->searchUsers(''); foreach ($usersInGroup as $user) { $affectedUsers[$user->getUID()] = $fileTarget; } // Remove the triggering user, we already managed his notifications unset($affectedUsers[$this->currentUser]); if (empty($affectedUsers)) { return; } $filteredStreamUsersInGroup = $this->userSettings->filterUsersBySetting(array_keys($affectedUsers), 'stream', Files_Sharing::TYPE_SHARED); $filteredEmailUsersInGroup = $this->userSettings->filterUsersBySetting(array_keys($affectedUsers), 'email', Files_Sharing::TYPE_SHARED); $affectedUsers = $this->fixPathsForShareExceptions($affectedUsers, $shareId); foreach ($affectedUsers as $user => $path) { if (empty($filteredStreamUsersInGroup[$user]) && empty($filteredEmailUsersInGroup[$user])) { continue; } $this->addNotificationsForUser($user, 'shared_with_by', array($path, $this->currentUser), $fileSource, $path, $itemType === 'file', !empty($filteredStreamUsersInGroup[$user]), !empty($filteredEmailUsersInGroup[$user]) ? $filteredEmailUsersInGroup[$user] : 0); } }
/** * Returns a specific principal, specified by it's path. * The returned structure should be the exact same as from * getPrincipalsByPrefix. * * @param string $path * @return array */ public function getPrincipalByPath($path) { $elements = explode('/', $path); if ($elements[0] !== 'principals') { return null; } if ($elements[1] !== 'groups') { return null; } $name = $elements[2]; $user = $this->groupManager->get($name); if (!is_null($user)) { return $this->groupToPrincipal($user); } return null; }
/** * @param string $search */ protected function getGroups($search) { $this->result['groups'] = $this->result['exact']['groups'] = []; $groups = $this->groupManager->search($search, $this->limit, $this->offset); $groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups); if (sizeof($groups) < $this->limit) { $this->reachedEndFor[] = 'groups'; } $userGroups = []; if (!empty($groups) && $this->shareWithGroupOnly) { // Intersect all the groups that match with the groups this user is a member of $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser()); $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups); $groups = array_intersect($groups, $userGroups); } foreach ($groups as $gid) { if (strtolower($gid) === $search) { $this->result['exact']['groups'][] = ['label' => $search, 'value' => ['shareType' => Share::SHARE_TYPE_GROUP, 'shareWith' => $search]]; } else { $this->result['groups'][] = ['label' => $gid, 'value' => ['shareType' => Share::SHARE_TYPE_GROUP, 'shareWith' => $gid]]; } } if ($this->offset === 0 && empty($this->result['exact']['groups'])) { // On page one we try if the search result has a direct hit on the // user id and if so, we add that to the exact match list $group = $this->groupManager->get($search); if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) { array_push($this->result['exact']['groups'], ['label' => $group->getGID(), 'value' => ['shareType' => Share::SHARE_TYPE_GROUP, 'shareWith' => $group->getGID()]]); } } }
/** * 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; }
/** * @param ManagerEvent $event */ public function event(ManagerEvent $event) { $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); if ($event->getEvent() === ManagerEvent::EVENT_CREATE) { $activity->setSubject(Extension::CREATE_TAG, [$actor, $this->prepareTagAsParameter($event->getTag())]); } else { if ($event->getEvent() === ManagerEvent::EVENT_UPDATE) { $activity->setSubject(Extension::UPDATE_TAG, [$actor, $this->prepareTagAsParameter($event->getTag()), $this->prepareTagAsParameter($event->getTagBefore())]); } else { if ($event->getEvent() === ManagerEvent::EVENT_DELETE) { $activity->setSubject(Extension::DELETE_TAG, [$actor, $this->prepareTagAsParameter($event->getTag())]); } else { return; } } } $group = $this->groupManager->get('admin'); if ($group instanceof IGroup) { foreach ($group->getUsers() as $user) { $activity->setAffectedUser($user->getUID()); $this->activityManager->publish($activity); } } }
/** * Create a share object from an database row * * @param mixed[] $data * @return \OCP\Share\IShare * @throws InvalidShare */ 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'])->setMailSend((bool) $data['mail_send']); $shareTime = new \DateTime(); $shareTime->setTimestamp((int) $data['stime']); $share->setShareTime($shareTime); if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { $sharedWith = $this->userManager->get($data['share_with']); if ($sharedWith === null) { throw new InvalidShare(); } $share->setSharedWith($sharedWith); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $sharedWith = $this->groupManager->get($data['share_with']); if ($sharedWith === null) { throw new InvalidShare(); } $share->setSharedWith($sharedWith); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $share->setPassword($data['share_with']); $share->setToken($data['token']); } } } if ($data['uid_initiator'] === null) { //OLD SHARE $sharedBy = $this->userManager->get($data['uid_owner']); if ($sharedBy === null) { throw new InvalidShare(); } $share->setSharedBy($sharedBy); $path = $this->getNode($share->getSharedBy(), (int) $data['file_source']); $owner = $path->getOwner(); $share->setShareOwner($owner); } else { //New share! $sharedBy = $this->userManager->get($data['uid_initiator']); $shareOwner = $this->userManager->get($data['uid_owner']); if ($sharedBy === null || $shareOwner === null) { throw new InvalidShare(); } $share->setSharedBy($sharedBy); $share->setShareOwner($shareOwner); } $path = $this->getNode($share->getShareOwner(), (int) $data['file_source']); $share->setNode($path); if ($data['expiration'] !== null) { $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']); $share->setExpirationDate($expiration); } $share->setProviderId($this->identifier()); return $share; }
public function testAddGroup() { $group = $this->getUniqueId(); $_POST = ['groupid' => $group]; $result = $this->api->addGroup([]); $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertTrue($result->succeeded()); $this->assertTrue($this->groupManager->groupExists($group)); $this->groupManager->get($group)->delete(); }
/** * get all SubAdmins * @return array */ public function getAllSubAdmins() { $qb = $this->dbConn->getQueryBuilder(); $result = $qb->select('*')->from('group_admin')->execute(); $subadmins = []; while ($row = $result->fetch()) { $subadmins[] = ['user' => $this->userManager->get($row['uid']), 'group' => $this->groupManager->get($row['gid'])]; } return $subadmins; }
protected function setUp() { parent::setUp(); $user = $this->getMockBuilder('\\OCP\\IUser')->disableOriginalConstructor()->getMock(); $user->method('getUID')->willReturn(self::TEST_FILES_SHARING_API_USER1); $userSession = $this->getMockBuilder('\\OCP\\IUserSession')->disableOriginalConstructor()->getMock(); $userSession->method('getUser')->willReturn(selF::TEST_FILES_SHARING_API_USER1); $this->propagationManager = $this->getMockBuilder('OCA\\Files_Sharing\\Propagation\\PropagationManager')->disableOriginalConstructor()->getMock(); $this->groupManager = \OC::$server->getGroupManager(); $this->groupPropagationManager = new GroupPropagationManager($userSession, $this->groupManager, $this->propagationManager); $this->groupPropagationManager->globalSetup(); // since the sharing code is not mockable, we have to create a real folder $this->loginAsUser(self::TEST_FILES_SHARING_API_USER1); $view1 = new View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files'); $view1->mkdir('/folder'); $this->fileInfo = $view1->getFileInfo('/folder'); $this->recipientGroup = $this->groupManager->get(self::TEST_FILES_SHARING_API_GROUP1); $this->recipientUser = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER3); Share::shareItem('folder', $this->fileInfo['fileid'], Share::SHARE_TYPE_GROUP, $this->recipientGroup->getGID(), \OCP\Constants::PERMISSION_READ); $this->loginAsUser($this->recipientUser->getUID()); }
public function deleteGroup($parameters) { // Check it exists if (!$this->groupManager->groupExists($parameters['groupid'])) { return new OC_OCS_Result(null, 101); } else { if ($parameters['groupid'] === 'admin' || !$this->groupManager->get($parameters['groupid'])->delete()) { // Cannot delete admin group return new OC_OCS_Result(null, 102); } else { return new OC_OCS_Result(null, 100); } } }
/** * get all SubAdmins * @return array */ public function getAllSubAdmins() { $qb = $this->dbConn->getQueryBuilder(); $result = $qb->select('*')->from('group_admin')->execute(); $subadmins = []; while ($row = $result->fetch()) { $user = $this->userManager->get($row['uid']); $group = $this->groupManager->get($row['gid']); if (!is_null($user) && !is_null($group)) { $subadmins[] = ['user' => $user, 'group' => $group]; } } $result->closeCursor(); return $subadmins; }
/** * @param array $parameters * @return OC_OCS_Result */ public function getSubAdminsOfGroup($parameters) { $group = $parameters['groupid']; // Check group exists $targetGroup = $this->groupManager->get($group); if ($targetGroup === null) { return new OC_OCS_Result(null, 101, 'Group does not exist'); } $subadmins = $this->groupManager->getSubAdmin()->getGroupsSubAdmins($targetGroup); // New class returns IUser[] so convert back $uids = []; foreach ($subadmins as $user) { $uids[] = $user->getUID(); } return new OC_OCS_Result($uids); }
/** * Returns the list of members for a group-principal * * @param string $principal * @return string[] * @throws Exception */ public function getGroupMemberSet($principal) { $elements = explode('/', $principal); if ($elements[0] !== 'principals') { return []; } if ($elements[1] !== 'groups') { return []; } $name = $elements[2]; $group = $this->groupManager->get($name); if (is_null($group)) { return []; } return array_map(function ($user) { return $this->userToPrincipal($user); }, $group->getUsers()); }
/** * @return string[] */ protected function getUsersToNotify() { if ($this->users !== null) { return $this->users; } $notifyGroups = json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true); $this->users = []; foreach ($notifyGroups as $group) { $groupToNotify = $this->groupManager->get($group); if ($groupToNotify instanceof IGroup) { foreach ($groupToNotify->getUsers() as $user) { $this->users[$user->getUID()] = true; } } } $this->users = array_keys($this->users); return $this->users; }
public function testSubAdminOfGroupAlreadySubAdmin() { $user1 = $this->generateUsers(); $user2 = $this->generateUsers(); $this->userSession->setUser($user1); $this->groupManager->get('admin')->addUser($user1); $group1 = $this->groupManager->createGroup($this->getUniqueID()); //Make user2 subadmin of group1 $_POST['groupid'] = $group1->getGID(); $result = $this->api->addSubAdmin(['userid' => $user2->getUID()]); $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertTrue($result->succeeded()); //Make user2 subadmin of group1 again $_POST['groupid'] = $group1->getGID(); $result = $this->api->addSubAdmin(['userid' => $user2->getUID()]); $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertTrue($result->succeeded()); $group1->delete(); }
/** * @inheritdoc */ public function moveShare(\OCP\Share\IShare $share, $recipientId) { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { throw new \InvalidArgumentException('Can\'t change target of link share'); } if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) { throw new \InvalidArgumentException('Invalid recipient'); } if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $sharedWith = $this->groupManager->get($share->getSharedWith()); $recipient = $this->userManager->get($recipientId); if (!$sharedWith->inGroup($recipient)) { throw new \InvalidArgumentException('Invalid recipient'); } } list($providerId, ) = $this->splitFullId($share->getId()); $provider = $this->factory->getProvider($providerId); $provider->move($share, $recipientId); }
/** * returns the available groups * @param string $search a search string * @return \OC\Group\Group[] */ private function getGroups($search = '') { if ($this->isAdmin) { return $this->groupManager->search($search); } else { // FIXME: Remove static method call $groupIds = \OC_SubAdmin::getSubAdminsGroups($this->user); /* \OC_SubAdmin::getSubAdminsGroups() returns an array of GIDs, but this * method is expected to return an array with the GIDs as keys and group objects as * values, so we need to convert this information. */ $groups = array(); foreach ($groupIds as $gid) { $group = $this->groupManager->get($gid); if (!is_null($group)) { $groups[$gid] = $group; } } return $groups; } }
/** * Unshare a share from the recipient. If this is a group share * this means we need a special entry in the share db. * * @param \OCP\Share\IShare $share * @param string $recipient UserId of recipient * @throws BackendError * @throws ProviderException */ public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $group = $this->groupManager->get($share->getSharedWith()); $user = $this->userManager->get($recipient); if (!$group->inGroup($user)) { throw new ProviderException('Recipient not in receiving group'); } // Try to fetch user specific share $qb = $this->dbConn->getQueryBuilder(); $stmt = $qb->select('*')->from('share')->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))->execute(); $data = $stmt->fetch(); /* * Check if there already is a user specific group share. * If there is update it (if required). */ if ($data === false) { $qb = $this->dbConn->getQueryBuilder(); $type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder'; //Insert new share $qb->insert('share')->values(['share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP), 'share_with' => $qb->createNamedParameter($recipient), 'uid_owner' => $qb->createNamedParameter($share->getShareOwner()), 'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()), 'parent' => $qb->createNamedParameter($share->getId()), 'item_type' => $qb->createNamedParameter($type), 'item_source' => $qb->createNamedParameter($share->getNode()->getId()), 'file_source' => $qb->createNamedParameter($share->getNode()->getId()), 'file_target' => $qb->createNamedParameter($share->getTarget()), 'permissions' => $qb->createNamedParameter(0), 'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp())])->execute(); } else { if ($data['permissions'] !== 0) { // Update existing usergroup share $qb = $this->dbConn->getQueryBuilder(); $qb->update('share')->set('permissions', $qb->createNamedParameter(0))->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))->execute(); } } } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { if ($share->getSharedWith() !== $recipient) { throw new ProviderException('Recipient does not match'); } // We can just delete user and link shares $this->delete($share); } else { throw new ProviderException('Invalid shareType'); } } }
/** * @param array $parameters * @return OC_OCS_Result */ public function removeFromGroup($parameters) { // Check if user is logged in $user = $this->userSession->getUser(); if ($user === null) { return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED); } $group = !empty($parameters['_delete']['groupid']) ? $parameters['_delete']['groupid'] : null; if (is_null($group)) { return new OC_OCS_Result(null, 101); } // If they're not an admin, check they are a subadmin of the group in question if (!$this->groupManager->isInGroup($user->getUID(), 'admin') && !OC_SubAdmin::isSubAdminofGroup($user->getUID(), $group)) { return new OC_OCS_Result(null, 104); } // Check they aren't removing themselves from 'admin' or their 'subadmin; group if ($parameters['userid'] === $user->getUID()) { if ($this->groupManager->isInGroup($user->getUID(), 'admin')) { if ($group === 'admin') { return new OC_OCS_Result(null, 105, 'Cannot remove yourself from the admin group'); } } else { // Not an admin, check they are not removing themself from their subadmin group if (in_array($group, OC_SubAdmin::getSubAdminsGroups($user->getUID()))) { return new OC_OCS_Result(null, 105, 'Cannot remove yourself from this group as you are a SubAdmin'); } } } // Check if the group exists if (!$this->groupManager->groupExists($group)) { return new OC_OCS_Result(null, 102); } // Check if the user exists if (!$this->userManager->userExists($parameters['userid'])) { return new OC_OCS_Result(null, 103); } // Remove user from group $this->groupManager->get($group)->removeUser($this->userManager->get($parameters['userid'])); return new OC_OCS_Result(null, 100); }
/** * @param \OCP\Share\IShare $share * @return bool */ protected function canAccessShare(\OCP\Share\IShare $share) { // A file with permissions 0 can't be accessed by us. So Don't show it if ($share->getPermissions() === 0) { return false; } // Owner of the file and the sharer of the file can always get share if ($share->getShareOwner() === $this->currentUser->getUID() || $share->getSharedBy() === $this->currentUser->getUID()) { return true; } // If the share is shared with you (or a group you are a member of) if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() === $this->currentUser->getUID()) { return true; } if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $sharedWith = $this->groupManager->get($share->getSharedWith()); if ($sharedWith->inGroup($this->currentUser)) { return true; } } return false; }
/** * Removes a subadmin from a group * * @param array $parameters * @return OC_OCS_Result */ public function removeSubAdmin($parameters) { $group = $this->groupManager->get($parameters['_delete']['groupid']); $user = $this->userManager->get($parameters['userid']); $subAdminManager = $this->groupManager->getSubAdmin(); // Check if the user exists if ($user === null) { return new OC_OCS_Result(null, 101, 'User does not exist'); } // Check if the group exists if ($group === null) { return new OC_OCS_Result(null, 101, 'Group does not exist'); } // Check if they are a subadmin of this said group if (!$subAdminManager->isSubAdminofGroup($user, $group)) { return new OC_OCS_Result(null, 102, 'User is not a subadmin of this group'); } // Go if ($subAdminManager->deleteSubAdmin($user, $group)) { return new OC_OCS_Result(null, 100); } else { return new OC_OCS_Result(null, 103, 'Unknown error occurred'); } }
/** * 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']); 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) { /* * TODO: Clean this up, this should be set as password not sharedWith */ $share->setSharedWith($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?? $path = $this->userFolder->getById($data['file_source']); $path = $path[0]; $share->setPath($path); $owner = $path->getStorage()->getOwner('.'); if ($owner !== false) { $share->setShareOwner($this->userManager->get($owner)); } if ($data['expiration'] !== null) { $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']); $share->setExpirationDate($expiration); } return $share; }
/** * @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); }