Example #1
0
 /**
  * Write down contents to a temporary file and return its absolute path
  *
  * @param string $relativePath
  * @param string $contents
  * @return string
  */
 public function createFile($relativePath, $contents)
 {
     $filePath = $this->config->getLessMaterializationRelativePath() . '/' . $relativePath;
     if (!$this->tmpDirectory->isExist($filePath)) {
         $this->tmpDirectory->writeFile($filePath, $contents);
     }
     return $this->tmpDirectory->getAbsolutePath($filePath);
 }
Example #2
0
 protected function setUp()
 {
     $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
     $filesystem = $this->_objectManager->create('Magento\\Framework\\App\\Filesystem');
     $this->_varDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem::VAR_DIR);
     $fullFileName = $this->_varDirectory->getAbsolutePath(self::FILE_PATH);
     $this->_testFileHandler = fopen($fullFileName, 'w');
 }
Example #3
0
 /**
  * Upload file from temporary folder.
  * @param string $tmpPath
  * @param \Magento\Core\Model\File\Uploader $uploader
  * @return array
  */
 public function uploadFromTmp($tmpPath, \Magento\Core\Model\File\Uploader $uploader)
 {
     $uploader->setAllowRenameFiles(true);
     $uploader->setFilesDispersion(true);
     $absoluteTmpPath = $this->_mediaDirectory->getAbsolutePath($tmpPath);
     $result = $uploader->save($absoluteTmpPath);
     return $result;
 }
Example #4
0
 /**
  * Flash ISM_BaseRunner cache
  * @param \Magento\Framework\Event\Observer $observer
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $dir = $this->_mediaDirectory->getAbsolutePath(Upload::UPLOAD_POST_IMAGE_DIR . 'cache/');
     if (is_dir($dir)) {
         $dir = $this->_mediaDirectory->getDriver()->readDirectory($dir);
         foreach ($dir as $file) {
             $this->_mediaDirectory->delete(Upload::UPLOAD_POST_IMAGE_DIR . 'cache/' . basename($file));
         }
     }
 }
 /**
  * Get backup-specific data from model for each row
  *
  * @param string $filename
  * @return array
  */
 protected function _generateRow($filename)
 {
     $row = parent::_generateRow($filename);
     foreach ($this->_backup->load($row['basename'], $this->_varDirectory->getAbsolutePath($this->_path))->getData() as $key => $value) {
         $row[$key] = $value;
     }
     $row['size'] = $this->_varDirectory->stat($this->_varDirectory->getRelativePath($filename))['size'];
     $row['id'] = $row['time'] . '_' . $row['type'];
     return $row;
 }
Example #6
0
 /**
  * Get path to PayPal certificate file, if file does not exist try to create it
  *
  * @return string
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function getCertPath()
 {
     if (!$this->getContent()) {
         throw new \Magento\Framework\Exception\LocalizedException(__('The PayPal certificate does not exist.'));
     }
     $certFileName = sprintf('cert_%s_%s.pem', $this->getWebsiteId(), strtotime($this->getUpdatedAt()));
     $certFile = self::BASEPATH_PAYPAL_CERT . $certFileName;
     if (!$this->varDirectory->isExist($certFile)) {
         $this->_createCertFile($certFile);
     }
     return $this->varDirectory->getAbsolutePath($certFile);
 }
Example #7
0
 /**
  * Get backup-specific data from model for each row
  *
  * @param string $filename
  * @return array
  */
 protected function _generateRow($filename)
 {
     $row = parent::_generateRow($filename);
     foreach ($this->_backup->load($row['basename'], $this->_varDirectory->getAbsolutePath($this->_path))->getData() as $key => $value) {
         $row[$key] = $value;
     }
     $row['size'] = $this->_varDirectory->stat($this->_varDirectory->getRelativePath($filename))['size'];
     if (isset($row['display_name']) && $row['display_name'] == '') {
         $row['display_name'] = 'WebSetupWizard';
     }
     $row['id'] = $row['time'] . '_' . $row['type'] . (isset($row['display_name']) ? $row['display_name'] : '');
     return $row;
 }
Example #8
0
 /**
  * @param string $dbCode
  * @throws LocalizedException
  */
 protected function unpackDb($dbCode)
 {
     $this->archive->unpack($this->directory->getAbsolutePath($this->getDbArchiveFilePath($dbCode)), $this->directory->getAbsolutePath($this->database->getDbPath($dbCode)));
     if (!$this->directory->isExist($this->database->getDbPath($dbCode))) {
         throw new LocalizedException(__('Cannot unpack db file.'));
     }
 }
 /**
  * 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;
 }
Example #10
0
    /**
     * Perform necessary preprocessing and materialization when the specified asset is requested
     *
     * Returns an array of two elements:
     * - directory where the file is supposed to be found
     * - relative path to the file
     *
     * returns false if source file was not found
     *
     * @param LocalInterface $asset
     * @return array|bool
     */
    private function preProcess(LocalInterface $asset)
    {
        $sourceFile = $this->findSourceFile($asset);
        $dir = $this->rootDir->getAbsolutePath();
        $path = '';
        if ($sourceFile) {
            $path = basename($sourceFile);
            $dir = dirname($sourceFile);
        }

        $chain = $this->createChain($asset, $dir, $path);
        $this->preProcessorPool->process($chain);
        $chain->assertValid();
        if ($chain->isChanged()) {
            $dir = $this->varDir->getAbsolutePath();
            $path = DirectoryList::TMP_MATERIALIZATION_DIR . '/source/' . $chain->getTargetAssetPath();
            $this->varDir->writeFile($path, $chain->getContent());
        }
        if (empty($path)) {
            $result = false;
        } else {
            $result = [$dir, $path];
        }
        return $result;
    }
Example #11
0
 /**
  * Save new image and remove old image.
  *
  * @param $file string new file
  * @param $old  string old file
  *
  * @return string file name
  * @throws LocalizedException
  */
 public function saveImage($file, $old)
 {
     $uploadDir = $this->_mediaDirectory->getAbsolutePath(self::UPLOAD_POST_IMAGE_DIR);
     try {
         $uploader = $this->_uploaderFactory->create(['fileId' => $file]);
         $uploader->setAllowedExtensions(self::TYPES_ALLOWED);
         $uploader->setAllowRenameFiles(true);
         $uploader->addValidateCallback('size', $this, 'validateMaxSize');
         $result = $uploader->save($uploadDir);
     } catch (\Exception $e) {
         throw new LocalizedException(__($e->getMessage()));
     }
     if ($old) {
         $this->removeImage($old);
     }
     return $result['file'];
 }
 /**
  * Check whether file to move exists. Getting unique name
  *
  * @param string $file
  * @param bool $forTmp
  * @return string
  */
 protected function getUniqueFileName($file, $forTmp = false)
 {
     if ($this->fileStorageDb->checkDbUsage()) {
         $destFile = $this->fileStorageDb->getUniqueFilename($this->mediaConfig->getBaseMediaUrlAddition(), $file);
     } else {
         $destinationFile = $forTmp ? $this->mediaDirectory->getAbsolutePath($this->mediaConfig->getTmpMediaPath($file)) : $this->mediaDirectory->getAbsolutePath($this->mediaConfig->getMediaPath($file));
         $destFile = dirname($file) . '/' . \Magento\MediaStorage\Model\File\Uploader::getNewFileName($destinationFile);
     }
     return $destFile;
 }
Example #13
0
 /**
  * Move files from TMP folder into destination folder
  *
  * @param string $tmpPath
  * @param string $destPath
  * @return bool
  */
 protected function _moveFile($tmpPath, $destPath)
 {
     if ($this->_directory->isFile($tmpPath)) {
         $tmpRealPath = $this->_directory->getDriver()->getRealPath($this->_directory->getAbsolutePath($tmpPath));
         $destinationRealPath = $this->_directory->getDriver()->getRealPath($this->_directory->getAbsolutePath($destPath));
         $isSameFile = $tmpRealPath === $destinationRealPath;
         return $isSameFile ?: $this->_directory->copyFile($tmpPath, $destPath);
     } else {
         return false;
     }
 }
Example #14
0
 /**
  * Check thumbnail and create it if need.
  *
  * @return bool
  */
 public function checkAndCreate()
 {
     if ($this->_mediaDirectory->isFile($this->_cacheDir . $this->_post->getImageUrl())) {
         return true;
     }
     if (!$this->_mediaDirectory->isFile(Upload::UPLOAD_POST_IMAGE_DIR . $this->_post->getImageUrl())) {
         return false;
     }
     $image = $this->_imageFactory->create(array('file' => $this->_mediaDirectory->getAbsolutePath(Upload::UPLOAD_POST_IMAGE_DIR . $this->_post->getImageUrl())));
     $image->setWH(75, 75);
     $image->resize();
     $image->save(DirectoryList::PUB . DIRECTORY_SEPARATOR . DirectoryList::MEDIA . DIRECTORY_SEPARATOR . $this->_cacheDir . $this->_post->getImageUrl());
     return true;
 }
 /**
  * Retrieve destination directory for given content type
  *
  * @param string $contentType
  * @return string
  * @throws \InvalidArgumentException
  */
 protected function getDestinationDirectory($contentType)
 {
     switch ($contentType) {
         case 'link_file':
             $directory = $this->mediaDirectory->getAbsolutePath($this->linkConfig->getBaseTmpPath());
             break;
         case 'link_sample_file':
             $directory = $this->mediaDirectory->getAbsolutePath($this->linkConfig->getBaseSampleTmpPath());
             break;
         case 'sample':
             $directory = $this->mediaDirectory->getAbsolutePath($this->sampleConfig->getBaseTmpPath());
             break;
         default:
             throw new \InvalidArgumentException('Invalid downloadable file content type.');
     }
     return $directory;
 }
Example #16
0
 /**
  * @return string Path to config file
  * @throws \Exception
  */
 public function makeConfig()
 {
     if (!$this->directory->isExist($this->basePath)) {
         //$this->directory->delete($this->basePath);
         $this->directory->create($this->basePath);
         $this->directory->changePermissions($this->basePath, 0777);
     }
     $jsonData = [];
     $sphinxData = ['time' => date('d.m.Y H:i:s'), 'host' => $this->host, 'port' => $this->port, 'fallback_port' => $this->port - 1, 'logdir' => $this->directory->getAbsolutePath($this->basePath), 'sphinxdir' => $this->directory->getAbsolutePath($this->basePath), 'indexes' => '', 'localdir' => dirname(dirname(__FILE__)), 'custom' => $this->config->getAdditionalSearchdConfig()];
     $sphinxTemplate = $this->config->getSphinxConfigurationTemplate();
     $indexTemplate = $this->config->getSphinxIndexConfigurationTemplate();
     /** @var \Mirasvit\Search\Model\Index $index */
     foreach ($this->indexCollectionFactory->create() as $index) {
         foreach (array_keys($this->storeManager->getStores()) as $storeId) {
             $indexName = $index->getIndexInstance()->getIndexer()->getIndexName($storeId);
             $data = ['name' => $indexName, 'min_word_len' => 1, 'path' => $this->directory->getAbsolutePath($this->basePath) . '/' . $indexName, 'custom' => $this->config->getAdditionalIndexConfig()];
             $jsonAttributes = [];
             $attributes = [];
             foreach (array_keys($index->getIndexInstance()->getAttributes(true)) as $attribute) {
                 $attributes[] = "    rt_field = {$attribute}";
                 $jsonAttributes[] = $attribute;
                 if (count($attributes) > 250) {
                     break;
                 }
             }
             $attributes[] = "    rt_field = options";
             $jsonAttributes[] = "options";
             $data['attributes'] = implode(PHP_EOL, $attributes);
             $sphinxData['indexes'] .= $this->helper->filterTemplate($indexTemplate, $data);
             $jsonData[$indexName] = $jsonAttributes;
         }
     }
     $config = $this->helper->filterTemplate($sphinxTemplate, $sphinxData);
     if ($this->directory->isWritable($this->basePath)) {
         $this->directory->writeFile($this->configFilePath, $config);
         $this->directory->writeFile($this->configFilePath . '.attr', json_encode($jsonData));
     } else {
         if ($this->directory->isExist($this->configFilePath)) {
             throw new \Exception(__('File %1 does not writable', $this->configFilePath));
         } else {
             throw new \Exception(__('Directory %1 does not writable', $this->basePath));
         }
     }
     return $this->directory->getAbsolutePath($this->configFilePath);
 }
Example #17
0
 /**
  * @magentoConfigFixture current_store dev/css/minify_files 1
  */
 public function testDeploymentWithMinifierEnabled()
 {
     $staticPath = $this->staticDir->getAbsolutePath();
     $fileToBePublished = $staticPath . '/frontend/FrameworkViewMinifier/default/en_US/css/styles.min.css';
     $fileToTestPublishing = dirname(__DIR__) . '/_files/static/theme/web/css/styles.css';
     $omFactory = $this->getMock(\Magento\Framework\App\ObjectManagerFactory::class, ['create'], [], '', false);
     $omFactory->expects($this->any())->method('create')->will($this->returnValue($this->objectManager));
     $output = $this->objectManager->create(\Symfony\Component\Console\Output\ConsoleOutput::class);
     $filesUtil = $this->getMock(\Magento\Framework\App\Utility\Files::class, [], [], '', false);
     $filesUtil->expects($this->any())->method('getStaticLibraryFiles')->will($this->returnValue([]));
     $filesUtil->expects($this->any())->method('getPhtmlFiles')->will($this->returnValue([]));
     $filesUtil->expects($this->any())->method('getStaticPreProcessingFiles')->will($this->returnValue([['frontend', 'FrameworkViewMinifier/default', '', '', 'css/styles.css', $fileToTestPublishing]]));
     /** @var \Magento\Deploy\Model\Deployer $deployer */
     $deployer = $this->objectManager->create(\Magento\Deploy\Model\Deployer::class, ['filesUtil' => $filesUtil, 'output' => $output]);
     $deployer->deploy($omFactory, ['en_US'], ['frontend' => ['FrameworkViewMinifier/default']]);
     $this->assertFileExists($fileToBePublished);
     $this->assertEquals(file_get_contents(dirname(__DIR__) . '/_files/static/expected/styles.magento.min.css'), file_get_contents($fileToBePublished), 'Minified file is not equal or minification did not work for deployed CSS');
 }
Example #18
0
 /**
  * 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));
     }
 }
Example #19
0
 /**
  * Return path to directory for upload file
  *
  * @return string
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function _getUploadDir()
 {
     $fieldConfig = $this->getFieldConfig();
     /* @var $fieldConfig \Magento\Framework\Simplexml\Element */
     if (!array_key_exists('upload_dir', $fieldConfig)) {
         throw new \Magento\Framework\Exception\LocalizedException(__('The base directory to upload file is not specified.'));
     }
     if (is_array($fieldConfig['upload_dir'])) {
         $uploadDir = $fieldConfig['upload_dir']['value'];
         if (array_key_exists('scope_info', $fieldConfig['upload_dir']) && $fieldConfig['upload_dir']['scope_info']) {
             $uploadDir = $this->_appendScopeInfo($uploadDir);
         }
         if (array_key_exists('config', $fieldConfig['upload_dir'])) {
             $uploadDir = $this->_mediaDirectory->getAbsolutePath($uploadDir);
         }
     } else {
         $uploadDir = (string) $fieldConfig['upload_dir'];
     }
     return $uploadDir;
 }
Example #20
0
 /**
  * Log debug data to file.
  * Log file dir: var/log/import_export/%Y/%m/%d/%time%_%operation_type%_%entity_type%.log
  *
  * @param mixed $debugData
  * @return $this
  */
 public function addLogComment($debugData)
 {
     if (is_array($debugData)) {
         $this->_logTrace = array_merge($this->_logTrace, $debugData);
     } else {
         $this->_logTrace[] = $debugData;
     }
     if (!$this->_debugMode) {
         return $this;
     }
     if (!$this->_logInstance) {
         $dirName = date('Y/m/d/');
         $fileName = join('_', array(str_replace(':', '-', $this->getRunAt()), $this->getScheduledOperationId(), $this->getOperationType(), $this->getEntity()));
         $path = 'import_export/' . $dirName;
         $this->_varDirectory->create($path);
         $fileName = $path . $fileName . '.log';
         $this->_logInstance = $this->_adapterFactory->create(array('fileName' => $this->_varDirectory->getAbsolutePath($fileName)))->setFilterDataKeys($this->_debugReplacePrivateDataKeys);
     }
     $this->_logInstance->log($debugData);
     return $this;
 }
Example #21
0
 /**
  * Enables apppropriate cache types in app/etc/env.php based on the passed in $cacheTypes array
  * TODO: to be removed in scope of MAGETWO-53476
  *
  * @param string[]
  *
  * @return void
  */
 private function enableCacheTypes($cacheTypes)
 {
     if (empty($cacheTypes)) {
         return;
     }
     $envPath = $this->getEnvPath();
     if ($this->write->isReadable($this->write->getRelativePath($envPath))) {
         $envData = (include $envPath);
         foreach ($cacheTypes as $cacheType) {
             if (isset($envData['cache_types'][$cacheType])) {
                 $envData['cache_types'][$cacheType] = 1;
             }
         }
         $formatter = new PhpFormatter();
         $contents = $formatter->format($envData);
         $this->write->writeFile($this->write->getRelativePath($envPath), $contents);
         if (function_exists('opcache_invalidate')) {
             opcache_invalidate($this->write->getAbsolutePath($envPath));
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function processImageContent($entityType, $imageContent)
 {
     if (!$this->contentValidator->isValid($imageContent)) {
         throw new InputException(new Phrase('The image content is not valid.'));
     }
     $fileContent = @base64_decode($imageContent->getBase64EncodedData(), true);
     $tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
     $fileName = substr(md5(rand()), 0, 7) . '.' . $imageContent->getName();
     $tmpDirectory->writeFile($fileName, $fileContent);
     $fileAttributes = ['tmp_name' => $tmpDirectory->getAbsolutePath() . $fileName, 'name' => $imageContent->getName()];
     try {
         $this->uploader->processFileAttributes($fileAttributes);
         $this->uploader->setFilesDispersion(true);
         $this->uploader->setFilenamesCaseSensitivity(false);
         $this->uploader->setAllowRenameFiles(true);
         $destinationFolder = $entityType;
         $this->uploader->save($this->mediaDirectory->getAbsolutePath($destinationFolder), $imageContent->getName());
     } catch (\Exception $e) {
         $this->logger->critical($e);
     }
     return $this->uploader->getUploadedFileName();
 }
Example #23
0
 /**
  * Goes to specified host/path and fetches reports from there.
  * Save reports to database.
  *
  * @param \Magento\Framework\Filesystem\Io\Sftp $connection
  * @return int Number of report rows that were fetched and saved successfully
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function fetchAndSave(\Magento\Framework\Filesystem\Io\Sftp $connection)
 {
     $fetched = 0;
     $listing = $this->_filterReportsList($connection->rawls());
     foreach ($listing as $filename => $attributes) {
         $localCsv = 'PayPal_STL_' . uniqid(\Magento\Framework\Math\Random::getRandomNumber()) . time() . '.csv';
         if ($connection->read($filename, $this->_tmpDirectory->getAbsolutePath($localCsv))) {
             if (!$this->_tmpDirectory->isWritable($localCsv)) {
                 throw new \Magento\Framework\Exception\LocalizedException(__('We cannot create a target file for reading reports.'));
             }
             $encoded = $this->_tmpDirectory->readFile($localCsv);
             $csvFormat = 'new';
             $fileEncoding = mb_detect_encoding($encoded);
             if (self::FILES_OUT_CHARSET != $fileEncoding) {
                 $decoded = @iconv($fileEncoding, self::FILES_OUT_CHARSET . '//IGNORE', $encoded);
                 $this->_tmpDirectory->writeFile($localCsv, $decoded);
                 $csvFormat = 'old';
             }
             // Set last modified date, this value will be overwritten during parsing
             if (isset($attributes['mtime'])) {
                 $date = new \DateTime();
                 $lastModified = $date->setTimestamp($attributes['mtime']);
                 $this->setReportLastModified($lastModified->format('Y-m-d H:i:s'));
             }
             $this->setReportDate($this->_fileNameToDate($filename))->setFilename($filename)->parseCsv($localCsv, $csvFormat);
             if ($this->getAccountId()) {
                 $this->save();
             }
             if ($this->_dataSaveAllowed) {
                 $fetched += count($this->_rows);
             }
             // clean object and remove parsed file
             $this->unsetData();
             $this->_tmpDirectory->delete($localCsv);
         }
     }
     return $fetched;
 }
Example #24
0
 /**
  * Insert logo to pdf page
  *
  * @param \Zend_Pdf_Page &$page
  * @param null $store
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function insertLogo(&$page, $store = null)
 {
     $this->y = $this->y ? $this->y : 815;
     $image = $this->_scopeConfig->getValue('sales/identity/logo', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store);
     if ($image) {
         $imagePath = '/sales/store/logo/' . $image;
         if ($this->_mediaDirectory->isFile($imagePath)) {
             $image = \Zend_Pdf_Image::imageWithPath($this->_mediaDirectory->getAbsolutePath($imagePath));
             $top = 830;
             //top border of the page
             $widthLimit = 270;
             //half of the page width
             $heightLimit = 270;
             //assuming the image is not a "skyscraper"
             $width = $image->getPixelWidth();
             $height = $image->getPixelHeight();
             //preserving aspect ratio (proportions)
             $ratio = $width / $height;
             if ($ratio > 1 && $width > $widthLimit) {
                 $width = $widthLimit;
                 $height = $width / $ratio;
             } elseif ($ratio < 1 && $height > $heightLimit) {
                 $height = $heightLimit;
                 $width = $height * $ratio;
             } elseif ($ratio == 1 && $height > $heightLimit) {
                 $height = $heightLimit;
                 $width = $widthLimit;
             }
             $y1 = $top - $height;
             $y2 = $top;
             $x1 = 25;
             $x2 = $x1 + $width;
             //coordinates after transformation are rounded by Zend
             $page->drawImage($image, $x1, $y1, $x2, $y2);
             $this->y = $y1 - 10;
         }
     }
 }
Example #25
0
 /**
  * Run application
  *
  * @return Response
  * @throws \LogicException
  */
 public function launch()
 {
     if ($this->mediaDirectoryPath !== $this->directory->getAbsolutePath()) {
         // Path to media directory changed or absent - update the config
         /** @var \Magento\MediaStorage\Model\File\Storage\Config $config */
         $config = $this->configFactory->create(['cacheFile' => $this->configCacheFile]);
         $config->save();
         $this->mediaDirectoryPath = $config->getMediaDirectory();
         $allowedResources = $config->getAllowedResources();
         $isAllowed = $this->isAllowed;
         if (!$isAllowed($this->relativeFileName, $allowedResources)) {
             throw new \LogicException('The specified path is not allowed.');
         }
     }
     /** @var \Magento\MediaStorage\Model\File\Storage\Synchronization $sync */
     $sync = $this->syncFactory->create(['directory' => $this->directory]);
     $sync->synchronize($this->relativeFileName);
     if ($this->directory->isReadable($this->relativeFileName)) {
         $this->response->setFilePath($this->directory->getAbsolutePath($this->relativeFileName));
     } else {
         $this->response->setHttpResponseCode(404);
     }
     return $this->response;
 }
Example #26
0
 /**
  * Get log file path
  *
  * @return string
  */
 public function getLogFilePath()
 {
     return $this->varReaderWriter->getAbsolutePath($this->logFilePath);
 }
Example #27
0
 /**
  * Reads file info
  *
  * @param string $filePath
  * @return array
  */
 protected function _readFileInfo($filePath)
 {
     $fullFilePath = $this->_directory->getAbsolutePath($filePath);
     $fileInfo = pathinfo($fullFilePath);
     return ['name' => $fileInfo['basename'], 'type' => $this->_getMimeTypeByExt($fileInfo['extension']), 'tmp_name' => $filePath, 'error' => 0, 'size' => $this->_directory->stat($filePath)['size']];
 }
Example #28
0
 /**
  * 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));
     }
 }
Example #29
0
 /**
  * Validate uploaded file
  *
  * @return $this
  * @throws \Magento\Framework\Model\Exception
  */
 protected function _validateUploadedFile()
 {
     $option = $this->getOption();
     $processingParams = $this->_getProcessingParams();
     /**
      * Upload init
      */
     $upload = new \Zend_File_Transfer_Adapter_Http();
     $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file';
     $maxFileSize = $this->getFileSizeService()->getMaxFileSize();
     try {
         $runValidation = $option->getIsRequire() || $upload->isUploaded($file);
         if (!$runValidation) {
             $this->setUserValue(null);
             return $this;
         }
         $fileInfo = $upload->getFileInfo($file);
         $fileInfo = $fileInfo[$file];
         $fileInfo['title'] = $fileInfo['name'];
     } catch (\Exception $e) {
         // when file exceeds the upload_max_filesize, $_FILES is empty
         if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $maxFileSize) {
             $this->setIsValid(false);
             $value = $this->getFileSizeService()->getMaxFileSizeInMb();
             throw new Exception(__("The file you uploaded is larger than %1 Megabytes allowed by server", $value));
         } else {
             switch ($this->getProcessMode()) {
                 case \Magento\Catalog\Model\Product\Type\AbstractType::PROCESS_MODE_FULL:
                     throw new Exception(__('Please specify the product\'s required option(s).'));
                     break;
                 default:
                     $this->setUserValue(null);
                     break;
             }
             return $this;
         }
     }
     /**
      * Option Validations
      */
     // Image dimensions
     $_dimentions = array();
     if ($option->getImageSizeX() > 0) {
         $_dimentions['maxwidth'] = $option->getImageSizeX();
     }
     if ($option->getImageSizeY() > 0) {
         $_dimentions['maxheight'] = $option->getImageSizeY();
     }
     if (count($_dimentions) > 0) {
         $upload->addValidator('ImageSize', false, $_dimentions);
     }
     // File extension
     $_allowed = $this->_parseExtensionsString($option->getFileExtension());
     if ($_allowed !== null) {
         $upload->addValidator('Extension', false, $_allowed);
     } else {
         $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions'));
         if ($_forbidden !== null) {
             $upload->addValidator('ExcludeExtension', false, $_forbidden);
         }
     }
     // Maximum filesize
     $upload->addValidator('FilesSize', false, array('max' => $maxFileSize));
     /**
      * Upload process
      */
     $this->_initFilesystem();
     if ($upload->isUploaded($file) && $upload->isValid($file)) {
         $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
         $fileName = \Magento\Core\Model\File\Uploader::getCorrectFileName($fileInfo['name']);
         $dispersion = \Magento\Core\Model\File\Uploader::getDispretionPath($fileName);
         $filePath = $dispersion;
         $tmpDirectory = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem::SYS_TMP_DIR);
         $fileHash = md5($tmpDirectory->readFile($tmpDirectory->getRelativePath($fileInfo['tmp_name'])));
         $filePath .= '/' . $fileHash . '.' . $extension;
         $fileFullPath = $this->_mediaDirectory->getAbsolutePath($this->_quotePath . $filePath);
         $upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true));
         $this->getProduct()->getTypeInstance()->addFileQueue(array('operation' => 'receive_uploaded_file', 'src_name' => $file, 'dst_name' => $fileFullPath, 'uploader' => $upload, 'option' => $this));
         $_width = 0;
         $_height = 0;
         if ($tmpDirectory->isReadable($tmpDirectory->getRelativePath($fileInfo['tmp_name']))) {
             $_imageSize = getimagesize($fileInfo['tmp_name']);
             if ($_imageSize) {
                 $_width = $_imageSize[0];
                 $_height = $_imageSize[1];
             }
         }
         $uri = $this->_filesystem->getUri(\Magento\Framework\App\Filesystem::MEDIA_DIR);
         $this->setUserValue(array('type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $uri . $this->_quotePath . $filePath, 'order_path' => $uri . $this->_orderPath . $filePath, 'fullpath' => $fileFullPath, 'size' => $fileInfo['size'], 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20)));
     } elseif ($upload->getErrors()) {
         $errors = $this->_getValidatorErrors($upload->getErrors(), $fileInfo);
         if (count($errors) > 0) {
             $this->setIsValid(false);
             throw new Exception(implode("\n", $errors));
         }
     } else {
         $this->setIsValid(false);
         throw new Exception(__('Please specify the product\'s required option(s).'));
     }
     return $this;
 }
Example #30
0
 /**
  * Generate swatch path and name for saving
  *
  * @param array $imageConfig
  * @param string $imageUrl
  * @param string $swatchType
  * @return array
  */
 protected function generateNamePath($imageConfig, $imageUrl, $swatchType)
 {
     $fileName = $this->prepareFileName($imageUrl);
     $absolutePath = $this->mediaDirectory->getAbsolutePath($this->getSwatchCachePath($swatchType));
     return ['path_for_save' => $absolutePath . $this->getFolderNameSize($swatchType, $imageConfig) . $fileName['path'], 'name' => $fileName['name']];
 }