/** * Current * * @return string */ public function current() { if (!isset($this->cached[$this->key()])) { $this->cached[$this->key()] = $this->directoryRead->readFile($this->key()); } return $this->cached[$this->key()]; }
/** * Load and merge all phrases from language packs by specified code * * Takes into account inheritance between language packs * Returns associative array where key is phrase in the source code and value is its translation * * @param string $languageCode * @return array */ public function getDictionary($languageCode) { $languages = []; $declarations = $this->dir->search('*/*/language.xml'); foreach ($declarations as $file) { $xmlSource = $this->dir->readFile($file); $languageConfig = $this->configFactory->create(['source' => $xmlSource]); $this->packList[$languageConfig->getVendor()][$languageConfig->getPackage()] = $languageConfig; if ($languageConfig->getCode() === $languageCode) { $languages[] = $languageConfig; } } // Collect the inherited packages with meta-information of sorting $packs = []; foreach ($languages as $languageConfig) { $this->collectInheritedPacks($languageConfig, $packs); } uasort($packs, [$this, 'sortInherited']); // Merge all packages of translation to one dictionary $result = []; foreach ($packs as $packInfo) { /** @var Config $languageConfig */ $languageConfig = $packInfo['language']; $dictionary = $this->readPackCsv($languageConfig->getVendor(), $languageConfig->getPackage()); $result = array_merge($result, $dictionary); } return $result; }
/** * {@inheritdoc} */ public function get($filename, $scope) { switch ($scope) { case 'global': $iterator = $this->moduleReader->getConfigurationFiles($filename)->toArray(); $themeConfigFile = $this->currentTheme->getCustomization()->getCustomViewConfigPath(); if ($themeConfigFile && $this->rootDirectory->isExist($this->rootDirectory->getRelativePath($themeConfigFile))) { $iterator[$this->rootDirectory->getRelativePath($themeConfigFile)] = $this->rootDirectory->readFile($this->rootDirectory->getRelativePath($themeConfigFile)); } else { $designPath = $this->resolver->resolve(RulePool::TYPE_FILE, 'etc/view.xml', $this->area, $this->currentTheme); if (file_exists($designPath)) { try { $designDom = new \DOMDocument(); $designDom->load($designPath); $iterator[$designPath] = $designDom->saveXML(); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Could not read config file')); } } } break; default: $iterator = $this->iteratorFactory->create([]); break; } return $iterator; }
/** * Returns contents of License file. * * @return string */ public function getContents() { if (!$this->dir->isFile(self::LICENSE_FILENAME)) { return false; } return $this->dir->readFile(self::LICENSE_FILENAME); }
/** * Get an array of URNs * * @param OutputInterface $output * @return array */ private function getUrnDictionary(OutputInterface $output) { $files = $this->filesUtility->getXmlCatalogFiles('*.xml'); $files = array_merge($files, $this->filesUtility->getXmlCatalogFiles('*.xsd')); $urns = []; foreach ($files as $file) { $content = $this->rootDirRead->readFile($this->rootDirRead->getRelativePath($file[0])); $matches = []; preg_match_all('/schemaLocation="(urn\\:magento\\:[^"]*)"/i', $content, $matches); if (isset($matches[1])) { $urns = array_merge($urns, $matches[1]); } } $urns = array_unique($urns); $paths = []; foreach ($urns as $urn) { try { $paths[$urn] = $this->urnResolver->getRealPath($urn); } catch (\Exception $e) { // don't add unsupported element to array if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln($e->getMessage()); } } } return $paths; }
/** * Minify template file * * @param string $file * @return void */ public function minify($file) { $file = $this->rootDirectory->getRelativePath($file); $content = preg_replace('#(?<!]]>)\\s+</#', '</', preg_replace('#((?:<\\?php\\s+(?!echo|print|if|elseif|else)[^\\?]*)\\?>)\\s+#', '$1 ', preg_replace('#(?<!' . implode('|', $this->inlineHtmlTags) . ')\\> \\<#', '><', preg_replace('#(?ix)(?>[^\\S ]\\s*|\\s{2,})(?=(?:(?:[^<]++|<(?!/?(?:textarea|pre|script)\\b))*+)' . '(?:<(?>textarea|pre|script)\\b|\\z))#', ' ', preg_replace('#(?<!:|\\\\|\'|")//(?!\\s*\\<\\!\\[)(?!\\s*]]\\>)[^\\n\\r]*#', '', preg_replace('#(?<!:)//[^\\n\\r]*(\\s\\?\\>)#', '$1', preg_replace('#//[^\\n\\r]*(\\<\\?php)[^\\n\\r]*(\\s\\?\\>)[^\\n\\r]*#', '', $this->rootDirectory->readFile($file)))))))); if (!$this->htmlDirectory->isExist()) { $this->htmlDirectory->create(); } $this->htmlDirectory->writeFile($file, rtrim($content)); }
/** * Returns contents of License file. * * @return string|boolean */ public function getContents() { if ($this->dir->isFile(self::LICENSE_FILENAME)) { return $this->dir->readFile(self::LICENSE_FILENAME); } elseif ($this->dir->isFile(self::DEFAULT_LICENSE_FILENAME)) { return $this->dir->readFile(self::DEFAULT_LICENSE_FILENAME); } else { return false; } }
/** * Fetches and outputs file to user browser * $info is array with following indexes: * - 'path' - full file path * - 'type' - mime type of file * - 'size' - size of file * - 'title' - user-friendly name of file (usually - original name as uploaded in Magento) * * @param \Magento\Framework\App\ResponseInterface $response * @param string $filePath * @param array $info * @return bool */ public function downloadFileOption($response, $filePath, $info) { try { $response->setHttpResponseCode(200)->setHeader('Pragma', 'public', true)->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)->setHeader('Content-type', $info['type'], true)->setHeader('Content-Length', $info['size'])->setHeader('Content-Disposition', 'inline' . '; filename=' . $info['title'])->clearBody(); $response->sendHeaders(); echo $this->directory->readFile($this->directory->getRelativePath($filePath)); } catch (\Exception $e) { return false; } return true; }
/** * Get translation data * * @param string $themePath * @return string[] * @throws \Exception * @throws \Magento\Framework\Exception */ public function getData($themePath) { $dictionary = []; $files = $this->filesUtility->getJsFiles($this->appState->getAreaCode(), $themePath); foreach ($files as $filePath) { $content = $this->rootDirectory->readFile($this->rootDirectory->getRelativePath($filePath[0])); foreach ($this->getPhrases($content) as $phrase) { $translatedPhrase = (string) __($phrase); if ($phrase != $translatedPhrase) { $dictionary[$phrase] = $translatedPhrase; } } } return $dictionary; }
/** * Read Magento updater application jobs queue as a JSON string. * * @return string Queue file content (valid JSON string) * @throws \RuntimeException */ public function read() { $queue = ''; if (!$this->reader->isExist($this->queueFileBasename)) { return $queue; } $queueFileContent = $this->reader->readFile($this->queueFileBasename); if ($queueFileContent) { json_decode($queueFileContent); if (json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException(sprintf('Content of "%s" must be a valid JSON.', $this->queueFileBasename)); } $queue = $queueFileContent; } return $queue; }
/** * Checks existence of composer.lock and returns its contents * * @return array * @throws \Exception */ private function getComposerInfo() { if (!$this->rootDir->isExist('composer.lock')) { throw new \Exception('Cannot read \'composer.lock\' file'); } return json_decode($this->rootDir->readFile('composer.lock'), true); }
/** * Perform necessary preprocessing and materialization when the specified asset is requested * * Returns an array of two elements: * - directory code where the file is supposed to be found * - relative path to the file * * Automatically caches the obtained successful results or returns false if source file was not found * * @param LocalInterface $asset * @return array|bool */ private function preProcess(LocalInterface $asset) { $sourceFile = $this->findSourceFile($asset); $dirCode = DirectoryList::ROOT; $path = $this->rootDir->getRelativePath($sourceFile); $cacheId = $path . ':' . $asset->getPath(); $cached = $this->cache->load($cacheId); if ($cached) { return unserialize($cached); } $origContent = $path ? $this->rootDir->readFile($path) : ''; $origContentType = $this->getContentType($path) ?: $asset->getContentType(); $chain = $this->chainFactory->create( [ 'asset' => $asset, 'origContent' => $origContent, 'origContentType' => $origContentType, 'origAssetPath' => $path ] ); $this->preProcessorPool->process($chain); $chain->assertValid(); if ($chain->isChanged()) { $dirCode = DirectoryList::VAR_DIR; $path = DirectoryList::TMP_MATERIALIZATION_DIR . '/source/' . $chain->getTargetAssetPath(); $this->varDir->writeFile($path, $chain->getContent()); } $result = [$dirCode, $path]; $this->cache->save(serialize($result), $cacheId); return $result; }
/** * {@inheritdoc} */ public function getContent() { if (null === $this->path) { $this->process(); } return $this->staticViewDir->readFile($this->path); }
/** * Render view config object for current package and theme * * @param array $params * @return \Magento\Framework\Config\View */ public function getViewConfig(array $params = []) { $this->assetRepo->updateDesignParams($params); /** @var $currentTheme \Magento\Framework\View\Design\ThemeInterface */ $currentTheme = $params['themeModel']; $key = $currentTheme->getCode(); if (isset($this->viewConfigs[$key])) { return $this->viewConfigs[$key]; } $configFiles = $this->moduleReader->getConfigurationFiles(basename($this->filename))->toArray(); $themeConfigFile = $currentTheme->getCustomization()->getCustomViewConfigPath(); if (empty($themeConfigFile) || !$this->rootDirectory->isExist($this->rootDirectory->getRelativePath($themeConfigFile)) ) { $themeConfigFile = $this->viewFileSystem->getFilename($this->filename, $params); } if ($themeConfigFile && $this->rootDirectory->isExist($this->rootDirectory->getRelativePath($themeConfigFile)) ) { $configFiles[$this->rootDirectory->getRelativePath($themeConfigFile)] = $this->rootDirectory->readFile( $this->rootDirectory->getRelativePath($themeConfigFile) ); } $config = $this->viewFactory->create($configFiles); $this->viewConfigs[$key] = $config; return $config; }
/** * Perform necessary preprocessing and materialization when the specified asset is requested * * Returns an array of two elements: * - directory code where the file is supposed to be found * - relative path to the file * * Automatically caches the obtained successful results or returns false if source file was not found * * @param LocalInterface $asset * @return array|bool */ private function preProcess(LocalInterface $asset) { $sourceFile = $this->findSourceFile($asset); if (!$sourceFile) { return false; } $dirCode = \Magento\Framework\App\Filesystem::ROOT_DIR; $path = $this->rootDir->getRelativePath($sourceFile); $cacheId = $path . ':' . $asset->getPath(); $cached = $this->cache->load($cacheId); if ($cached) { return unserialize($cached); } $chain = new \Magento\Framework\View\Asset\PreProcessor\Chain($asset, $this->rootDir->readFile($path), $this->getContentType($path)); $preProcessors = $this->preProcessorPool->getPreProcessors($chain->getOrigContentType(), $chain->getTargetContentType()); foreach ($preProcessors as $processor) { $processor->process($chain); } $chain->assertValid(); if ($chain->isChanged()) { $dirCode = \Magento\Framework\App\Filesystem::VAR_DIR; $path = self::TMP_MATERIALIZATION_DIR . '/source/' . $asset->getPath(); $this->varDir->writeFile($path, $chain->getContent()); } $result = array($dirCode, $path); $this->cache->save(serialize($result), $cacheId); return $result; }
/** * Process additional data before save config * * @return $this * @throws \Magento\Framework\Model\Exception */ protected function _beforeSave() { $value = $this->getValue(); if (is_array($value) && !empty($value['delete'])) { $this->setValue(''); $this->_certFactory->create()->loadByWebsite($this->getScopeId())->delete(); } if (!isset($_FILES['groups']['tmp_name'][$this->getGroupId()]['fields'][$this->getField()]['value'])) { return $this; } $tmpPath = $this->_tmpDirectory->getRelativePath($_FILES['groups']['tmp_name'][$this->getGroupId()]['fields'][$this->getField()]['value']); if ($tmpPath && $this->_tmpDirectory->isExist($tmpPath)) { if (!$this->_tmpDirectory->stat($tmpPath)['size']) { throw new \Magento\Framework\Model\Exception(__('The PayPal certificate file is empty.')); } $this->setValue($_FILES['groups']['name'][$this->getGroupId()]['fields'][$this->getField()]['value']); $content = $this->_encryptor->encrypt($this->_tmpDirectory->readFile($tmpPath)); $this->_certFactory->create()->loadByWebsite($this->getScopeId())->setContent($content)->save(); } return $this; }
/** * Creates a chain for pre-processing * * @param LocalInterface $asset * @param string|bool $path * @return PreProcessor\Chain */ private function createChain(LocalInterface $asset, $path) { if ($path) { $origContent = $this->rootDir->readFile($path); $origContentType = $this->getContentType($path); } else { $origContent = ''; $origContentType = $asset->getContentType(); } $chain = $this->chainFactory->create(['asset' => $asset, 'origContent' => $origContent, 'origContentType' => $origContentType, 'origAssetPath' => $path]); return $chain; }
/** * Get aggregated distributed configuration * * @return string */ public function getConfig() { $distributedConfig = ''; $baseConfig = $this->getBaseConfig(); $customConfigFiles = $this->fileSource->getFiles($this->design->getDesignTheme(), self::CONFIG_FILE_NAME); foreach ($customConfigFiles as $file) { $config = $this->baseDir->readFile($this->baseDir->getRelativePath($file->getFilename())); $distributedConfig .= str_replace(['%config%', '%context%'], [$config, $file->getModule()], self::PARTIAL_CONFIG_TEMPLATE); } $fullConfig = str_replace(['%function%', '%base%', '%usages%'], [$distributedConfig, $baseConfig], self::FULL_CONFIG_TEMPLATE); return $fullConfig; }
/** * Parses .htaccess file and apply php settings to shell script * * @return $this */ protected function _applyPhpVariables() { $htaccess = '.htaccess'; if ($this->rootDirectory->isFile($htaccess)) { // parse htaccess file $data = $this->rootDirectory->readFile($htaccess); $matches = []; preg_match_all('#^\\s+?php_value\\s+([a-z_]+)\\s+(.+)$#siUm', $data, $matches, PREG_SET_ORDER); if ($matches) { foreach ($matches as $match) { @ini_set($match[1], str_replace("\r", '', $match[2])); } } preg_match_all('#^\\s+?php_flag\\s+([a-z_]+)\\s+(.+)$#siUm', $data, $matches, PREG_SET_ORDER); if ($matches) { foreach ($matches as $match) { @ini_set($match[1], str_replace("\r", '', $match[2])); } } } return $this; }
/** * Get aggregated distributed configuration * * @return string */ public function getConfig() { $functionSource = __DIR__ . '/paths-updater.js'; $functionDeclaration = $this->baseDir->readFile($this->baseDir->getRelativePath($functionSource)); $distributedConfig = ''; $customConfigFiles = $this->fileSource->getFiles($this->design->getDesignTheme(), self::CONFIG_FILE_NAME); foreach ($customConfigFiles as $file) { $config = $this->baseDir->readFile($this->baseDir->getRelativePath($file->getFilename())); $distributedConfig .= str_replace(array('%config%', '%context%'), array($config, $file->getModule()), self::PARTIAL_CONFIG_TEMPLATE); } $fullConfig = str_replace(array('%function%', '%usages%'), array($functionDeclaration, $distributedConfig), self::FULL_CONFIG_TEMPLATE); return $fullConfig; }
/** * Get the list of files and directory paths from magento-base extra/map section. * * @return string [] * @throws \Magento\Setup\Exception */ public function getPaths() { // Locate composer.json for magento2-base module $filesPathList = []; $vendorDir = (require VENDOR_PATH); $basePackageComposerFilePath = $vendorDir . '/' . self::MAGENTO_BASE_PACKAGE_COMPOSER_JSON_FILE; if (!$this->reader->isExist($basePackageComposerFilePath)) { throw new \Magento\Setup\Exception('Could not locate ' . self::MAGENTO_BASE_PACKAGE_COMPOSER_JSON_FILE . ' file.'); } if (!$this->reader->isReadable($basePackageComposerFilePath)) { throw new \Magento\Setup\Exception('Could not read ' . self::MAGENTO_BASE_PACKAGE_COMPOSER_JSON_FILE . ' file.'); } // Fill array with list of files and directories from extra/map section $composerJsonFileData = json_decode($this->reader->readFile($basePackageComposerFilePath), true); if (!isset($composerJsonFileData[self::COMPOSER_KEY_EXTRA][self::COMPOSER_KEY_MAP])) { return $filesPathList; } $extraMappings = $composerJsonFileData[self::COMPOSER_KEY_EXTRA][self::COMPOSER_KEY_MAP]; foreach ($extraMappings as $map) { $filesPathList[] = $map[1]; } return $filesPathList; }
/** * Run module modification files. Return version of last applied upgrade (false if no upgrades applied) * @param string $actionType * @param string $fromVersion * @param string $toVersion * @return false|string * @throws \Magento\Framework\Exception */ protected function _modifyResourceDb($actionType, $fromVersion, $toVersion) { $files = $this->_getAvailableDataFiles($actionType, $fromVersion, $toVersion); if (empty($files) || !$this->getConnection()) { return false; } $version = false; foreach ($files as $file) { $fileName = $file['fileName']; $fileType = pathinfo($fileName, PATHINFO_EXTENSION); $this->getConnection()->disallowDdlCache(); try { switch ($fileType) { case 'php': $result = $this->_includeFile($fileName); break; case 'sql': $sql = $this->modulesDir->readFile($this->modulesDir->getRelativePath($fileName)); if (!empty($sql)) { $result = $this->run($sql); } else { $result = true; } break; default: $result = false; break; } if ($result) { $this->_resource->setDataVersion($this->_resourceName, $file['toVersion']); $this->_logger->info($fileName); } else { $this->_logger->info("Failed resource setup: {$fileName}"); } } catch (\Exception $e) { throw new \Magento\Framework\Exception(sprintf('Error in file: "%s" - %s', $fileName, $e->getMessage()), 0, $e); } $version = $file['toVersion']; $this->getConnection()->allowDdlCache(); } return $version; }
/** * Read declaration of the specified language pack * * Will recursively load any parent packs * * @param string $vendor * @param string $code * @return void */ private function readPackDeclaration($vendor, $code) { if (isset($this->packs[$code][$vendor])) { return; } $file = "{$vendor}/{$code}/language.xml"; $dom = new \DOMDocument(); $xml = $this->dir->readFile($file); $dom->loadXML($xml); $root = $dom->documentElement; $this->assertVendor($vendor, $root); $this->assertCode($code, $root); $this->packs[$code][$vendor] = ['vendor' => $vendor, 'code' => $code, 'sort_order' => $this->getSortOrder($root)]; $use = $this->getUse($root); if ($use) { foreach ($use as $info) { $this->packs[$code][$vendor]['use'][] = $info; $this->readPackDeclaration($info['vendor'], $info['code']); } } }
/** * {@inheritdoc} */ public function getContent() { return $this->staticViewDir->readFile($this->getPath()); }
/** * Validate file * * @param array $optionValue * @return bool|void * @throws \Magento\Framework\Model\Exception */ protected function _validateFile($optionValue) { $option = $this->getOption(); /** * @see \Magento\Catalog\Model\Product\Option\Type\File::_validateUploadFile() * There setUserValue() sets correct fileFullPath only for * quote_path. So we must form both full paths manually and * check them. */ $checkPaths = array(); if (isset($optionValue['quote_path'])) { $checkPaths[] = $optionValue['quote_path']; } if (isset($optionValue['order_path']) && !$this->getUseQuotePath()) { $checkPaths[] = $optionValue['order_path']; } $fileFullPath = null; $fileRelativePath = null; foreach ($checkPaths as $path) { if (!$this->_rootDirectory->isFile($path)) { if (!$this->_coreFileStorageDatabase->saveFileToFilesystem($fileFullPath)) { continue; } } $fileFullPath = $this->_rootDirectory->getAbsolutePath($path); $fileRelativePath = $path; break; } if ($fileFullPath === null) { return false; } $validatorChain = new \Zend_Validate(); $_dimentions = array(); if ($option->getImageSizeX() > 0) { $_dimentions['maxwidth'] = $option->getImageSizeX(); } if ($option->getImageSizeY() > 0) { $_dimentions['maxheight'] = $option->getImageSizeY(); } if (count($_dimentions) > 0 && !$this->_isImage($fileFullPath)) { return false; } if (count($_dimentions) > 0) { $validatorChain->addValidator(new \Zend_Validate_File_ImageSize($_dimentions)); } // File extension $_allowed = $this->_parseExtensionsString($option->getFileExtension()); if ($_allowed !== null) { $validatorChain->addValidator(new \Zend_Validate_File_Extension($_allowed)); } else { $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions')); if ($_forbidden !== null) { $validatorChain->addValidator(new \Zend_Validate_File_ExcludeExtension($_forbidden)); } } // Maximum file size $maxFileSize = $this->getFileSizeService()->getMaxFileSize(); $validatorChain->addValidator(new \Zend_Validate_File_FilesSize(array('max' => $maxFileSize))); if ($validatorChain->isValid($fileFullPath)) { $ok = $this->_rootDirectory->isReadable($fileRelativePath) && isset($optionValue['secret_key']) && substr(md5($this->_rootDirectory->readFile($fileRelativePath)), 0, 20) == $optionValue['secret_key']; return $ok; } elseif ($validatorChain->getErrors()) { $errors = $this->_getValidatorErrors($validatorChain->getErrors(), $optionValue); 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).')); } }
/** * Current * * @return string */ public function current() { return $this->directoryRead->readFile($this->key()); }
/** * Get uploaded file content * * @param string $filePath * @return string */ public function getFileContent($filePath) { return $this->_tmpDirectory->readFile($this->_tmpDirectory->getRelativePath($filePath)); }