/** * @param File $file * @return static */ public static function fromFile(File $file) { $note = new static(); $note->setId($file->getId()); $note->setContent($file->getContent()); $note->setModified($file->getMTime()); $note->setTitle(substr($file->getName(), 0, -4)); // remove trailing .txt $note->resetUpdatedFields(); return $note; }
/** * @param File $file * @return static */ public static function fromFile(File $file) { $note = new static(); $note->setId($file->getId()); $note->setContent($file->getContent()); $note->setModified($file->getMTime()); $note->setTitle(pathinfo($file->getName(), PATHINFO_FILENAME)); // remove extension $note->resetUpdatedFields(); return $note; }
/** * Downloads the requested file * * @param File $file * @param bool $base64Encode * * @return false|array */ public function downloadFile($file, $base64Encode = false) { try { $this->logger->debug("[DownloadService] File to Download: {name}", ['name' => $file->getName()]); $download = ['preview' => $file->getContent(), 'mimetype' => $file->getMimeType()]; if ($base64Encode) { $download['preview'] = $this->encode($download['preview']); } } catch (\Exception $exception) { $download = false; } return $download; }
/** * Downloads the requested file * * @param File $file * @param bool $base64Encode * * @return array|false * @throws NotFoundServiceException */ public function downloadFile($file, $base64Encode = false) { try { $this->logger->debug("[DownloadService] File to Download: {name}", ['name' => $file->getName()]); $download = ['preview' => $file->getContent(), 'mimetype' => $file->getMimeType()]; if ($base64Encode) { $download['preview'] = $this->encode($download['preview']); } return $download; } catch (\Exception $exception) { throw new NotFoundServiceException('There was a problem accessing the file'); } }
protected function setUp() { parent::setUp(); $this->createUser('userid', 'pass'); $this->loginAsUser('userid'); $app = new Application(); $this->container = $app->getContainer(); $this->container['AppName'] = 'core'; $this->container['AvatarManager'] = $this->getMock('OCP\\IAvatarManager'); $this->container['Cache'] = $this->getMockBuilder('OC\\Cache\\File')->disableOriginalConstructor()->getMock(); $this->container['L10N'] = $this->getMock('OCP\\IL10N'); $this->container['L10N']->method('t')->will($this->returnArgument(0)); $this->container['UserManager'] = $this->getMock('OCP\\IUserManager'); $this->container['UserSession'] = $this->getMock('OCP\\IUserSession'); $this->container['Request'] = $this->getMock('OCP\\IRequest'); $this->container['UserFolder'] = $this->getMock('OCP\\Files\\Folder'); $this->container['Logger'] = $this->getMock('OCP\\ILogger'); $this->avatarMock = $this->getMock('OCP\\IAvatar'); $this->userMock = $this->getMock('OCP\\IUser'); $this->avatarController = $this->container['AvatarController']; // Configure userMock $this->userMock->method('getDisplayName')->willReturn('displayName'); $this->userMock->method('getUID')->willReturn('userId'); $this->container['UserManager']->method('get')->willReturnMap([['userId', $this->userMock]]); $this->container['UserSession']->method('getUser')->willReturn($this->userMock); $this->avatarFile = $this->getMock('OCP\\Files\\File'); $this->avatarFile->method('getContnet')->willReturn('image data'); $this->avatarFile->method('getMimeType')->willReturn('image type'); $this->avatarFile->method('getEtag')->willReturn('my etag'); }
/** * 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; }
/** * Prepares an empty Thumbnail array to send back * * When we can't even get the file information, we send an empty mimeType * * @param File $file * @param int $status * * @return array<string,null|string> */ private function prepareEmptyThumbnail($file, $status) { $thumbnail = []; if ($status !== Http::STATUS_NOT_FOUND) { $mimeType = ''; if ($file) { $mimeType = $file->getMimeType(); } $thumbnail = ['preview' => null, 'mimetype' => $mimeType]; } return $thumbnail; }
/** * Returns the path which goes from the file, up to the root folder of the Gallery: * current_folder/my_file * * That root folder changes when folders are shared publicly * * @param File|Folder $node * * @return string */ public function getPathFromVirtualRoot($node) { $path = $node->getPath(); $nodeType = $node->getType(); // Needed because fromRootToFolder always ends with a slash if ($nodeType === 'dir') { $path .= '/'; } $path = str_replace($this->fromRootToFolder, '', $path); $path = rtrim($path, '/'); return $path; }
/** * Tests if a GIF is animated * * An animated gif contains multiple "frames", with each frame having a * header made up of: * * a static 4-byte sequence (\x00\x21\xF9\x04) * * 4 variable bytes * * a static 2-byte sequence (\x00\x2C) (Photoshop uses \x00\x21) * * We read through the file until we reach the end of the file, or we've * found at least 2 frame headers * * @link http://php.net/manual/en/function.imagecreatefromgif.php#104473 * * @param File $file * * @return bool * @throws InternalServerErrorServiceException */ private function isGifAnimated($file) { $count = 0; try { $fileHandle = $file->fopen('rb'); while (!feof($fileHandle) && $count < 2) { $chunk = fread($fileHandle, 1024 * 100); //read 100kb at a time $count += preg_match_all('#\\x00\\x21\\xF9\\x04.{4}\\x00(\\x2C|\\x21)#s', $chunk, $matches); } fclose($fileHandle); } catch (\Exception $exception) { throw new InternalServerErrorServiceException('Something went wrong when trying to read a GIF file'); } return $count > 1; }
/** * test if file is a note * * @param \OCP\Files\File $file * @return bool */ private function isNote($file) { $allowedExtensions = ['txt', 'org', 'markdown', 'md', 'note']; if ($file->getType() !== 'file') { return false; } if (!in_array(pathinfo($file->getName(), PATHINFO_EXTENSION), $allowedExtensions)) { return false; } return true; }
/** * @param File $file * @param bool $previewRequired * * @return array <string,mixed> */ private function mockPreviewData($file, $previewRequired) { $mimeType = $previewRequired ? 'image/png' : $file->getMimeType(); $preview = ['preview' => $file->getContent(), 'mimetype' => $mimeType]; return $preview; }
/** * index a file * * @param File $file the file to be indexed * @param bool $commit * * @return bool true when something was stored in the index, false otherwise (eg, folders are not indexed) * @throws NotIndexedException when an unsupported file type is encountered */ public function indexFile(File $file, $commit = true) { // we decide how to index on mime type or file extension $mimeType = $file->getMimeType(); $fileExtension = strtolower(pathinfo($file->getName(), PATHINFO_EXTENSION)); // initialize plain lucene document $doc = new Document(); // index content for local files only $storage = $file->getStorage(); if ($storage->isLocal()) { $path = $storage->getLocalFile($file->getInternalPath()); //try to use special lucene document types if ('text/html' === $mimeType) { //TODO could be indexed, even if not local $doc = HTML::loadHTML($file->getContent()); } else { if ('text/' === substr($mimeType, 0, 5) || 'application/x-tex' === $mimeType) { $body = $file->getContent(); if ($body != '') { $doc->addField(Document\Field::UnStored('body', $body)); } } else { if ('application/pdf' === $mimeType) { $doc = Pdf::loadPdf($file->getContent()); // the zend classes only understand docx and not doc files } else { if ($fileExtension === 'docx') { $doc = Document\Docx::loadDocxFile($path); //} else if ('application/msexcel' === $mimeType) { } else { if ($fileExtension === 'xlsx') { $doc = Document\Xlsx::loadXlsxFile($path); //} else if ('application/mspowerpoint' === $mimeType) { } else { if ($fileExtension === 'pptx') { $doc = Document\Pptx::loadPptxFile($path); } else { if ($fileExtension === 'odt') { $doc = Odt::loadOdtFile($path); } else { if ($fileExtension === 'ods') { $doc = Ods::loadOdsFile($path); } else { throw new NotIndexedException(); } } } } } } } } } // Store filecache id as unique id to lookup by when deleting $doc->addField(Document\Field::Keyword('fileId', $file->getId())); // Store document path for the search results $doc->addField(Document\Field::Text('path', $file->getPath(), 'UTF-8')); $doc->addField(Document\Field::unIndexed('mtime', $file->getMTime())); $doc->addField(Document\Field::unIndexed('size', $file->getSize())); $doc->addField(Document\Field::unIndexed('mimetype', $mimeType)); $this->index->updateFile($doc, $file->getId(), $commit); return true; }
/** * Determines if we can read the content of the file and returns a file pointer resource * * We can't use something like $node->isReadable() as it's too unreliable * Some storage classes just check for the presence of the file * * @param File $file * * @return resource * @throws InternalServerErrorServiceException */ private function isFileReadable($file) { try { $fileHandle = $file->fopen('rb'); if (!$fileHandle) { throw new \Exception(); } } catch (\Exception $exception) { throw new InternalServerErrorServiceException('Something went wrong when trying to read' . $file->getPath()); } return $fileHandle; }
/** * @param File $file */ public function addAttachmentFromFiles(File $file) { $part = new Horde_Mime_Part(); $part->setCharset('us-ascii'); $part->setDisposition('attachment'); $part->setName($file->getName()); $part->setContents($file->getContent()); $part->setType($file->getMimeType()); $this->attachments[] = $part; }
/** * Tests if a GIF is animated * * An animated gif contains multiple "frames", with each frame having a * header made up of: * * a static 4-byte sequence (\x00\x21\xF9\x04) * * 4 variable bytes * * a static 2-byte sequence (\x00\x2C) (Photoshop uses \x00\x21) * * We read through the file until we reach the end of the file, or we've * found at least 2 frame headers * * @link http://php.net/manual/en/function.imagecreatefromgif.php#104473 * * @param File $file * * @return bool */ private function isGifAnimated($file) { $fileHandle = $file->fopen('rb'); $count = 0; while (!feof($fileHandle) && $count < 2) { $chunk = fread($fileHandle, 1024 * 100); //read 100kb at a time $count += preg_match_all('#\\x00\\x21\\xF9\\x04.{4}\\x00(\\x2C|\\x21)#s', $chunk, $matches); } fclose($fileHandle); return $count > 1; }
/** * @param File|Folder $path */ protected function pathCreateChecks($path) { // Make sure that we do not share a path that contains a shared mountpoint if ($path instanceof \OCP\Files\Folder) { $mounts = $this->mountManager->findIn($path->getPath()); foreach ($mounts as $mount) { if ($mount->getStorage()->instanceOfStorage('\\OCA\\Files_Sharing\\ISharedStorage')) { throw new \InvalidArgumentException('Path contains files shared with you'); } } } }
/** * Get all shares by the given user. Sharetype and path can be used to filter. * * @param string $userId * @param int $shareType * @param \OCP\Files\File|\OCP\Files\Folder $node * @param bool $reshares Also get the shares where $user is the owner instead of just the shares where $user is the initiator * @param int $limit The maximum number of shares to be returned, -1 for all shares * @param int $offset * @return Share[] */ public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) { $qb = $this->dbConn->getQueryBuilder(); $qb->select('*')->from('share'); $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType))); /** * Reshares for this user are shares where they are the owner. */ if ($reshares === false) { //Special case for old shares created via the web UI $or1 = $qb->expr()->andX($qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)), $qb->expr()->isNull('uid_initiator')); $qb->andWhere($qb->expr()->orX($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)), $or1)); } else { $qb->andWhere($qb->expr()->orX($qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)), $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)))); } if ($node !== null) { $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId()))); } if ($limit !== -1) { $qb->setMaxResults($limit); } $qb->setFirstResult($offset); $qb->orderBy('id'); $cursor = $qb->execute(); $shares = []; while ($data = $cursor->fetch()) { $shares[] = $this->createShare($data); } $cursor->closeCursor(); return $shares; }
/** * Returns true if the file is of a supported media type and adds it to the array of items to * return * * @todo We could potentially check if the file is readable ($file->stat() maybe) in order to * only return valid files, but this may slow down operations * * @param File $file the file to test * * @return bool */ private function isPreviewAvailable($file) { try { $mimeType = $file->getMimetype(); if (in_array($mimeType, $this->supportedMediaTypes)) { $this->addFileToResults($file); return true; } } catch (\Exception $exception) { return false; } return false; }