/** * Read legacy config data * * @return array list of mount configs */ protected function readLegacyConfig() { // read global config $data = parent::readLegacyConfig(); $userId = $this->getUser()->getUID(); // don't use array_filter() with ARRAY_FILTER_USE_KEY, it's PHP 5.6+ if (isset($data[\OC_Mount_Config::MOUNT_TYPE_USER])) { $newData = []; foreach ($data[\OC_Mount_Config::MOUNT_TYPE_USER] as $key => $value) { if (strtolower($key) === strtolower($userId) || $key === 'all') { $newData[$key] = $value; } } $data[\OC_Mount_Config::MOUNT_TYPE_USER] = $newData; } if (isset($data[\OC_Mount_Config::MOUNT_TYPE_GROUP])) { $newData = []; foreach ($data[\OC_Mount_Config::MOUNT_TYPE_GROUP] as $key => $value) { if ($this->groupManager->isInGroup($userId, $key)) { $newData[$key] = $value; } } $data[\OC_Mount_Config::MOUNT_TYPE_GROUP] = $newData; } return $data; }
/** * Check if an app is enabled for user * * @param string $appId * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used * @return bool */ public function isEnabledForUser($appId, $user = null) { if (is_null($user)) { $user = $this->userSession->getUser(); } $installedApps = $this->getInstalledApps(); if (isset($installedApps[$appId])) { $enabled = $installedApps[$appId]; if ($enabled === 'yes') { return true; } elseif (is_null($user)) { return false; } else { $groupIds = json_decode($enabled); $userGroups = $this->groupManager->getUserGroupIds($user); foreach ($userGroups as $groupId) { if (array_search($groupId, $groupIds) !== false) { return true; } } return false; } } else { return false; } }
protected function tearDown() { foreach ($this->users as $user) { $user->delete(); } $this->groupManager->get('admin')->delete(); parent::tearDown(); }
/** * Returns whether the currently logged in user is an administrator * * @return bool true if the user is an admin */ private function isAdmin() { $user = $this->userSession->getUser(); if ($user !== null) { return $this->groupManager->isAdmin($user->getUID()); } return false; }
/** * @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 readDBConfig() { $userMounts = $this->dbConfig->getAdminMountsFor(DBConfigService::APPLICABLE_TYPE_USER, $this->getUser()->getUID()); $globalMounts = $this->dbConfig->getAdminMountsFor(DBConfigService::APPLICABLE_TYPE_GLOBAL, null); $groups = $this->groupManager->getUserGroupIds($this->getUser()); if (is_array($groups) && count($groups) !== 0) { $groupMounts = $this->dbConfig->getAdminMountsForMultiple(DBConfigService::APPLICABLE_TYPE_GROUP, $groups); } else { $groupMounts = []; } return array_merge($userMounts, $groupMounts, $globalMounts); }
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() . '"'); } }
/** * Creates a subadmin * * @param array $parameters * @return OC_OCS_Result */ public function addSubAdmin($parameters) { $group = $_POST['groupid']; $user = $parameters['userid']; // Check if the user exists if (!$this->userManager->userExists($user)) { return new OC_OCS_Result(null, 101, 'User does not exist'); } // Check if group exists if (!$this->groupManager->groupExists($group)) { return new OC_OCS_Result(null, 102, 'Group:' . $group . ' does not exist'); } // Check if trying to make subadmin of admin group if (strtolower($group) === 'admin') { return new OC_OCS_Result(null, 103, 'Cannot create subadmins for admin group'); } // We cannot be subadmin twice if (OC_Subadmin::isSubAdminOfGroup($user, $group)) { return new OC_OCS_Result(null, 100); } // Go if (OC_Subadmin::createSubAdmin($user, $group)) { return new OC_OCS_Result(null, 100); } else { return new OC_OCS_Result(null, 103, 'Unknown error occured'); } }
/** * @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); }
/** * Creates a new tag * * @param string $data JSON encoded string containing the properties of the tag to create * @param string $contentType content type of the data * @return ISystemTag newly created system tag * * @throws BadRequest if a field was missing * @throws Conflict if a tag with the same properties already exists * @throws UnsupportedMediaType if the content type is not supported */ private function createTag($data, $contentType = 'application/json') { if (explode(';', $contentType)[0] === 'application/json') { $data = json_decode($data, true); } else { throw new UnsupportedMediaType(); } if (!isset($data['name'])) { throw new BadRequest('Missing "name" attribute'); } $tagName = $data['name']; $userVisible = true; $userAssignable = true; if (isset($data['userVisible'])) { $userVisible = (bool) $data['userVisible']; } if (isset($data['userAssignable'])) { $userAssignable = (bool) $data['userAssignable']; } if ($userVisible === false || $userAssignable === false) { if (!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) { throw new BadRequest('Not sufficient permissions'); } } try { return $this->tagManager->createTag($tagName, $userVisible, $userAssignable); } catch (TagAlreadyExistsException $e) { throw new Conflict('Tag already exists', 0, $e); } }
/** * 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); } }
/** * 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]); }
/** * @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); } } }
/** * Set the mail address of a user * * @NoAdminRequired * @NoSubadminRequired * * @param string $id * @param string $mailAddress * @return DataResponse */ public function setMailAddress($id, $mailAddress) { $userId = $this->userSession->getUser()->getUID(); $user = $this->userManager->get($id); if ($userId !== $id && !$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Forbidden'))), Http::STATUS_FORBIDDEN); } if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Invalid mail address'))), Http::STATUS_UNPROCESSABLE_ENTITY); } if (!$user) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Invalid user'))), Http::STATUS_UNPROCESSABLE_ENTITY); } // this is the only permission a backend provides and is also used // for the permission of setting a email address if (!$user->canChangeDisplayName()) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Unable to change mail address'))), Http::STATUS_FORBIDDEN); } // delete user value if email address is empty if ($mailAddress === '') { $this->config->deleteUserValue($id, 'settings', 'email'); } else { $this->config->setUserValue($id, 'settings', 'email', $mailAddress); } return new DataResponse(array('status' => 'success', 'data' => array('username' => $id, 'mailAddress' => $mailAddress, 'message' => (string) $this->l10n->t('Email saved'))), Http::STATUS_OK); }
public function tearDown() { $this->groupManager->removeListener('\\OC\\Group', 'preAddUser', [$this, 'onPreProcessUser']); $this->groupManager->removeListener('\\OC\\Group', 'postAddUser', [$this, 'onPostAddUser']); $this->groupManager->removeListener('\\OC\\Group', 'preRemoveUser', [$this, 'onPreProcessUser']); $this->groupManager->removeListener('\\OC\\Group', 'postRemoveUser', [$this, 'onPostRemoveUser']); }
public function testGetShareByIdGroupShare() { $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share')->values(['share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_GROUP), '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)]); $this->assertEquals(1, $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(); $storage = $this->getMock('OC\\Files\\Storage\\Storage'); $storage->expects($this->once())->method('getOwner')->willReturn('shareOwner'); $path = $this->getMock('OCP\\Files\\Folder'); $path->expects($this->once())->method('getStorage')->wilLReturn($storage); $this->userFolder->expects($this->once())->method('getById')->with(42)->willReturn([$path]); $sharedWith = $this->getMock('OCP\\IGroup'); $sharedBy = $this->getMock('OCP\\IUser'); $shareOwner = $this->getMock('OCP\\IUser'); $this->userManager->method('get')->will($this->returnValueMap([['sharedBy', $sharedBy], ['shareOwner', $shareOwner]])); $this->groupManager->expects($this->once())->method('get')->with('sharedWith')->willReturn($sharedWith); $share = $this->provider->getShareById($id); $this->assertEquals($id, $share->getId()); $this->assertEquals(\OCP\Share::SHARE_TYPE_GROUP, $share->getShareType()); $this->assertEquals($sharedWith, $share->getSharedWith()); $this->assertEquals($sharedBy, $share->getSharedBy()); $this->assertEquals($shareOwner, $share->getShareOwner()); $this->assertEquals($path, $share->getPath()); $this->assertEquals(13, $share->getPermissions()); $this->assertEquals(null, $share->getToken()); $this->assertEquals(null, $share->getExpirationDate()); $this->assertEquals('myTarget', $share->getTarget()); }
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); } }
/** * 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; }
/** * 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()]]); } } }
/** * Copied from \OC_Util::isSharingDisabledForUser * * TODO: Deprecate fuction from OC_Util * * @param string $userId * @return bool */ public function sharingDisabledForUser($userId) { if ($userId === null) { return false; } if (isset($this->sharingDisabledForUsersCache[$userId])) { return $this->sharingDisabledForUsersCache[$userId]; } if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') { $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); $excludedGroups = json_decode($groupsList); if (is_null($excludedGroups)) { $excludedGroups = explode(',', $groupsList); $newValue = json_encode($excludedGroups); $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue); } $user = $this->userManager->get($userId); $usersGroups = $this->groupManager->getUserGroupIds($user); if (!empty($usersGroups)) { $remainingGroups = array_diff($usersGroups, $excludedGroups); // if the user is only in groups which are disabled for sharing then // sharing is also disabled for the user if (empty($remainingGroups)) { $this->sharingDisabledForUsersCache[$userId] = true; return true; } } } $this->sharingDisabledForUsersCache[$userId] = false; return false; }
/** * Detect unmerged received shares and merge them properly */ private function fixUnmergedShares(IOutput $out, IUser $user) { $groups = $this->groupManager->getUserGroupIds($user); if (empty($groups)) { // user is in no groups, so can't have received group shares return; } $subSharesByItemSource = $this->getSharesWithUser(DefaultShareProvider::SHARE_TYPE_USERGROUP, [$user->getUID()]); if (empty($subSharesByItemSource)) { // nothing to repair for this user return; } $groupSharesByItemSource = $this->getSharesWithUser(Constants::SHARE_TYPE_GROUP, $groups); if (empty($groupSharesByItemSource)) { // shouldn't happen, those invalid shares must be cleant already by RepairInvalidShares return; } // because sometimes one wants to give the user more permissions than the group share $userSharesByItemSource = $this->getSharesWithUser(Constants::SHARE_TYPE_USER, [$user->getUID()]); foreach ($groupSharesByItemSource as $itemSource => $groupShares) { if (!isset($subSharesByItemSource[$itemSource])) { // no subshares for this item source, skip it continue; } $subShares = $subSharesByItemSource[$itemSource]; if (isset($userSharesByItemSource[$itemSource])) { // add it to the subshares to get a similar treatment $subShares = array_merge($subShares, $userSharesByItemSource[$itemSource]); } $this->fixThisShare($groupShares, $subShares); } }
/** * @param string $enabled * @param IUser $user * @return bool */ private function checkAppForUser($enabled, $user) { if ($enabled === 'yes') { return true; } elseif (is_null($user)) { return false; } else { if (empty($enabled)) { return false; } $groupIds = json_decode($enabled); if (!is_array($groupIds)) { $jsonError = json_last_error(); \OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']); return false; } $userGroups = $this->groupManager->getUserGroupIds($user); foreach ($userGroups as $groupId) { if (array_search($groupId, $groupIds) !== false) { return true; } } return false; } }
/** * Read legacy config data * * @return array list of mount configs */ protected function readLegacyConfig() { // read global config $data = parent::readLegacyConfig(); $userId = $this->getUser()->getUID(); if (isset($data[\OC_Mount_Config::MOUNT_TYPE_USER])) { $data[\OC_Mount_Config::MOUNT_TYPE_USER] = array_filter($data[\OC_Mount_Config::MOUNT_TYPE_USER], function ($key) use($userId) { return strtolower($key) === strtolower($userId) || $key === 'all'; }, ARRAY_FILTER_USE_KEY); } if (isset($data[\OC_Mount_Config::MOUNT_TYPE_GROUP])) { $data[\OC_Mount_Config::MOUNT_TYPE_GROUP] = array_filter($data[\OC_Mount_Config::MOUNT_TYPE_GROUP], function ($key) use($userId) { return $this->groupManager->isInGroup($userId, $key); }, ARRAY_FILTER_USE_KEY); } return $data; }
/** * @dataProvider dataIndex * @param bool $isAdmin */ public function testIndex($isAdmin) { $this->groupManager->expects($this->once())->method('isAdmin')->with('author')->willReturn($isAdmin); $controller = $this->getController(); $response = $controller->index(); $this->assertInstanceOf('OCP\\AppFramework\\Http\\TemplateResponse', $response); $this->assertSame(['is_admin' => $isAdmin], $response->getParams()); }
public function testDeleteGroup() { $group = $this->groupManager->createGroup($this->getUniqueId()); $result = $this->api->deleteGroup(['groupid' => $group->getGID()]); $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertTrue($result->succeeded()); $this->assertFalse($this->groupManager->groupExists($group->getGID())); }
/** * 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 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(); $storage = $this->getMock('OC\\Files\\Storage\\Storage'); $storage->method('getOwner')->willReturn('shareOwner'); $path1 = $this->getMock('OCP\\Files\\File'); $path1->expects($this->once())->method('getStorage')->willReturn($storage); $path2 = $this->getMock('OCP\\Files\\Folder'); $path2->expects($this->once())->method('getStorage')->willReturn($storage); $this->userFolder->method('getById')->will($this->returnValueMap([[1, [$path1]], [3, [$path2]]])); $shareOwner = $this->getMock('OCP\\IUser'); $user1 = $this->getMock('OCP\\IUser'); $user2 = $this->getMock('OCP\\IUser'); $user3 = $this->getMock('OCP\\IUser'); $this->userManager->method('get')->will($this->returnValueMap([['shareOwner', $shareOwner], ['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($path1, $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($path2, $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()); }
public function testDeleteGroup() { $this->groupManager->method('groupExists')->with('ExistingGroup')->willReturn('true'); $group = $this->createGroup('ExistingGroup'); $this->groupManager->method('get')->with('ExistingGroup')->willReturn($group); $group->expects($this->once())->method('delete')->willReturn(true); $result = $this->api->deleteGroup(['groupid' => 'ExistingGroup']); $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertTrue($result->succeeded()); }