/** * {@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; }
/** * 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)); }
/** * 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; }
/** * 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; }
/** * Load widget XML config and merge with theme widget config * * @return array|null * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function getWidgetConfigAsArray() { if ($this->_widgetConfigXml === null) { $this->_widgetConfigXml = $this->_widgetModel->getWidgetByClassType($this->getType()); if ($this->_widgetConfigXml) { $configFile = $this->_viewFileSystem->getFilename('widget.xml', ['area' => $this->getArea(), 'theme' => $this->getThemeId(), 'module' => $this->_namespaceResolver->determineOmittedNamespace(preg_replace('/^(.+?)\\/.+$/', '\\1', $this->getType()), true)]); $isReadable = $configFile && $this->_directory->isReadable($this->_directory->getRelativePath($configFile)); if ($isReadable) { $config = $this->_reader->readFile($configFile); $widgetName = isset($this->_widgetConfigXml['name']) ? $this->_widgetConfigXml['name'] : null; $themeWidgetConfig = null; if ($widgetName !== null) { foreach ($config as $widget) { if (isset($widget['name']) && $widgetName === $widget['name']) { $themeWidgetConfig = $widget; break; } } } if ($themeWidgetConfig) { $this->_widgetConfigXml = array_replace_recursive($this->_widgetConfigXml, $themeWidgetConfig); } } } } return $this->_widgetConfigXml; }
/** * 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; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function get($filename, $scope) { $moduleDir = $this->modulesDirectory->getAbsolutePath(); $configDir = $this->configDirectory->getAbsolutePath(); $mageScopePath = $moduleDir . '/Magento'; $output = array('base' => array(), 'mage' => array(), 'custom' => array()); $files = glob($moduleDir . '*/*/etc/module.xml'); foreach ($files as $file) { $scope = strpos($file, $mageScopePath) === 0 ? 'mage' : 'custom'; $output[$scope][] = $this->rootDirectory->getRelativePath($file); } $files = glob($configDir . '*/module.xml'); foreach ($files as $file) { $output['base'][] = $this->rootDirectory->getRelativePath($file); } return $this->iteratorFactory->create($this->rootDirectory, array_merge($output['mage'], $output['custom'], $output['base'])); }
/** * @param \Magento\Framework\View\Asset\LocalInterface $asset * * @return bool|string * @deprecated If custom vendor directory is outside Magento root, then this method will return unexpected result */ public function findRelativeSourceFilePath(LocalInterface $asset) { $sourceFile = $this->findSourceFile($asset); if (!$sourceFile) { return false; } return $this->rootDir->getRelativePath($sourceFile); }
/** * Get path of file after using fallback rules * * @param RuleInterface $fallbackRule * @param string $file * @param array $params * @return string|bool */ protected function resolveFile(RuleInterface $fallbackRule, $file, array $params = []) { foreach ($fallbackRule->getPatternDirs($params) as $dir) { $path = "{$dir}/{$file}"; if ($this->rootDirectory->isExist($this->rootDirectory->getRelativePath($path))) { return $path; } } return false; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * Simple check if file is image * * @param array|string $fileInfo - either file data from \Zend_File_Transfer or file path * @return boolean * @see \Magento\Catalog\Model\Product\Option\Type\File::_isImage */ protected function isImage($fileInfo) { // Maybe array with file info came in if (is_array($fileInfo)) { return strstr($fileInfo['type'], 'image/'); } // File path came in - check the physical file if (!$this->rootDirectory->isReadable($this->rootDirectory->getRelativePath($fileInfo))) { return false; } $imageInfo = getimagesize($fileInfo); if (!$imageInfo) { return false; } return true; }
/** * Perform actual minification * * @return void */ protected function minify() { $isExists = $this->staticViewDir->isExist($this->path); if (!$isExists) { $shouldMinify = true; } elseif ($this->strategy == self::FILE_EXISTS) { $shouldMinify = false; } else { $origlFile = $this->rootDir->getRelativePath($this->originalAsset->getSourceFile()); $origMtime = $this->rootDir->stat($origlFile)['mtime']; $minMtime = $this->staticViewDir->stat($this->path)['mtime']; $shouldMinify = $origMtime != $minMtime; } if ($shouldMinify) { $content = $this->adapter->minify($this->originalAsset->getContent()); $this->staticViewDir->writeFile($this->path, $content); } }
/** * 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; }
/** * Get uploaded file content * * @param string $filePath * @return string */ public function getFileContent($filePath) { return $this->_tmpDirectory->readFile($this->_tmpDirectory->getRelativePath($filePath)); }
/** * Temporary directory path to store images * * @return string */ public function getTemporaryDirectory() { return $this->mediaDirectory->getRelativePath('/theme/origin'); }