Esempio n. 1
0
 /**
  * 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;
     }
 }
Esempio n. 2
0
 /**
  * Create a new \OCP\ITags instance and load tags from db.
  *
  * @see \OCP\ITags
  * @param string $type The type identifier e.g. 'contact' or 'event'.
  * @param array $defaultTags An array of default tags to be used if none are stored.
  * @param boolean $includeShared Whether to include tags for items shared with this user by others.
  * @param string $userId user for which to retrieve the tags, defaults to the currently
  * logged in user
  * @return \OCP\ITags
  */
 public function load($type, $defaultTags = array(), $includeShared = false, $userId = null)
 {
     if (is_null($userId)) {
         $userId = $this->userSession->getUser()->getUId();
     }
     return new Tags($this->mapper, $userId, $type, $defaultTags, $includeShared);
 }
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  *
  * @return TemplateResponse
  */
 public function index()
 {
     $userId = $this->userSession->getUser()->getUID();
     $appVersion = $this->config->getAppValue($this->appName, 'installed_version');
     $defaultView = $this->config->getUserValue($userId, $this->appName, 'currentView', 'month');
     return new TemplateResponse('calendar', 'main', ['appVersion' => $appVersion, 'defaultView' => $defaultView]);
 }
Esempio n. 4
0
 /**
  * @NoAdminRequired
  * @UseSession
  *
  * @param string $oldPassword
  * @param string $newPassword
  * @return DataResponse
  */
 public function updatePrivateKeyPassword($oldPassword, $newPassword)
 {
     $result = false;
     $uid = $this->userSession->getUser()->getUID();
     $errorMessage = $this->l->t('Could not update the private key password.');
     //check if password is correct
     $passwordCorrect = $this->userManager->checkPassword($uid, $newPassword);
     if ($passwordCorrect !== false) {
         $encryptedKey = $this->keyManager->getPrivateKey($uid);
         $decryptedKey = $this->crypt->decryptPrivateKey($encryptedKey, $oldPassword);
         if ($decryptedKey) {
             $encryptedKey = $this->crypt->symmetricEncryptFileContent($decryptedKey, $newPassword);
             $header = $this->crypt->generateHeader();
             if ($encryptedKey) {
                 $this->keyManager->setPrivateKey($uid, $header . $encryptedKey);
                 $this->session->setPrivateKey($decryptedKey);
                 $result = true;
             }
         } else {
             $errorMessage = $this->l->t('The old password was not correct, please try again.');
         }
     } else {
         $errorMessage = $this->l->t('The current log-in password was not correct, please try again.');
     }
     if ($result === true) {
         $this->session->setStatus(Session::INIT_SUCCESSFUL);
         return new DataResponse(['message' => (string) $this->l->t('Private key password successfully updated.')]);
     } else {
         return new DataResponse(['message' => (string) $errorMessage], Http::STATUS_BAD_REQUEST);
     }
 }
Esempio n. 5
0
 /**
  * @return IUser|null
  */
 protected function getUser()
 {
     if ($this->user) {
         return $this->user;
     }
     return $this->userSession->getUser();
 }
Esempio n. 6
0
 /**
  * returns an array of users in the group specified
  *
  * @param array $parameters
  * @return OC_OCS_Result
  */
 public function getGroup($parameters)
 {
     // Check if user is logged in
     $user = $this->userSession->getUser();
     if ($user === null) {
         return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED);
     }
     $groupId = $parameters['groupid'];
     // Check the group exists
     if (!$this->groupManager->groupExists($groupId)) {
         return new OC_OCS_Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The requested group could not be found');
     }
     $isSubadminOfGroup = false;
     $group = $this->groupManager->get($groupId);
     if ($group !== null) {
         $isSubadminOfGroup = $this->groupManager->getSubAdmin()->isSubAdminofGroup($user, $group);
     }
     // Check subadmin has access to this group
     if ($this->groupManager->isAdmin($user->getUID()) || $isSubadminOfGroup) {
         $users = $this->groupManager->get($groupId)->getUsers();
         $users = array_map(function ($user) {
             /** @var IUser $user */
             return $user->getUID();
         }, $users);
         $users = array_values($users);
         return new OC_OCS_Result(['users' => $users]);
     } else {
         return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED, 'User does not have access to specified group');
     }
 }
 /**
  * Returns whether the currently logged in user is an administrator
  */
 private function isAdmin()
 {
     $user = $this->userSession->getUser();
     if ($user !== null) {
         return $this->groupManager->isAdmin($user->getUID());
     }
     return false;
 }
 /**
  * @NoAdminRequired
  *
  * @param string $pattern
  * @param bool $filterGroups
  * @return DataResponse
  */
 public function index($pattern = '', $filterGroups = false)
 {
     $groupPattern = $filterGroups ? $pattern : '';
     $groupsInfo = new \OC\Group\MetaData($this->userSession->getUser()->getUID(), $this->isAdmin, $this->groupManager);
     $groupsInfo->setSorting($groupsInfo::SORT_USERCOUNT);
     list($adminGroups, $groups) = $groupsInfo->get($groupPattern, $pattern);
     return new DataResponse(array('data' => array('adminGroups' => $adminGroups, 'groups' => $groups)));
 }
Esempio n. 9
0
 /**
  * Updates the tags of the specified file path.
  * The passed tags are absolute, which means they will
  * replace the actual tag selection.
  *
  * @param array $tagName tag name to filter by
  * @return FileInfo[] list of matching files
  * @throws \Exception if the tag does not exist
  */
 public function getFilesByTag($tagName)
 {
     $nodes = $this->homeFolder->searchByTag($tagName, $this->userSession->getUser()->getUId());
     foreach ($nodes as &$node) {
         $node = $node->getFileInfo();
     }
     return $nodes;
 }
 protected function manipulateStorageConfig(StorageConfig $storage)
 {
     /** @var AuthMechanism */
     $authMechanism = $storage->getAuthMechanism();
     $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
     /** @var Backend */
     $backend = $storage->getBackend();
     $backend->manipulateStorageConfig($storage, $this->userSession->getUser());
 }
Esempio n. 11
0
 /**
  * @NoAdminRequired
  * @UseSession
  *
  * @return RedirectResponse
  */
 public function logout()
 {
     $loginToken = $this->request->getCookie('oc_token');
     if (!is_null($loginToken)) {
         $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
     }
     $this->userSession->logout();
     return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
 }
 /**
  * get a config value
  *
  * @return JSONResponse
  *
  * @NoAdminRequired
  */
 public function getView()
 {
     $userId = $this->userSession->getUser()->getUID();
     $app = $this->appName;
     try {
         $view = $this->config->getUserValue($userId, $app, 'currentView', 'month');
     } catch (\Exception $e) {
         return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR);
     }
     return new JSONResponse(['value' => $view]);
 }
Esempio n. 13
0
 /**
  * Create a new \OCP\ITags instance and load tags from db.
  *
  * @see \OCP\ITags
  * @param string $type The type identifier e.g. 'contact' or 'event'.
  * @param array $defaultTags An array of default tags to be used if none are stored.
  * @param boolean $includeShared Whether to include tags for items shared with this user by others.
  * @param string $userId user for which to retrieve the tags, defaults to the currently
  * logged in user
  * @return \OCP\ITags
  */
 public function load($type, $defaultTags = array(), $includeShared = false, $userId = null)
 {
     if (is_null($userId)) {
         $user = $this->userSession->getUser();
         if ($user === null) {
             // nothing we can do without a user
             return null;
         }
         $userId = $this->userSession->getUser()->getUId();
     }
     return new Tags($this->mapper, $userId, $type, $defaultTags, $includeShared);
 }
Esempio n. 14
0
 /**
  * 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);
 }
Esempio n. 15
0
 /**
  * become another user
  * @param string $userid
  * @UseSession
  * @return JSONResponse
  */
 public function impersonate($userid)
 {
     $oldUserId = $this->userSession->getUser()->getUID();
     $this->logger->warning("User {$oldUserId} trying to impersonate user {$userid}", ['app' => 'impersonate']);
     $user = $this->userManager->get($userid);
     if ($user === null) {
         return new JSONResponse("No user found for {$userid}", Http::STATUS_NOT_FOUND);
     } else {
         $this->logger->warning("changing to user {$userid}", ['app' => 'impersonate']);
         $this->userSession->setUser($user);
     }
     return new JSONResponse();
 }
Esempio n. 16
0
 /**
  * @param ILogger $logger
  * @param IUserSession $userSession
  * @param IConfig $config
  */
 public function __construct(ILogger $logger, IUserSession $userSession, IConfig $config)
 {
     $this->logger = $logger;
     $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser() : false;
     $this->config = $config;
     $this->supportedKeyFormats = ['hash', 'password'];
 }
Esempio n. 17
0
 /**
  * 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();
     if ($userId !== $id && !$this->isAdmin && !$this->subAdminFactory->isUserAccessible($userId, $id)) {
         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);
     }
     $user = $this->userManager->get($id);
     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);
 }
 /**
  * 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]);
 }
Esempio n. 19
0
 /**
  * Updates the tags of the specified file path.
  * The passed tags are absolute, which means they will
  * replace the actual tag selection.
  *
  * @param array $tagName tag name to filter by
  * @return FileInfo[] list of matching files
  * @throws \Exception if the tag does not exist
  */
 public function getFilesByTag($tagName)
 {
     $nodes = $this->homeFolder->searchByTag($tagName, $this->userSession->getUser()->getUId());
     $fileInfos = [];
     foreach ($nodes as $node) {
         try {
             /** @var \OC\Files\Node\Node $node */
             $fileInfos[] = $node->getFileInfo();
         } catch (\Exception $e) {
             // FIXME Should notify the user, when this happens
             // Can not get FileInfo, maybe the connection to the external
             // storage is interrupted.
         }
     }
     return $fileInfos;
 }
Esempio n. 20
0
 /**
  * Creates a new comment
  *
  * @param string $objectType e.g. "files"
  * @param string $objectId e.g. the file id
  * @param string $data JSON encoded string containing the properties of the tag to create
  * @param string $contentType content type of the data
  * @return IComment newly created comment
  *
  * @throws BadRequest if a field was missing
  * @throws UnsupportedMediaType if the content type is not supported
  */
 private function createComment($objectType, $objectId, $data, $contentType = 'application/json')
 {
     if (explode(';', $contentType)[0] === 'application/json') {
         $data = json_decode($data, true);
     } else {
         throw new UnsupportedMediaType();
     }
     $actorType = $data['actorType'];
     $actorId = null;
     if ($actorType === 'users') {
         $user = $this->userSession->getUser();
         if (!is_null($user)) {
             $actorId = $user->getUID();
         }
     }
     if (is_null($actorId)) {
         throw new BadRequest('Invalid actor "' . $actorType . '"');
     }
     try {
         $comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId);
         $comment->setMessage($data['message']);
         $comment->setVerb($data['verb']);
         $this->commentsManager->save($comment);
         return $comment;
     } catch (\InvalidArgumentException $e) {
         throw new BadRequest('Invalid input values', 0, $e);
     }
 }
Esempio n. 21
0
 /**
  * @param ILogger $logger
  * @param IUserSession $userSession
  * @param Crypt $crypt
  * @param KeyManager $keyManager
  */
 public function __construct(ILogger $logger, IUserSession $userSession, Crypt $crypt, KeyManager $keyManager)
 {
     $this->logger = $logger;
     $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
     $this->crypt = $crypt;
     $this->keyManager = $keyManager;
 }
 /**
  * constructor of the controller
  *
  * @param string $appName
  * @param IRequest $request
  * @param ILogger $logger
  * @param IUserSession $userSession
  * @param CurrentUserSettings $userSettings
  */
 public function __construct($appName, IRequest $request, ILogger $logger, IUserSession $userSession, CurrentUserSettings $userSettings)
 {
     parent::__construct($appName, $request);
     $this->logger = $logger;
     $this->user = $userSession->getUser();
     $this->userSettings = $userSettings;
 }
Esempio n. 23
0
 /**
  * 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 ($this->entityTypeCollections !== null) {
         return;
     }
     $user = $this->userSession->getUser();
     if (is_null($user)) {
         throw new NotAuthenticated();
     }
     $event = new CommentsEntityEvent(CommentsEntityEvent::EVENT_ENTITY);
     $this->dispatcher->dispatch(CommentsEntityEvent::EVENT_ENTITY, $event);
     $this->entityTypeCollections = [];
     foreach ($event->getEntityCollections() as $entity => $entityExistsFunction) {
         $this->entityTypeCollections[$entity] = new EntityTypeCollection($entity, $this->commentsManager, $this->userManager, $this->userSession, $this->logger, $entityExistsFunction);
     }
 }
Esempio n. 24
0
 /**
  * @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);
         }
     }
 }
Esempio n. 25
0
 /**
  * @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()]]);
         }
     }
 }
Esempio n. 26
0
 /**
  * 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);
     }
 }
Esempio n. 27
0
 /**
  * Returns a list of properties for this nodes.
  *
  * The properties list is a list of propertynames the client requested,
  * encoded in clark-notation {xmlnamespace}tagname
  *
  * If the array is empty, it means 'all properties' were requested.
  *
  * Note that it's fine to liberally give properties back, instead of
  * conforming to the list of requested properties.
  * The Server class will filter out the extra.
  *
  * @param array $properties
  * @return array
  */
 function getProperties($properties)
 {
     $properties = array_keys($this->properties);
     $result = [];
     foreach ($properties as $property) {
         $getter = $this->properties[$property];
         if (method_exists($this->comment, $getter)) {
             $result[$property] = $this->comment->{$getter}();
         }
     }
     if ($this->comment->getActorType() === 'users') {
         $user = $this->userManager->get($this->comment->getActorId());
         $displayName = is_null($user) ? null : $user->getDisplayName();
         $result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName;
     }
     $unread = null;
     $user = $this->userSession->getUser();
     if (!is_null($user)) {
         $readUntil = $this->commentsManager->getReadMark($this->comment->getObjectType(), $this->comment->getObjectId(), $user);
         if (is_null($readUntil)) {
             $unread = 'true';
         } else {
             $unread = $this->comment->getCreationDateTime() > $readUntil;
             // re-format for output
             $unread = $unread ? 'true' : 'false';
         }
     }
     $result[self::PROPERTY_NAME_UNREAD] = $unread;
     return $result;
 }
Esempio n. 28
0
 /**
  * Redirects to the file list and highlight the given file id
  *
  * @param string $fileId file id to show
  * @return RedirectResponse redirect response or not found response
  * @throws \OCP\Files\NotFoundException
  *
  * @NoCSRFRequired
  * @NoAdminRequired
  */
 public function showFile($fileId)
 {
     $uid = $this->userSession->getUser()->getUID();
     $baseFolder = $this->rootFolder->get($uid . '/files/');
     $files = $baseFolder->getById($fileId);
     $params = [];
     if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
         $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
         $files = $baseFolder->getById($fileId);
         $params['view'] = 'trashbin';
     }
     if (!empty($files)) {
         $file = current($files);
         if ($file instanceof Folder) {
             // set the full path to enter the folder
             $params['dir'] = $baseFolder->getRelativePath($file->getPath());
         } else {
             // set parent path as dir
             $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
             // and scroll to the entry
             $params['scrollto'] = $file->getName();
         }
         return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
     }
     throw new \OCP\Files\NotFoundException();
 }
Esempio n. 29
0
 /**
  * @NoAdminRequired
  *
  * @param array $crop
  * @return DataResponse
  */
 public function postCroppedAvatar($crop)
 {
     $userId = $this->userSession->getUser()->getUID();
     if (is_null($crop)) {
         return new DataResponse(['data' => ['message' => $this->l->t("No crop data provided")]], Http::STATUS_BAD_REQUEST);
     }
     if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
         return new DataResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]], Http::STATUS_BAD_REQUEST);
     }
     $tmpAvatar = $this->cache->get('tmpAvatar');
     if (is_null($tmpAvatar)) {
         return new DataResponse(['data' => ['message' => $this->l->t("No temporary profile picture available, try again")]], Http::STATUS_BAD_REQUEST);
     }
     $image = new \OC_Image($tmpAvatar);
     $image->crop($crop['x'], $crop['y'], round($crop['w']), round($crop['h']));
     try {
         $avatar = $this->avatarManager->getAvatar($userId);
         $avatar->set($image);
         // Clean up
         $this->cache->remove('tmpAvatar');
         return new DataResponse(['status' => 'success']);
     } catch (\OC\NotSquareException $e) {
         return new DataResponse(['data' => ['message' => $this->l->t('Crop is not square')]], Http::STATUS_BAD_REQUEST);
     } catch (\Exception $e) {
         return new DataResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_BAD_REQUEST);
     }
 }
Esempio n. 30
0
 /**
  * @param array $parameters
  * @throws InvalidFilterException when the filter is invalid
  * @throws \OutOfBoundsException when no user is given
  */
 protected function readParameters(array $parameters)
 {
     $this->filter = isset($parameters['filter']) && is_string($parameters['filter']) ? (string) $parameters['filter'] : 'all';
     if ($this->filter !== $this->data->validateFilter($this->filter)) {
         throw new InvalidFilterException();
     }
     $this->since = (int) $this->request->getParam('since', 0);
     $this->limit = (int) $this->request->getParam('limit', 50);
     $this->loadPreviews = $this->request->getParam('previews', 'false') === 'true';
     $this->objectType = (string) $this->request->getParam('object_type', '');
     $this->objectId = (int) $this->request->getParam('object_id', 0);
     $this->sort = (string) $this->request->getParam('sort', '');
     $this->sort = in_array($this->sort, ['asc', 'desc']) ? $this->sort : 'desc';
     if ($this->objectType !== '' && $this->objectId === 0 || $this->objectType === '' && $this->objectId !== 0) {
         // Only allowed together
         $this->objectType = '';
         $this->objectId = 0;
     }
     $user = $this->userSession->getUser();
     if ($user instanceof IUser) {
         $this->user = $user->getUID();
     } else {
         // No user logged in
         throw new \OutOfBoundsException();
     }
 }