/** * Upload file controller action * * @return \Magento\Framework\Controller\ResultInterface */ public function executeInternal() { $type = $this->getRequest()->getParam('type'); $tmpPath = ''; if ($type == 'samples') { $tmpPath = $this->_sample->getBaseTmpPath(); } elseif ($type == 'links') { $tmpPath = $this->_link->getBaseTmpPath(); } elseif ($type == 'link_samples') { $tmpPath = $this->_link->getBaseSampleTmpPath(); } try { $uploader = $this->uploaderFactory->create(['fileId' => $type]); $result = $this->_fileHelper->uploadFromTmp($tmpPath, $uploader); if (!$result) { throw new \Exception('File can not be moved from temporary folder to the destination folder.'); } /** * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS */ $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']); $result['path'] = str_replace('\\', '/', $result['path']); if (isset($result['file'])) { $relativePath = rtrim($tmpPath, '/') . '/' . ltrim($result['file'], '/'); $this->storageDatabase->saveFile($relativePath); } $result['cookie'] = ['name' => $this->_getSession()->getName(), 'value' => $this->_getSession()->getSessionId(), 'lifetime' => $this->_getSession()->getCookieLifetime(), 'path' => $this->_getSession()->getCookiePath(), 'domain' => $this->_getSession()->getCookieDomain()]; } catch (\Exception $e) { $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()]; } return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result); }
/** * Clean files in database on cleaning merged assets * * @param \Magento\Framework\View\Asset\MergeService $subject * @param callable $proceed * * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundCleanMergedJsCss(\Magento\Framework\View\Asset\MergeService $subject, \Closure $proceed) { $proceed(); /** @var \Magento\Framework\Filesystem\Directory\ReadInterface $pubStaticDirectory */ $pubStaticDirectory = $this->filesystem->getDirectoryRead(DirectoryList::STATIC_VIEW); $mergedDir = $pubStaticDirectory->getAbsolutePath() . '/' . \Magento\Framework\View\Asset\Merged::getRelativeDir(); $this->database->deleteFolder($mergedDir); }
public function aroundDeleteFolder(Database $subject, $proceed, $folderName) { if ($this->helper->checkS3Usage()) { /** @var \Arkade\S3\Model\MediaStorage\File\Storage\S3 $storageModel */ $storageModel = $subject->getStorageDatabaseModel(); $storageModel->deleteDirectory($folderName); } else { $proceed($folderName); } }
/** * Save file to storage * * @param array $result * @return $this */ protected function _afterSave($result) { if (empty($result['path']) || empty($result['file'])) { return $this; } if ($this->_coreFileStorage->isInternalStorage() || $this->skipDbProcessing()) { return $this; } $this->_result['file'] = $this->_coreFileStorageDb->saveUploadedFile($result); return $this; }
public function testCopyQuoteToOrder() { $optionMock = $this->getMockBuilder('Magento\\Catalog\\Model\\Product\\Configuration\\Item\\Option\\OptionInterface')->disableOriginalConstructor()->setMethods(['getValue'])->getMockForAbstractClass(); $quotePath = '/quote/path/path/uploaded.file'; $orderPath = '/order/path/path/uploaded.file'; $optionMock->expects($this->any())->method('getValue')->will($this->returnValue(['quote_path' => $quotePath, 'order_path' => $orderPath])); $this->rootDirectory->expects($this->any())->method('isFile')->with($this->equalTo($quotePath))->will($this->returnValue(true)); $this->rootDirectory->expects($this->any())->method('isReadable')->with($this->equalTo($quotePath))->will($this->returnValue(true)); $this->rootDirectory->expects($this->any())->method('getAbsolutePath')->will($this->returnValue('/file.path')); $this->coreFileStorageDatabase->expects($this->any())->method('copyFile')->will($this->returnValue('true')); $fileObject = $this->getFileObject(); $fileObject->setData('configuration_item_option', $optionMock); $this->assertInstanceOf('Magento\\Catalog\\Model\\Product\\Option\\Type\\File', $fileObject->copyQuoteToOrder()); }
/** * Retrieve media base directory path * * @return string */ public function getMediaBaseDirectory() { if ($this->_mediaBaseDirectory === null) { $this->_mediaBaseDirectory = $this->_storageHelper->getMediaBaseDir(); } return $this->_mediaBaseDirectory; }
/** * If DB file storage is on - find there, otherwise - just file_exists * * @param string $filename relative path * @return bool */ protected function _isFile($filename) { if ($this->_fileStorageHelper->checkDbUsage() && !$this->getMediaDirectory()->isFile($filename)) { $this->_fileStorageHelper->saveFileToFilesystem($filename); } return $this->getMediaDirectory()->isFile($filename); }
/** * @param array $optionValue * @return void */ protected function initFilePath($optionValue) { /** * @see \Magento\Catalog\Model\Product\Option\Type\File\ValidatorFile::validate * There setUserValue() sets correct fileFullPath only for * quote_path. So we must form both full paths manually and * check them. */ $checkPaths = []; if (isset($optionValue['quote_path'])) { $checkPaths[] = $optionValue['quote_path']; } if (isset($optionValue['order_path']) && !$this->useQuotePath) { $checkPaths[] = $optionValue['order_path']; } foreach ($checkPaths as $path) { if (!$this->rootDirectory->isFile($path)) { if (!$this->coreFileStorageDatabase->saveFileToFilesystem($path)) { continue; } } $this->fileFullPath = $this->rootDirectory->getAbsolutePath($path); $this->fileRelativePath = $path; break; } }
/** * If DB file storage is on - find there, otherwise - just file_exists * * @param string $filename relative file path * @return bool */ protected function checkIsFile($filename) { if ($this->fileStorageDatabase->checkDbUsage() && !$this->mediaDirectory->isFile($filename)) { $this->fileStorageDatabase->saveFileToFilesystem($filename); } return $this->mediaDirectory->isFile($filename); }
/** * Retrieve media base directory path * * @return string */ public function getMediaBaseDirectory() { if (is_null($this->mediaBaseDirectory)) { $this->mediaBaseDirectory = $this->storageHelper->getMediaBaseDir(); } return $this->mediaBaseDirectory; }
/** * Check file in database storage if needed and place it on file system * * @param string $filePath * @param string $relativePath * @return bool */ protected function _processDatabaseFile($filePath, $relativePath) { if (!$this->_fileStorageDatabase->checkDbUsage()) { return false; } $file = $this->_storageDatabaseFactory->create()->loadByFilename($relativePath); if (!$file->getId()) { return false; } $stream = $this->_rootDir->openFile($relativePath, 'w+'); $stream->lock(); $stream->write($filePath, $file->getContent()); $stream->unlock(); $stream->close(); return true; }
/** * cover positive case for getFaviconFile and checkIsFile */ public function testGetFaviconFile() { $scopeConfigValue = 'path'; $urlToMediaDir = 'http://magento.url/pub/media/'; $expectedFile = ImageFavicon::UPLOAD_DIR . '/' . $scopeConfigValue; $expectedUrl = $urlToMediaDir . $expectedFile; $this->scopeManager->expects($this->once())->method('getValue')->with('design/head/shortcut_icon', ScopeInterface::SCOPE_STORE)->willReturn($scopeConfigValue); $this->store->expects($this->once())->method('getBaseUrl')->with(UrlInterface::URL_TYPE_MEDIA)->willReturn($urlToMediaDir); $this->fileStorageDatabase->expects($this->once())->method('checkDbUsage')->willReturn(true); $this->fileStorageDatabase->expects($this->once())->method('saveFileToFilesystem')->willReturn(true); $this->mediaDir->expects($this->at(0))->method('isFile')->with($expectedFile)->willReturn(false); $this->mediaDir->expects($this->at(1))->method('isFile')->with($expectedFile)->willReturn(true); $results = $this->object->getFaviconFile(); $this->assertEquals($expectedUrl, $results); $this->assertNotFalse($results); }
/** * Checking file for save and save it to tmp dir * * @param string $fileId * * @return string[] * * @throws \Magento\Framework\Exception\LocalizedException */ public function saveFileToTmpDir($fileId) { $baseTmpPath = $this->getBaseTmpPath(); $uploader = $this->uploaderFactory->create(['fileId' => $fileId]); $uploader->setAllowedExtensions($this->getAllowedExtensions()); $uploader->setAllowRenameFiles(true); $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath)); if (!$result) { throw new \Magento\Framework\Exception\LocalizedException(__('File can not be saved to the destination folder.')); } /** * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS */ $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']); $result['path'] = str_replace('\\', '/', $result['path']); $result['url'] = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $this->getFilePath($baseTmpPath, $result['file']); $result['name'] = $result['file']; if (isset($result['file'])) { try { $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/'); $this->coreFileStorageDatabase->saveFile($relativePath); } catch (\Exception $e) { $this->logger->critical($e); throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong while saving the file(s).')); } } return $result; }
public function testGetDirsCollectionCreateSubDirectories() { $directoryName = 'test1'; $this->coreFileStorageMock->expects($this->once())->method('checkDbUsage')->willReturn(true); $this->directoryCollectionMock->expects($this->once())->method('getSubdirectories')->with(self::STORAGE_ROOT_DIR)->willReturn([['name' => $directoryName]]); $this->directoryDatabaseFactoryMock->expects($this->once())->method('create')->willReturn($this->directoryCollectionMock); $this->directoryMock->expects($this->once())->method('create')->with(rtrim(self::STORAGE_ROOT_DIR, '/') . '/' . $directoryName); $this->generalTestGetDirsCollection(self::STORAGE_ROOT_DIR); }
/** * Check whether file to move exists. Getting unique name * * @param <type> $file * @return string */ protected function getUniqueFileName($file) { if ($this->fileStorageDb->checkDbUsage()) { $destFile = $this->fileStorageDb->getUniqueFilename($this->mediaConfig->getBaseMediaUrlAddition(), $file); } else { $destFile = dirname($file) . '/' . \Magento\MediaStorage\Model\File\Uploader::getNewFileName($this->mediaDirectory->getAbsolutePath($this->getAttributeSwatchPath($file))); } return $destFile; }
/** * Move file from tmp path to base path * * @param string $baseTmpPath * @param string $basePath * @param string $file * @return string */ protected function _moveFileFromTmp($baseTmpPath, $basePath, $file) { if (strrpos($file, '.tmp') == strlen($file) - 4) { $file = substr($file, 0, strlen($file) - 4); } $destFile = dirname($file) . '/' . \Magento\MediaStorage\Model\File\Uploader::getNewFileName($this->getFilePath($basePath, $file)); $this->_coreFileStorageDatabase->copyFile($this->getFilePath($baseTmpPath, $file), $this->getFilePath($basePath, $destFile)); $this->_mediaDirectory->renameFile($this->getFilePath($baseTmpPath, $file), $this->getFilePath($basePath, $destFile)); return str_replace('\\', '/', $destFile); }
public function testGetMediaBaseDir() { $mediaDirMock = $this->getMockForAbstractClass('\\Magento\\Framework\\Filesystem\\Directory\\ReadInterface'); $mediaDirMock->expects($this->any())->method('getAbsolutePath')->will($this->returnValue('media-dir')); $filesystemMock = $this->getMockBuilder('Magento\\Framework\\Filesystem')->disableOriginalConstructor()->getMock(); $filesystemMock->expects($this->once())->method('getDirectoryRead')->with(DirectoryList::MEDIA)->will($this->returnValue($mediaDirMock)); $this->helper = $this->objectManager->getObject('Magento\\MediaStorage\\Helper\\File\\Storage\\Database', ['filesystem' => $filesystemMock, 'fileStorage' => $this->fileStorageMock, 'dbStorageFactory' => $this->dbStorageFactoryMock, 'config' => $this->configMock]); $this->assertEquals('media-dir', $this->helper->getMediaBaseDir()); $this->assertEquals('media-dir', $this->helper->getMediaBaseDir()); }
public function testExecute() { $data = ['tmp_name' => 'tmp_name', 'path' => 'path', 'file' => 'file']; $uploader = $this->getMockBuilder('Magento\\MediaStorage\\Model\\File\\Uploader')->disableOriginalConstructor()->getMock(); $resultJson = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Json')->disableOriginalConstructor()->setMethods(['setData'])->getMock(); $this->request->expects($this->once())->method('getParam')->with('type')->willReturn('samples'); $this->sample->expects($this->once())->method('getBaseTmpPath')->willReturn('base_tmp_path'); $this->uploaderFactory->expects($this->once())->method('create')->willReturn($uploader); $this->fileHelper->expects($this->once())->method('uploadFromTmp')->willReturn($data); $this->storageDatabase->expects($this->once())->method('saveFile'); $this->session->expects($this->once())->method('getName')->willReturn('Name'); $this->session->expects($this->once())->method('getSessionId')->willReturn('SessionId'); $this->session->expects($this->once())->method('getCookieLifetime')->willReturn('CookieLifetime'); $this->session->expects($this->once())->method('getCookiePath')->willReturn('CookiePath'); $this->session->expects($this->once())->method('getCookieDomain')->willReturn('CookieDomain'); $this->resultFactory->expects($this->once())->method('create')->willReturn($resultJson); $resultJson->expects($this->once())->method('setData')->willReturnSelf(); $this->assertEquals($resultJson, $this->upload->execute()); }
/** * Delete file (and its thumbnail if exists) from storage * * @param string $target File path to be deleted * @return $this */ public function deleteFile($target) { $relativePath = $this->_directory->getRelativePath($target); if ($this->_directory->isFile($relativePath)) { $this->_directory->delete($relativePath); } $this->_coreFileStorageDb->deleteFile($target); $thumb = $this->getThumbnailPath($target, true); $relativePathThumb = $this->_directory->getRelativePath($thumb); if ($thumb) { if ($this->_directory->isFile($relativePathThumb)) { $this->_directory->delete($relativePathThumb); } $this->_coreFileStorageDb->deleteFile($thumb); } return $this; }
/** * Quote item to order item copy process * * @return $this */ public function copyQuoteToOrder() { $quoteOption = $this->getConfigurationItemOption(); try { $value = unserialize($quoteOption->getValue()); if (!isset($value['quote_path'])) { throw new \Exception(); } $quotePath = $value['quote_path']; $orderPath = $value['order_path']; if (!$this->_rootDirectory->isFile($quotePath) || !$this->_rootDirectory->isReadable($quotePath)) { throw new \Exception(); } $this->_coreFileStorageDatabase->copyFile($this->_rootDirectory->getAbsolutePath($quotePath), $this->_rootDirectory->getAbsolutePath($orderPath)); } catch (\Exception $e) { return $this; } return $this; }
/** * Copy image and return new filename. * * @param string $file * @return string * @throws \Magento\Framework\Exception\LocalizedException */ protected function _copyImage($file) { try { $destinationFile = $this->_getUniqueFileName($file); if (!$this->_mediaDirectory->isFile($this->_mediaConfig->getMediaPath($file))) { throw new \Exception(); } if ($this->_fileStorageDb->checkDbUsage()) { $this->_fileStorageDb->copyFile($this->_mediaDirectory->getAbsolutePath($this->_mediaConfig->getMediaShortUrl($file)), $this->_mediaConfig->getMediaShortUrl($destinationFile)); $this->_mediaDirectory->delete($this->_mediaConfig->getMediaPath($destinationFile)); } else { $this->_mediaDirectory->copyFile($this->_mediaConfig->getMediaPath($file), $this->_mediaConfig->getMediaPath($destinationFile)); } return str_replace('\\', '/', $destinationFile); } catch (\Exception $e) { $file = $this->_mediaConfig->getMediaPath($file); throw new LocalizedException(__('We couldn\'t copy file %1. Please delete media with non-existing images and try again.', $file)); } }
/** * Process File Queue * * @return $this * @throws \Magento\Framework\Exception\LocalizedException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function processFileQueue() { if (empty($this->_fileQueue)) { return $this; } foreach ($this->_fileQueue as &$queueOptions) { if (isset($queueOptions['operation']) && ($operation = $queueOptions['operation'])) { switch ($operation) { case 'receive_uploaded_file': $src = isset($queueOptions['src_name']) ? $queueOptions['src_name'] : ''; $dst = isset($queueOptions['dst_name']) ? $queueOptions['dst_name'] : ''; /** @var $uploader \Zend_File_Transfer_Adapter_Http */ $uploader = isset($queueOptions['uploader']) ? $queueOptions['uploader'] : null; $path = dirname($dst); try { $rootDir = $this->_filesystem->getDirectoryWrite(DirectoryList::ROOT); $rootDir->create($rootDir->getRelativePath($path)); } catch (\Magento\Framework\Exception\FileSystemException $e) { throw new \Magento\Framework\Exception\LocalizedException(__('We can\'t create writeable directory "%1".', $path)); } $uploader->setDestination($path); if (empty($src) || empty($dst) || !$uploader->receive($src)) { /** * @todo: show invalid option */ if (isset($queueOptions['option'])) { $queueOptions['option']->setIsValid(false); } throw new \Magento\Framework\Exception\LocalizedException(__('The file upload failed.')); } $this->_fileStorageDb->saveFile($dst); break; default: break; } } $queueOptions = null; } return $this; }
/** * Retrieve URL for media catalog * * If we use Database file storage and server doesn't support rewrites (.htaccess in media folder) * we have to put name of fetching media script exactly into URL * * @param Filesystem $filesystem * @param bool $secure * @return string|bool */ protected function _getMediaScriptUrl(Filesystem $filesystem, $secure) { if (!$this->getConfig(self::XML_PATH_USE_REWRITES) && $this->_coreFileStorageDatabase->checkDbUsage()) { $baseUrl = $this->getBaseUrl(UrlInterface::URL_TYPE_WEB, $secure); return $baseUrl . $filesystem->getUri(DirectoryList::PUB) . '/' . self::MEDIA_REWRITE_SCRIPT; } return false; }
public function testMoveImageFromTmpNoDb() { $this->fileStorageDbMock->method('checkDbUsage')->willReturn(false); $this->fileStorageDbMock->method('renameFile')->will($this->returnSelf()); $this->mediaHelperObject->moveImageFromTmp('file.tmp'); }
public function testClearCache() { $this->coreFileHelper->expects($this->once())->method('deleteFolder')->will($this->returnValue(true)); $this->image->clearCache(); }
/** * First check this file on FS * If it doesn't exist - try to download it from DB * * @param string $filename * @return bool */ protected function _fileExists($filename) { if ($this->_mediaDirectory->isFile($filename)) { return true; } else { return $this->_coreFileStorageDatabase->saveFileToFilesystem($this->_mediaDirectory->getAbsolutePath($filename)); } }