/** * @inheritdoc */ public function getFile($size) { $ext = $this->getExtention(); if ($size === -1) { $path = 'avatar.' . $ext; } else { $path = 'avatar.' . $size . '.' . $ext; } try { $file = $this->folder->get($path); } catch (NotFoundException $e) { if ($size <= 0) { throw new NotFoundException(); } $avatar = new OC_Image(); /** @var File $file */ $file = $this->folder->get('avatar.' . $ext); $avatar->loadFromData($file->getContent()); if ($size !== -1) { $avatar->resize($size); } $file = $this->folder->newFile($path); $file->putContent($avatar->data()); } return $file; }
/** * 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(); }
/** * @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(); }
/** * Updates the tags of the specified file path. * The passed tags are absolute, which means they will * replace the actual tag selection. * * @param string $path path * @param array $tags array of tags * @return array list of tags * @throws \OCP\Files\NotFoundException if the file does not exist */ public function updateFileTags($path, $tags) { $fileId = $this->homeFolder->get($path)->getId(); $currentTags = $this->tagger->getTagsForObjects(array($fileId)); if (!empty($currentTags)) { $currentTags = current($currentTags); } $newTags = array_diff($tags, $currentTags); foreach ($newTags as $tag) { $this->tagger->tagAs($fileId, $tag); } $deletedTags = array_diff($currentTags, $tags); foreach ($deletedTags as $tag) { $this->tagger->unTag($fileId, $tag); } // TODO: re-read from tagger to make sure the // list is up to date, in case of concurrent changes ? return $tags; }
/** * 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); }
/** * 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; }
/** * 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()]]); } }
/** * @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); } }
/** * Adds shares to propfind response * * @param PropFind $propFind propfind object * @param \Sabre\DAV\INode $sabreNode sabre node */ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $sabreNode) { if (!$sabreNode instanceof \OCA\DAV\Connector\Sabre\Node) { return; } // need prefetch ? if ($sabreNode instanceof \OCA\DAV\Connector\Sabre\Directory && $propFind->getDepth() !== 0 && !is_null($propFind->getStatus(self::SHARETYPES_PROPERTYNAME))) { $folderNode = $this->userFolder->get($propFind->getPath()); $children = $folderNode->getDirectoryListing(); $this->cachedShareTypes[$folderNode->getId()] = $this->getShareTypes($folderNode); foreach ($children as $childNode) { $this->cachedShareTypes[$childNode->getId()] = $this->getShareTypes($childNode); } } $propFind->handle(self::SHARETYPES_PROPERTYNAME, function () use($sabreNode) { if (isset($this->cachedShareTypes[$sabreNode->getId()])) { $shareTypes = $this->cachedShareTypes[$sabreNode->getId()]; } else { $node = $this->userFolder->get($sabreNode->getPath()); $shareTypes = $this->getShareTypes($node); } return new ShareTypeList($shareTypes); }); }
/** * get path of file and the title.txt and check if they are the same * file. If not the title needs to be renamed * * @param Folder $folder a folder to the notes directory * @param string $title the filename which should be used * @param string $extension the extension which should be used * @param int $id the id of the note for which the title should be generated * used to see if the file itself has the title and not a different file for * checking for filename collisions * @return string the resolved filename to prevent overwriting different * files with the same title */ private function generateFileName(Folder $folder, $title, $extension, $id) { $path = $title . '.' . $extension; // if file does not exist, that name has not been taken. Similar we don't // need to handle file collisions if it is the filename did not change if (!$folder->nodeExists($path) || $folder->get($path)->getId() === $id) { return $path; } else { // increments name (2) to name (3) $match = preg_match('/\\((?P<id>\\d+)\\)$/', $title, $matches); if ($match) { $newId = (int) $matches['id'] + 1; $newTitle = preg_replace('/(.*)\\s\\((\\d+)\\)$/', '$1 (' . $newId . ')', $title); } else { $newTitle = $title . ' (2)'; } return $this->generateFileName($folder, $newTitle, $extension, $id); } }
/** * @param \OCP\Files\Folder $parent * @param string $folderName * @return \OCP\Files\Folder * @throws SetUpException */ private function getOrCreateSubFolder(Folder $parent, $folderName) { if ($parent->nodeExists($folderName)) { return $parent->get($folderName); } else { return $parent->newFolder($folderName); } }
/** * @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); } // get sender data $headers = []; /** @var Account $account */ $from = new Horde_Mail_Rfc822_Address($account->getEMailAddress()); $from->personal = $account->getName(); $headers['From'] = $from; $headers['Subject'] = $subject; if (trim($cc) !== '') { $headers['Cc'] = trim($cc); } if (trim($bcc) !== '') { $headers['Bcc'] = trim($bcc); } // in reply to handling $folderId = base64_decode($folderId); $mailbox = null; if (!is_null($folderId) && !is_null($messageId)) { $mailbox = $account->getMailbox($folderId); $message = $mailbox->getMessage($messageId); if (is_null($subject)) { // prevent 'Re: Re:' stacking if (strcasecmp(substr($message->getSubject(), 0, 4), 'Re: ') === 0) { $headers['Subject'] = $message->getSubject(); } else { $headers['Subject'] = 'Re: ' . $message->getSubject(); } } $headers['In-Reply-To'] = $message->getMessageId(); if (is_null($to)) { $to = $message->getToEmail(); } } $headers['To'] = $to; // build mime body $mail = new Horde_Mime_Mail(); $mail->addHeaders($headers); $mail->setBody($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) { $a = new \Horde_Mime_Part(); $a->setCharset('us-ascii'); $a->setDisposition('attachment'); $a->setName($f->getName()); $a->setContents($f->getContent()); $a->setType($f->getMimeType()); $mail->addMimePart($a); } } } } // create transport and send try { $transport = $account->createTransport(); $mail->send($transport); // in case of reply we flag the message as answered if ($mailbox) { $mailbox->setMessageFlag($messageId, Horde_Imap_Client::FLAG_ANSWERED, true); } // save the message in the sent folder $sentFolder = $account->getSentFolder(); /** @var resource $raw */ $raw = $mail->getRaw(); $raw = stream_get_contents($raw); $sentFolder->saveMessage($raw, [Horde_Imap_Client::FLAG_SEEN]); // delete draft message if (!is_null($draftUID)) { $draftsFolder = $account->getDraftsFolder(); $folderId = $draftsFolder->getFolderId(); $this->logger->debug("deleting sent draft <{$draftUID}> in folder <{$folderId}>"); $draftsFolder->setMessageFlag($draftUID, \Horde_Imap_Client::FLAG_DELETED, true); $account->deleteDraft($draftUID); $this->logger->debug("sent draft <{$draftUID}> deleted"); } } 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(); }