public function testUpdateFileTags() { $tag1 = 'tag1'; $tag2 = 'tag2'; $subdir = $this->root->newFolder('subdir'); $testFile = $subdir->newFile('test.txt'); $testFile->putContent('test contents'); $fileId = $testFile->getId(); // set tags $this->tagService->updateFileTags('subdir/test.txt', array($tag1, $tag2)); $this->assertEquals(array($fileId), $this->tagger->getIdsForTag($tag1)); $this->assertEquals(array($fileId), $this->tagger->getIdsForTag($tag2)); // remove tag $result = $this->tagService->updateFileTags('subdir/test.txt', array($tag2)); $this->assertEquals(array(), $this->tagger->getIdsForTag($tag1)); $this->assertEquals(array($fileId), $this->tagger->getIdsForTag($tag2)); // clear tags $result = $this->tagService->updateFileTags('subdir/test.txt', array()); $this->assertEquals(array(), $this->tagger->getIdsForTag($tag1)); $this->assertEquals(array(), $this->tagger->getIdsForTag($tag2)); // non-existing file $caught = false; try { $this->tagService->updateFileTags('subdir/unexist.txt', array($tag1)); } catch (\OCP\Files\NotFoundException $e) { $caught = true; } $this->assertTrue($caught); $subdir->delete(); }
/** * 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; }
/** * converts a path relative to the users files folder * eg /user/files/foo.txt -> /foo.txt * @param string $path * @return string relative path */ protected function getRelativePath($path) { if (!isset(self::$userFolderCache)) { $user = \OC::$server->getUserSession()->getUser()->getUID(); self::$userFolderCache = \OC::$server->getUserFolder($user); } return self::$userFolderCache->getRelativePath($path); }
public function testSetAvatar() { $oldFile = $this->getMock('\\OCP\\Files\\File'); $this->folder->method('get')->will($this->returnValueMap([['avatar.jpg', $oldFile], ['avatar.png', $oldFile]])); $oldFile->expects($this->exactly(2))->method('delete'); $newFile = $this->getMock('\\OCP\\Files\\File'); $this->folder->expects($this->once())->method('newFile')->with('avatar.png')->willReturn($newFile); $image = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $newFile->expects($this->once())->method('putContent')->with($image->data()); $this->avatar->set($image->data()); }
/** * Returns a parsed configuration * * @param Folder $folder * @param string $configName * * @return array|string[] * * @throws ServiceException */ private function parseConfig($folder, $configName) { try { /** @var File $configFile */ $configFile = $folder->get($configName); $rawConfig = $configFile->getContent(); $saneConfig = $this->bomFixer($rawConfig); $parsedConfig = Yaml::parse($saneConfig); //\OC::$server->getLogger()->debug("rawConfig : {path}", ['path' => $rawConfig]); } catch (\Exception $exception) { $errorMessage = "Problem while parsing the configuration file"; throw new ServiceException($errorMessage); } return $parsedConfig; }
/** * 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?? $path = $this->userFolder->getById((int) $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; }
/** * 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; }
/** * @NoAdminRequired * * @param int $accountId * @param string $folderId * @param string $subject * @param string $body * @param string $to * @param string $cc * @param string $bcc * @param int $draftUID * @param string $messageId * @param mixed $attachments * @return JSONResponse */ public function send($accountId, $folderId, $subject, $body, $to, $cc, $bcc, $draftUID, $messageId, $attachments) { $account = $this->accountService->find($this->currentUserId, $accountId); if ($account instanceof UnifiedAccount) { list($account, $folderId, $messageId) = $account->resolve($messageId); } if (!$account instanceof Account) { return new JSONResponse(['message' => 'Invalid account'], Http::STATUS_BAD_REQUEST); } $mailbox = null; if (!is_null($folderId) && !is_null($messageId)) { // Reply $message = $account->newReplyMessage(); $mailbox = $account->getMailbox(base64_decode($folderId)); $repliedMessage = $mailbox->getMessage($messageId); if (is_null($subject)) { // No subject set – use the original one $message->setSubject($repliedMessage->getSubject()); } else { $message->setSubject($subject); } if (is_null($to)) { $message->setTo($repliedMessage->getToList()); } else { $message->setTo(Message::parseAddressList($to)); } $message->setRepliedMessage($repliedMessage); } else { // New message $message = $account->newMessage(); $message->setTo(Message::parseAddressList($to)); $message->setSubject($subject ?: ''); } $message->setFrom($account->getEMailAddress()); $message->setCC(Message::parseAddressList($cc)); $message->setBcc(Message::parseAddressList($bcc)); $message->setContent($body); if (is_array($attachments)) { foreach ($attachments as $attachment) { $fileName = $attachment['fileName']; if ($this->userFolder->nodeExists($fileName)) { $f = $this->userFolder->get($fileName); if ($f instanceof File) { $message->addAttachmentFromFiles($f); } } } } try { $account->sendMessage($message, $draftUID); // in case of reply we flag the message as answered if ($message instanceof ReplyMessage) { $mailbox->setMessageFlag($messageId, Horde_Imap_Client::FLAG_ANSWERED, true); } } catch (\Horde_Exception $ex) { $this->logger->error('Sending mail failed: ' . $ex->getMessage()); return new JSONResponse(array('message' => $ex->getMessage()), Http::STATUS_INTERNAL_SERVER_ERROR); } return new JSONResponse(); }
/** * @NoAdminRequired * @NoCSRFRequired * * @param int $accountId * @param string $folderId * @param string $messageId * @param string $attachmentId * @param string $targetPath * @return JSONResponse */ public function saveAttachment($accountId, $folderId, $messageId, $attachmentId, $targetPath) { $mailBox = $this->getFolder($accountId, $folderId); $attachmentIds = [$attachmentId]; if ($attachmentId === 0) { $m = $mailBox->getMessage($messageId); $attachmentIds = array_map(function ($a) { return $a['id']; }, $m->attachments); } foreach ($attachmentIds as $attachmentId) { $attachment = $mailBox->getAttachment($messageId, $attachmentId); $fileName = $attachment->getName(); $fileParts = pathinfo($fileName); $fileName = $fileParts['filename']; $fileExtension = $fileParts['extension']; $fullPath = "{$targetPath}/{$fileName}.{$fileExtension}"; $counter = 2; while ($this->userFolder->nodeExists($fullPath)) { $fullPath = "{$targetPath}/{$fileName} ({$counter}).{$fileExtension}"; $counter++; } $newFile = $this->userFolder->newFile($fullPath); $newFile->putContent($attachment->getContents()); } return new JSONResponse(); }
/** * 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(); }
/** * Convert an IShare to an array for OCS output * * @param IShare $share * @return array */ protected function formatShare($share) { $result = ['id' => $share->getId(), 'share_type' => $share->getShareType(), 'uid_owner' => $share->getSharedBy()->getUID(), 'displayname_owner' => $share->getSharedBy()->getDisplayName(), 'permissions' => $share->getPermissions(), 'stime' => $share->getShareTime(), 'parent' => $share->getParent(), 'expiration' => null, 'token' => null]; $path = $share->getPath(); $result['path'] = $this->userFolder->getRelativePath($path->getPath()); if ($path instanceof \OCP\Files\Folder) { $result['item_type'] = 'folder'; } else { $result['item_type'] = 'file'; } $result['storage_id'] = $path->getStorage()->getId(); $result['storage'] = \OC\Files\Cache\Storage::getNumericStorageId($path->getStorage()->getId()); $result['item_source'] = $path->getId(); $result['file_source'] = $path->getId(); $result['file_parent'] = $path->getParent()->getId(); $result['file_target'] = $share->getTarget(); if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { $sharedWith = $share->getSharedWith(); $result['share_with'] = $sharedWith->getUID(); $result['share_with_displayname'] = $sharedWith->getDisplayName(); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $sharedWith = $share->getSharedWith(); $result['share_with'] = $sharedWith->getGID(); $result['share_with_displayname'] = $sharedWith->getGID(); } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $result['share_with'] = $share->getPassword(); $result['share_with_displayname'] = $share->getPassword(); $result['token'] = $share->getToken(); $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]); $expiration = $share->getExpirationDate(); if ($expiration !== null) { $result['expiration'] = $expiration->format('Y-m-d 00:00:00'); } } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) { $result['share_with'] = $share->getSharedWith(); $result['share_with_displayname'] = $share->getSharedWith(); $result['token'] = $share->getToken(); } } } } $result['mail_send'] = $share->getMailSend() ? 1 : 0; return $result; }
/** * Runs before each test (public method) * * It's important to recreate the app for every test, as if the user had just logged in * * @fixme Or just create the app once for each type of env and run all tests. For that to work, * I think I would need to switch to Cepts */ protected function _before() { $this->coreTestCase->setUp(); $app = new Gallery(); $this->container = $app->getContainer(); $this->server = $this->container->getServer(); $setupData = $this->getModule('\\Helper\\DataSetup'); $this->userId = $setupData->userId; $this->sharerUserId = $setupData->sharerUserId; $this->sharedFolder = $setupData->sharedFolder; $this->sharedFolderName = $this->sharedFolder->getName(); $this->sharedFile = $setupData->sharedFile; $this->sharedFileName = $this->sharedFile->getName(); $this->sharedFolderToken = $setupData->sharedFolderToken; $this->sharedFileToken = $setupData->sharedFileToken; $this->passwordForFolderShare = $setupData->passwordForFolderShare; }
/** * Get all files for the given tag * * @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) { try { $fileIds = $this->tagger->getIdsForTag($tagName); } catch (\Exception $e) { return []; } $fileInfos = []; foreach ($fileIds as $fileId) { $nodes = $this->homeFolder->getById((int) $fileId); foreach ($nodes as $node) { /** @var \OC\Files\Node\Node $node */ $fileInfos[] = $node->getFileInfo(); } } return $fileInfos; }
/** * Get the extention of the avatar. If there is no avatar throw Exception * * @return string * @throws NotFoundException */ private function getExtention() { if ($this->folder->nodeExists('avatar.jpg')) { return 'jpg'; } elseif ($this->folder->nodeExists('avatar.png')) { return 'png'; } throw new NotFoundException(); }
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()); }
/** * remove the users avatar * @return void */ public function remove() { try { $this->folder->get('avatar.jpg')->delete(); } catch (\OCP\Files\NotFoundException $e) { } try { $this->folder->get('avatar.png')->delete(); } catch (\OCP\Files\NotFoundException $e) { } }
/** * @NoAdminRequired * * @param string $path * @return DataResponse */ public function postAvatar($path) { $userId = $this->userSession->getUser()->getUID(); $files = $this->request->getUploadedFile('files'); $headers = []; if ($this->request->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE_8])) { // due to upload iframe workaround, need to set content-type to text/plain $headers['Content-Type'] = 'text/plain'; } if (isset($path)) { $path = stripslashes($path); $node = $this->userFolder->get($path); if (!$node instanceof \OCP\Files\File) { return new DataResponse(['data' => ['message' => $this->l->t('Please select a file.')]], Http::STATUS_OK, $headers); } if ($node->getSize() > 20 * 1024 * 1024) { return new DataResponse(['data' => ['message' => $this->l->t('File is too big')]], Http::STATUS_BAD_REQUEST, $headers); } $content = $node->getContent(); } elseif (!is_null($files)) { if ($files['error'][0] === 0 && is_uploaded_file($files['tmp_name'][0]) && !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])) { if ($files['size'][0] > 20 * 1024 * 1024) { return new DataResponse(['data' => ['message' => $this->l->t('File is too big')]], Http::STATUS_BAD_REQUEST, $headers); } $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200); $content = $this->cache->get('avatar_upload'); unlink($files['tmp_name'][0]); } else { return new DataResponse(['data' => ['message' => $this->l->t('Invalid file provided')]], Http::STATUS_BAD_REQUEST, $headers); } } else { //Add imgfile return new DataResponse(['data' => ['message' => $this->l->t('No image or file provided')]], Http::STATUS_BAD_REQUEST, $headers); } try { $image = new \OC_Image(); $image->loadFromData($content); $image->fixOrientation(); if ($image->valid()) { $mimeType = $image->mimeType(); if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') { return new DataResponse(['data' => ['message' => $this->l->t('Unknown filetype')]], Http::STATUS_OK, $headers); } $this->cache->set('tmpAvatar', $image->data(), 7200); return new DataResponse(['data' => 'notsquare'], Http::STATUS_OK, $headers); } else { return new DataResponse(['data' => ['message' => $this->l->t('Invalid image')]], Http::STATUS_OK, $headers); } } catch (\Exception $e) { $this->logger->logException($e, ['app' => 'core']); return new DataResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK, $headers); } }
/** * @NoAdminRequired * @NoCSRFRequired * * @param string $path */ public function done($path) { //TODO: move file $np = $path . '.new'; try { $node_new = $this->userFolder->get($np); } catch (\OCP\Files\NotFoundException $exception) { return new JSONResponse([], Http::STATUS_NOT_FOUND); } $hash = $node_new->hash('sha1'); return new JSONResponse($hash); }
/** * Get all files for the given tag * * @param string $tagName tag name to filter by * @return Node[] list of matching files * @throws \Exception if the tag does not exist */ public function getFilesByTag($tagName) { try { $fileIds = $this->tagger->getIdsForTag($tagName); } catch (\Exception $e) { return []; } $allNodes = []; foreach ($fileIds as $fileId) { $allNodes = array_merge($allNodes, $this->homeFolder->getById((int) $fileId)); } return $allNodes; }
/** * {@inheritDoc} */ public function getFilePath($itemSource, $uidOwner) { try { $calendar = $this->calendars->find($itemSource, $uidOwner); $fileId = $calendar->getFileId(); if ($fileId === null) { return false; } $files = $this->userFolder->getById($fileId); if (!$files || empty($files)) { return false; } else { return $files[0]->getPath(); } } catch (BusinessLayer\Exception $ex) { return false; } }
/** * @NoAdminRequired * @NoCSRFRequired */ public function cover() { // we no longer need the session to be kept open session_write_close(); $albumId = $this->getIdFromSlug($this->params('albumIdOrSlug')); $album = $this->albumBusinessLayer->find($albumId, $this->userId); $nodes = $this->userFolder->getById($album->getCoverFileId()); if (count($nodes) > 0) { // get the first valid node $node = $nodes[0]; $mime = $node->getMimeType(); $content = $node->getContent(); return new FileResponse(array('mimetype' => $mime, 'content' => $content)); } $r = new Response(); $r->setStatus(Http::STATUS_NOT_FOUND); return $r; }
/** * test unshare of a reshared file */ function testDeleteReshare() { $node1 = $this->userFolder->get($this->folder); $share1 = $this->shareManager->newShare(); $share1->setNode($node1)->setSharedBy(self::TEST_FILES_SHARING_API_USER1)->setSharedWith(self::TEST_FILES_SHARING_API_USER2)->setShareType(\OCP\Share::SHARE_TYPE_USER)->setPermissions(31); $share1 = $this->shareManager->createShare($share1); $user2folder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER2); $node2 = $user2folder->get($this->folder . '/' . $this->filename); $share2 = $this->shareManager->newShare(); $share2->setNode($node2)->setSharedBy(self::TEST_FILES_SHARING_API_USER2)->setShareType(\OCP\Share::SHARE_TYPE_LINK)->setPermissions(1); $share2 = $this->shareManager->createShare($share2); // test if we can unshare the link again $request = $this->createRequest([]); $ocs = $this->createOCS($request, self::TEST_FILES_SHARING_API_USER2); $result = $ocs->deleteShare($share2->getId()); $this->assertTrue($result->succeeded()); $this->shareManager->deleteShare($share1); }
/** * @NoAdminRequired * * @param string $path * @return DataResponse */ public function postAvatar($path) { $userId = $this->userSession->getUser()->getUID(); $files = $this->request->getUploadedFile('files'); if (isset($path)) { $path = stripslashes($path); $node = $this->userFolder->get($path); if ($node->getSize() > 20 * 1024 * 1024) { return new DataResponse(['data' => ['message' => $this->l->t('File is too big')]], Http::STATUS_BAD_REQUEST); } $content = $node->getContent(); } elseif (!is_null($files)) { if ($files['error'][0] === 0 && is_uploaded_file($files['tmp_name'][0]) && !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])) { if ($files['size'][0] > 20 * 1024 * 1024) { return new DataResponse(['data' => ['message' => $this->l->t('File is too big')]], Http::STATUS_BAD_REQUEST); } $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200); $content = $this->cache->get('avatar_upload'); unlink($files['tmp_name'][0]); } else { return new DataResponse(['data' => ['message' => $this->l->t('Invalid file provided')]], Http::STATUS_BAD_REQUEST); } } else { //Add imgfile return new DataResponse(['data' => ['message' => $this->l->t('No image or file provided')]], Http::STATUS_BAD_REQUEST); } try { $image = new \OC_Image(); $image->loadFromData($content); $image->fixOrientation(); if ($image->valid()) { $mimeType = $image->mimeType(); if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') { return new DataResponse(['data' => ['message' => $this->l->t('Unknown filetype')]]); } $this->cache->set('tmpAvatar', $image->data(), 7200); return new DataResponse(['data' => 'notsquare']); } else { return new DataResponse(['data' => ['message' => $this->l->t('Invalid image')]]); } } catch (\Exception $e) { return new DataResponse(['data' => ['message' => $e->getMessage()]]); } }
public function testDeleteNestedShares() { $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)]); $this->assertEquals(1, $qb->execute()); // Get the id $qb = $this->dbConn->getQueryBuilder(); $cursor = $qb->select('id')->from('share')->setMaxResults(1)->orderBy('id', 'DESC')->execute(); $id1 = $cursor->fetch(); $id1 = $id1['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('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), 'parent' => $qb->expr()->literal($id1)]); $this->assertEquals(1, $qb->execute()); // Get the id $qb = $this->dbConn->getQueryBuilder(); $cursor = $qb->select('id')->from('share')->setMaxResults(1)->orderBy('id', 'DESC')->execute(); $id2 = $cursor->fetch(); $id2 = $id2['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('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), 'parent' => $qb->expr()->literal($id2)]); $this->assertEquals(1, $qb->execute()); $storage = $this->getMock('OC\\Files\\Storage\\Storage'); $storage->method('getOwner')->willReturn('shareOwner'); $path = $this->getMock('OCP\\Files\\Node'); $path->method('getStorage')->wilLReturn($storage); $this->userFolder->method('getById')->with(42)->willReturn([$path]); $sharedWith = $this->getMock('OCP\\IUser'); $sharedWith->method('getUID')->willReturn('sharedWith'); $sharedBy = $this->getMock('OCP\\IUser'); $sharedBy->method('getUID')->willReturn('sharedBy'); $shareOwner = $this->getMock('OCP\\IUser'); $this->userManager->method('get')->will($this->returnValueMap([['sharedWith', $sharedWith], ['sharedBy', $sharedBy], ['shareOwner', $shareOwner]])); $share = $this->provider->getShareById($id1); $this->provider->delete($share); $qb = $this->dbConn->getQueryBuilder(); $qb->select('*')->from('share'); $cursor = $qb->execute(); $result = $cursor->fetchAll(); $cursor->closeCursor(); $this->assertEmpty($result); }
public function testFindNodesByFileIdsSubDir() { $filesNode1 = $this->getMockBuilder('\\OCP\\Files\\Folder')->disableOriginalConstructor()->getMock(); $filesNode1->expects($this->once())->method('getName')->will($this->returnValue('first node')); $filesNode2 = $this->getMockBuilder('\\OCP\\Files\\File')->disableOriginalConstructor()->getMock(); $filesNode2->expects($this->once())->method('getName')->will($this->returnValue('second node')); $reportTargetNode = $this->getMockBuilder('\\OCA\\DAV\\Connector\\Sabre\\Directory')->disableOriginalConstructor()->getMock(); $reportTargetNode->expects($this->any())->method('getPath')->will($this->returnValue('/sub1/sub2')); $subNode = $this->getMockBuilder('\\OCP\\Files\\Folder')->disableOriginalConstructor()->getMock(); $this->userFolder->expects($this->at(0))->method('get')->with('/sub1/sub2')->will($this->returnValue($subNode)); $subNode->expects($this->at(0))->method('getById')->with('111')->will($this->returnValue([$filesNode1])); $subNode->expects($this->at(1))->method('getById')->with('222')->will($this->returnValue([$filesNode2])); /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit_Framework_MockObject_MockObject $reportTargetNode */ $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); $this->assertCount(2, $result); $this->assertInstanceOf('\\OCA\\DAV\\Connector\\Sabre\\Directory', $result[0]); $this->assertEquals('first node', $result[0]->getName()); $this->assertInstanceOf('\\OCA\\DAV\\Connector\\Sabre\\File', $result[1]); $this->assertEquals('second node', $result[1]->getName()); }
/** * @NoAdminRequired * * @param string $path * @return DataResponse */ public function importOc($path) { try { $file = $this->userFolder->get($path); if (!$file instanceof File) { throw new Exception($this->l10n->t('Could not open file')); } if ($file->getMimeType() !== 'text/csv') { throw new Exception($this->l10n->t('Import file must be of type text/csv')); } $vehicle = $this->importCsv($file->getContent()); return new DataResponse(['name' => $vehicle->getName(), 'id' => $vehicle->getId()]); } catch (NotFoundException $ex) { $this->logger->info("CSV OC Import: File <{$path}> does not exist"); return new DataResponse($this->l10n->t('File does not exist'), Http::STATUS_BAD_REQUEST); } catch (Exception $ex) { $this->logger->info('Error while importing CSV file: ' + $ex->getMessage()); return new DataResponse($this->l10n->t('Error while importing'), Http::STATUS_BAD_REQUEST); } }
public function testSetAvatar() { $avatarFileJPG = $this->getMock('\\OCP\\Files\\File'); $avatarFileJPG->method('getName')->willReturn('avatar.jpg'); $avatarFileJPG->expects($this->once())->method('delete'); $avatarFilePNG = $this->getMock('\\OCP\\Files\\File'); $avatarFilePNG->method('getName')->willReturn('avatar.png'); $avatarFilePNG->expects($this->once())->method('delete'); $resizedAvatarFile = $this->getMock('\\OCP\\Files\\File'); $resizedAvatarFile->method('getName')->willReturn('avatar.32.jpg'); $resizedAvatarFile->expects($this->once())->method('delete'); $nonAvatarFile = $this->getMock('\\OCP\\Files\\File'); $nonAvatarFile->method('getName')->willReturn('avatarX'); $nonAvatarFile->expects($this->never())->method('delete'); $this->folder->method('search')->with('avatar')->willReturn([$avatarFileJPG, $avatarFilePNG, $resizedAvatarFile, $nonAvatarFile]); $newFile = $this->getMock('\\OCP\\Files\\File'); $this->folder->expects($this->once())->method('newFile')->with('avatar.png')->willReturn($newFile); $image = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $newFile->expects($this->once())->method('putContent')->with($image->data()); $this->avatar->set($image->data()); }
/** * @dataProvider sharesGetPropertiesDataProvider */ public function testPreloadThenGetProperties($shareTypes) { $sabreNode1 = $this->getMockBuilder('\\OCA\\DAV\\Connector\\Sabre\\File')->disableOriginalConstructor()->getMock(); $sabreNode1->expects($this->any())->method('getId')->will($this->returnValue(111)); $sabreNode1->expects($this->never())->method('getPath'); $sabreNode2 = $this->getMockBuilder('\\OCA\\DAV\\Connector\\Sabre\\File')->disableOriginalConstructor()->getMock(); $sabreNode2->expects($this->any())->method('getId')->will($this->returnValue(222)); $sabreNode2->expects($this->never())->method('getPath'); $sabreNode = $this->getMockBuilder('\\OCA\\DAV\\Connector\\Sabre\\Directory')->disableOriginalConstructor()->getMock(); $sabreNode->expects($this->any())->method('getId')->will($this->returnValue(123)); // never, because we use getDirectoryListing from the Node API instead $sabreNode->expects($this->never())->method('getChildren'); $sabreNode->expects($this->any())->method('getPath')->will($this->returnValue('/subdir')); // node API nodes $node = $this->getMock('\\OCP\\Files\\Folder'); $node->expects($this->any())->method('getId')->will($this->returnValue(123)); $node1 = $this->getMock('\\OCP\\Files\\File'); $node1->expects($this->any())->method('getId')->will($this->returnValue(111)); $node2 = $this->getMock('\\OCP\\Files\\File'); $node2->expects($this->any())->method('getId')->will($this->returnValue(222)); $node->expects($this->once())->method('getDirectoryListing')->will($this->returnValue([$node1, $node2])); $this->userFolder->expects($this->once())->method('get')->with('/subdir')->will($this->returnValue($node)); $this->shareManager->expects($this->any())->method('getSharesBy')->with($this->equalTo('user1'), $this->anything(), $this->anything(), $this->equalTo(false), $this->equalTo(1))->will($this->returnCallback(function ($userId, $requestedShareType, $node, $flag, $limit) use($shareTypes) { if ($node->getId() === 111 && in_array($requestedShareType, $shareTypes)) { return ['dummyshare']; } return []; })); // simulate sabre recursive PROPFIND traversal $propFindRoot = new \Sabre\DAV\PropFind('/subdir', [self::SHARETYPES_PROPERTYNAME], 1); $propFind1 = new \Sabre\DAV\PropFind('/subdir/test.txt', [self::SHARETYPES_PROPERTYNAME], 0); $propFind2 = new \Sabre\DAV\PropFind('/subdir/test2.txt', [self::SHARETYPES_PROPERTYNAME], 0); $this->plugin->handleGetProperties($propFindRoot, $sabreNode); $this->plugin->handleGetProperties($propFind1, $sabreNode1); $this->plugin->handleGetProperties($propFind2, $sabreNode2); $result = $propFind1->getResultForMultiStatus(); $this->assertEmpty($result[404]); unset($result[404]); $this->assertEquals($shareTypes, $result[200][self::SHARETYPES_PROPERTYNAME]->getShareTypes()); }
/** * {@inheritDoc} */ public function getFilePath($itemSource, $uidOwner) { try { if (substr_count($itemSource, '::') === 0) { return false; } list($calendarId) = explode('::', $itemSource, 1); $calendar = $this->calendars->find($calendarId, $uidOwner); $fileId = $calendar->getFileId(); if ($fileId === null) { return false; } $files = $this->userFolder->getById($fileId); if (!$files || empty($files)) { return false; } else { return $files[0]->getPath(); } } catch (BusinessLayer\Exception $ex) { return false; } }
/** * @dataProvider showFileMethodProvider */ public function testShowFileRouteWithTrashedFile($useShowFile) { $this->appManager->expects($this->once())->method('isEnabledForUser')->with('files_trashbin')->will($this->returnValue(true)); $parentNode = $this->getMock('\\OCP\\Files\\Folder'); $parentNode->expects($this->once())->method('getPath')->will($this->returnValue('testuser1/files_trashbin/files/test.d1462861890/sub')); $baseFolderFiles = $this->getMock('\\OCP\\Files\\Folder'); $baseFolderTrash = $this->getMock('\\OCP\\Files\\Folder'); $this->rootFolder->expects($this->at(0))->method('get')->with('testuser1/files/')->will($this->returnValue($baseFolderFiles)); $this->rootFolder->expects($this->at(1))->method('get')->with('testuser1/files_trashbin/files/')->will($this->returnValue($baseFolderTrash)); $baseFolderFiles->expects($this->once())->method('getById')->with(123)->will($this->returnValue([])); $node = $this->getMock('\\OCP\\Files\\File'); $node->expects($this->once())->method('getParent')->will($this->returnValue($parentNode)); $node->expects($this->once())->method('getName')->will($this->returnValue('somefile.txt')); $baseFolderTrash->expects($this->at(0))->method('getById')->with(123)->will($this->returnValue([$node])); $baseFolderTrash->expects($this->at(1))->method('getRelativePath')->with('testuser1/files_trashbin/files/test.d1462861890/sub')->will($this->returnValue('/test.d1462861890/sub')); $this->urlGenerator->expects($this->once())->method('linkToRoute')->with('files.view.index', ['view' => 'trashbin', 'dir' => '/test.d1462861890/sub', 'scrollto' => 'somefile.txt'])->will($this->returnValue('/apps/files/?view=trashbin&dir=/test.d1462861890/sub&scrollto=somefile.txt')); $expected = new Http\RedirectResponse('/apps/files/?view=trashbin&dir=/test.d1462861890/sub&scrollto=somefile.txt'); if ($useShowFile) { $this->assertEquals($expected, $this->viewController->showFile(123)); } else { $this->assertEquals($expected, $this->viewController->index('/whatever', '', '123')); } }