/** * Delete all service folders from var directory */ public function cleanVarFolder() { foreach ($this->getVarSubFolders() as $folder) { try { $this->_filesystem->delete($folder); } catch (Magento_Filesystem_Exception $e) { } } }
/** * 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 Mage_Core_Controller_Response_Http $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->_filesystem->read($filePath); } catch (Exception $e) { return false; } return true; }
/** * Create thumbnail for image and save it to thumbnails directory * * @param string $source Image path to be resized * @param bool $keepRation Keep aspect ratio or not * @return bool|string Resized filepath or false if errors were occurred */ public function resizeFile($source, $keepRation = true) { if (!$this->_filesystem->isFile($source) || !$this->_filesystem->isReadable($source)) { return false; } $targetDir = $this->getThumbsPath($source); if (!$this->_filesystem->isWritable($targetDir)) { $this->_filesystem->createDirectory($targetDir); } if (!$this->_filesystem->isWritable($targetDir)) { return false; } $adapter = Mage::helper('Mage_Core_Helper_Data')->getImageAdapterType(); $image = Varien_Image_Adapter::factory($adapter); $image->open($source); $width = $this->getConfigData('resize_width'); $height = $this->getConfigData('resize_height'); $image->keepAspectRatio($keepRation); $image->resize($width, $height); $dest = $targetDir . DS . pathinfo($source, PATHINFO_BASENAME); $image->save($dest); if ($this->_filesystem->isFile($dest)) { return $dest; } return false; }
/** * Check and process robots file * * @return Mage_Backend_Model_Config_Backend_Admin_Robots */ protected function _afterSave() { if ($this->getValue()) { $this->_filesystem->write($this->_filePath, $this->getValue()); } return parent::_afterSave(); }
/** * Check file system full path * * @param string $fullPath * @param bool $recursive * @param bool $existence * @return bool */ protected function _checkFullPath($fullPath, $recursive, $existence) { $result = true; if ($recursive && $this->_filesystem->isDirectory($fullPath)) { $pathsToCheck = $this->_filesystem->getNestedKeys($fullPath); array_unshift($pathsToCheck, $fullPath); } else { $pathsToCheck = array($fullPath); } $skipFileNames = array('.svn', '.htaccess'); foreach ($pathsToCheck as $pathToCheck) { if (in_array(basename($pathToCheck), $skipFileNames)) { continue; } if ($existence) { $setError = !$this->_filesystem->isWritable($fullPath); } else { $setError = $this->_filesystem->has($fullPath) && !$this->_filesystem->isWritable($fullPath); } if ($setError) { $this->_getInstaller()->getDataModel()->addError(Mage::helper('Mage_Install_Helper_Data')->__('Path "%s" must be writable.', $pathToCheck)); $result = false; } } return $result; }
/** * 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->_filesystem->isFile($filename)) { return true; } else { return Mage::helper('Mage_Core_Helper_File_Storage_Database')->saveFileToFilesystem($filename); } }
/** * Get captcha image directory * * @param mixed $website * @return string */ public function getImgDir($website = null) { $mediaDir = $this->_config->getOptions()->getDir('media'); $captchaDir = Magento_Filesystem::getPathFromArray(array($mediaDir, 'captcha', $this->_app->getWebsite($website)->getCode())); $this->_filesystem->setWorkingDirectory($mediaDir); $this->_filesystem->setIsAllowCreateDirectories(true); $this->_filesystem->ensureDirectoryExists($captchaDir, 0755); return $captchaDir . Magento_Filesystem::DIRECTORY_SEPARATOR; }
public function replaceTmpEncryptKey($key = null) { if (!$key) { $key = md5(Mage::helper('Mage_Core_Helper_Data')->getRandomString(10)); } $localXml = $this->_filesystem->read($this->_localConfigFile); $localXml = str_replace(self::TMP_ENCRYPT_KEY_VALUE, $key, $localXml); $this->_filesystem->write($this->_localConfigFile, $localXml); return $this; }
/** * Get backup-specific data from model for each row * * @param string $filename * @return array */ protected function _generateRow($filename) { $row = parent::_generateRow($filename); foreach (Mage::getSingleton('Mage_Backup_Model_Backup')->load($row['basename'], $this->_baseDir)->getData() as $key => $value) { $row[$key] = $value; } $row['size'] = $this->_filesystem->getFileSize($filename); $row['id'] = $row['time'] . '_' . $row['type']; return $row; }
/** * @return int|mixed */ public function getSize() { if (!is_null($this->getData('size'))) { return $this->getData('size'); } if ($this->exists()) { $this->setData('size', $this->_filesystem->getFileSize($this->_getFilePath())); return $this->getData('size'); } return 0; }
/** * Fill collection with theme model loaded from filesystem * * @param bool $printQuery * @param bool $logQuery * @return Mage_Core_Model_Theme_Collection */ public function loadData($printQuery = false, $logQuery = false) { if ($this->isLoaded()) { return $this; } $pathsToThemeConfig = array(); foreach ($this->getTargetPatterns() as $directoryPath) { $pathsToThemeConfig = array_merge($pathsToThemeConfig, str_replace('/', DIRECTORY_SEPARATOR, $this->_filesystem->searchKeys($this->getBaseDir(), $directoryPath))); } $this->_loadFromFilesystem($pathsToThemeConfig)->clearTargetPatterns()->_updateRelations()->_renderFilters()->_clearFilters(); return $this; }
/** * Delete Expired Captcha Images * * @return Mage_Captcha_Model_Observer */ public function deleteExpiredImages() { foreach (Mage::app()->getWebsites(true) as $website) { $expire = time() - Mage::helper('Mage_Captcha_Helper_Data')->getConfigNode('timeout', $website->getDefaultStore()) * 60; $imageDirectory = Mage::helper('Mage_Captcha_Helper_Data')->getImgDir($website); foreach ($this->_filesystem->getNestedKeys($imageDirectory) as $filePath) { if ($this->_filesystem->isFile($filePath) && pathinfo($filePath, PATHINFO_EXTENSION) == 'png' && $this->_filesystem->getMTime($filePath) < $expire) { $this->_filesystem->delete($filePath); } } } return $this; }
/** * Retrieve block view from file (template) * * @param string $fileName * @return string * @throws Exception */ public function fetchView($fileName) { $viewShortPath = str_replace(Mage::getBaseDir(), '', $fileName); Magento_Profiler::start('TEMPLATE:' . $fileName, array('group' => 'TEMPLATE', 'file_name' => $viewShortPath)); // EXTR_SKIP protects from overriding // already defined variables extract($this->_viewVars, EXTR_SKIP); $do = $this->getDirectOutput(); if (!$do) { ob_start(); } if ($this->getShowTemplateHints()) { echo <<<HTML <div style="position:relative; border:1px dotted red; margin:6px 2px; padding:18px 2px 2px 2px; zoom:1;"> <div style="position:absolute; left:0; top:0; padding:2px 5px; background:red; color:white; font:normal 11px Arial; text-align:left !important; z-index:998;" onmouseover="this.style.zIndex='999'" onmouseout="this.style.zIndex='998'" title="{$fileName}">{$fileName}</div> HTML; if (self::$_showTemplateHintsBlocks) { $thisClass = get_class($this); echo <<<HTML <div style="position:absolute; right:0; top:0; padding:2px 5px; background:red; color:blue; font:normal 11px Arial; text-align:left !important; z-index:998;" onmouseover="this.style.zIndex='999'" onmouseout="this.style.zIndex='998'" title="{$thisClass}">{$thisClass}</div> HTML; } } try { if ((Magento_Filesystem::isPathInDirectory($fileName, Mage::getBaseDir('app')) || Magento_Filesystem::isPathInDirectory($fileName, $this->_viewDir) || $this->_getAllowSymlinks()) && $this->_filesystem->isFile($fileName)) { include $fileName; } else { Mage::log("Invalid template file: '{$fileName}'", Zend_Log::CRIT, null, true); } } catch (Exception $e) { if (!$do) { ob_get_clean(); } throw $e; } if ($this->getShowTemplateHints()) { echo '</div>'; } if (!$do) { $html = ob_get_clean(); } else { $html = ''; } Magento_Profiler::stop('TEMPLATE:' . $fileName); return $html; }
/** * Saves uploaded by Mage_Core_Model_File_Uploader file to DB with existence tests * * param $result should be result from Mage_Core_Model_File_Uploader::save() method * Checks in DB, whether uploaded file exists ($result['file']) * If yes, renames file on FS (!!!!!) * Saves file with unique name into DB * If passed file exists returns new name, file was renamed to (in the same context) * Otherwise returns $result['file'] * * @param array $result * @return string */ public function saveUploadedFile($result = array()) { if ($this->checkDbUsage()) { $path = rtrim(str_replace(array('\\', '/'), DS, $result['path']), DS); $file = '/' . ltrim($result['file'], '\\/'); $uniqueResultFile = $this->getUniqueFilename($path, $file); if ($uniqueResultFile !== $file) { $this->_filesystem->setWorkingDirectory($path); $this->_filesystem->rename($path . $file, $path . $uniqueResultFile); } $this->saveFile($path . $uniqueResultFile); return $uniqueResultFile; } else { return $result['file']; } }
/** * Uninstall the application * * @return bool */ public function uninstall() { if (!Mage::isInstalled()) { return false; } $this->_cleanUpDatabase(); /* Remove temporary directories */ $configOptions = Mage::app()->getConfig()->getOptions(); $dirsToRemove = array($configOptions->getCacheDir(), $configOptions->getSessionDir(), $configOptions->getExportDir(), $configOptions->getLogDir(), $configOptions->getVarDir() . '/report'); foreach ($dirsToRemove as $dir) { $this->_filesystem->delete($dir); } /* Remove local configuration */ $this->_filesystem->delete($configOptions->getEtcDir() . '/local.xml'); return true; }
/** * Simple check if file is image * * @param array|string $fileInfo - either file data from Zend_File_Transfer or file path * @return boolean */ 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->_filesystem->isReadable($fileInfo)) { return false; } $imageInfo = getimagesize($fileInfo); if (!$imageInfo) { return false; } return true; }
/** * Save file to storage * * @param string $filePath * @param string $content * @param bool $overwrite * @return bool */ public function saveFile($filePath, $content, $overwrite = false) { if (strpos($filePath, $this->getMediaBaseDirectory()) !== 0) { $filePath = $this->getMediaBaseDirectory() . DS . $filePath; } try { if (!$this->_filesystem->isFile($filePath) || $overwrite && $this->_filesystem->delete($filePath)) { $this->_filesystem->write($filePath, $content); return true; } } catch (Magento_Filesystem_Exception $e) { $this->_logger->log($e->getMessage()); Mage::throwException($this->_helper->__('Unable to save file: %s', $filePath)); } return false; }
/** * Copy image and return new filename. * * @param string $file * @return string */ protected function _copyImage($file) { try { $destinationFile = $this->_getUniqueFileName($file); if (!$this->_filesystem->isFile($this->_getConfig()->getMediaPath($file), $this->_baseMediaPath)) { throw new Exception(); } if (Mage::helper('Mage_Core_Helper_File_Storage_Database')->checkDbUsage()) { Mage::helper('Mage_Core_Helper_File_Storage_Database')->copyFile($this->_getConfig()->getMediaShortUrl($file), $this->_getConfig()->getMediaShortUrl($destinationFile)); $this->_filesystem->delete($this->_getConfig()->getMediaPath($destinationFile), $this->_baseMediaPath); } else { $this->_filesystem->copy($this->_getConfig()->getMediaPath($file), $this->_getConfig()->getMediaPath($destinationFile), $this->_baseMediaPath); } return str_replace(DS, '/', $destinationFile); } catch (Exception $e) { $file = $this->_getConfig()->getMediaPath($file); Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('Failed to copy file %s. Please, delete media with non-existing images and try again.', $file)); } }
/** * Parses .htaccess file and apply php settings to shell script * * @return Mage_Core_Model_ShellAbstract */ protected function _applyPhpVariables() { $htaccess = $this->_getRootPath() . '.htaccess'; if ($this->_filesystem->isFile($htaccess)) { // parse htaccess file $data = $this->_filesystem->read($htaccess); $matches = array(); 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; }
/** * Load local package data array * * @param string $packageName without extension * @return array|false */ public function loadLocalPackage($packageName) { //check LFI protection $this->checkLfiProtection($packageName); $path = $this->getLocalPackagesPath(); $xmlFile = $path . $packageName . '.xml'; $serFile = $path . $packageName . '.ser'; if ($this->_filesystem->isFile($xmlFile) && $this->_filesystem->isReadable($xmlFile)) { $xml = simplexml_load_string($this->_filesystem->read($xmlFile)); $data = Mage::helper('Mage_Core_Helper_Data')->xmlToAssoc($xml); if (!empty($data)) { return $data; } } if ($this->_filesystem->isFile($serFile) && $this->_filesystem->isReadable($xmlFile)) { $data = unserialize($this->_filesystem->read($serFile)); if (!empty($data)) { return $data; } } return false; }
/** * Return path of the current selected directory or root directory for startup * Try to create target directory if it doesn't exist * * @throws Mage_Core_Exception * @return string */ public function getCurrentPath() { if (!$this->_currentPath) { $currentPath = $this->getStorageRoot(); $path = $this->_getRequest()->getParam($this->getTreeNodeName()); if ($path) { $path = $this->convertIdToPath($path); if ($this->_filesystem->isDirectory($path)) { $currentPath = $path; } } try { if (!$this->_filesystem->isWritable($currentPath)) { $this->_filesystem->createDirectory($currentPath); } } catch (Magento_Filesystem_Exception $e) { $message = Mage::helper('Mage_Cms_Helper_Data')->__('The directory %s is not writable by server.', $currentPath); Mage::throwException($message); } $this->_currentPath = $currentPath; } return $this->_currentPath; }
/** * Save package file to var/connect. * * @return boolean */ public function savePackage() { if ($this->getData('file_name') != '') { $fileName = $this->getData('file_name'); $this->unsetData('file_name'); } else { $fileName = $this->getName(); } if (!preg_match('/^[a-z0-9]+[a-z0-9\\-\\_\\.]*([\\/\\\\]{1}[a-z0-9]+[a-z0-9\\-\\_\\.]*)*$/i', $fileName)) { return false; } if (!$this->getPackageXml()) { $this->generatePackageXml(); } if (!$this->getPackageXml()) { return false; } try { $path = Mage::helper('Mage_Connect_Helper_Data')->getLocalPackagesPath(); $this->_filesystem->write($path . 'package.xml', $this->getPackageXml()); $this->unsPackageXml(); $this->unsTargets(); $xml = Mage::helper('Mage_Core_Helper_Data')->assocToXml($this->getData()); $xml = new Varien_Simplexml_Element($xml->asXML()); // prepare dir to save $parts = explode(DS, $fileName); array_pop($parts); $newDir = implode(DS, $parts); if (!empty($newDir) && !$this->_filesystem->isDirectory($path . $newDir)) { $this->_filesystem->ensureDirectoryExists($path, $newDir, 0777); } $this->_filesystem->write($path . $fileName . '.xml', $xml->asNiceXml()); } catch (Magento_Filesystem_Exception $e) { return false; } return true; }
public function savePackage() { if ($this->getData('file_name') != '') { $fileName = $this->getData('file_name'); $this->unsetData('file_name'); } else { $fileName = $this->getName(); } if (!preg_match('/^[a-z0-9]+[a-z0-9\\-\\_\\.]*([\\/\\\\]{1}[a-z0-9]+[a-z0-9\\-\\_\\.]*)*$/i', $fileName)) { return false; } if (!$this->getPackageXml()) { $this->generatePackageXml(); } if (!$this->getPackageXml()) { return false; } $pear = Varien_Pear::getInstance(); $dir = Mage::getBaseDir('var') . DS . 'pear'; try { $this->_filesystem->write($dir . DS . 'package.xml', $this->getPackageXml()); } catch (Magento_Filesystem_Exception $e) { return false; } $pkgver = $this->getName() . '-' . $this->getReleaseVersion(); $this->unsPackageXml(); $this->unsRoles(); $xml = Mage::helper('Mage_Core_Helper_Data')->assocToXml($this->getData()); $xml = new Varien_Simplexml_Element($xml->asXML()); try { $this->_filesystem->write($dir . DS . $fileName . '.xml', $xml->asNiceXml()); } catch (Magento_Filesystem_Exception $e) { return false; } return true; }
/** * @covers Mage_Captcha_Model_Zend::getImgDir * @covers Mage_Captcha_Helper_Data::getImgDir */ public function testGetImgDir() { $captchaTmpDir = TESTS_TEMP_DIR . DIRECTORY_SEPARATOR . 'captcha'; $option = $this->_getOptionStub(); $option->expects($this->once())->method('getDir')->will($this->returnValue($captchaTmpDir)); $config = $this->_getConfigStub(); $config->expects($this->any())->method('getOptions')->will($this->returnValue($option)); $object = $this->_getHelper($this->_getStoreStub(), $config); $this->assertEquals($object->getImgDir(), Magento_Filesystem::getPathFromArray(array($captchaTmpDir, 'captcha', 'base')) . Magento_Filesystem::DIRECTORY_SEPARATOR); }
/** * Load aliases to classes map from file * * @param string $pathToMapFile * * @return string */ protected function _loadMap($pathToMapFile) { $pathToMapFile = $this->_baseDir . DS . $pathToMapFile; if ($this->_filesystem->isFile($pathToMapFile)) { return $this->_filesystem->read($pathToMapFile); } return ''; }
public function __destruct() { if ($this->_isMapChanged && $this->_canSaveMap) { if (!$this->_filesystem->isDirectory($this->_mapDir)) { $this->_filesystem->createDirectory($this->_mapDir, 0777); } $this->_filesystem->write($this->_mapFile, serialize($this->_map)); } }
/** * Process File Queue * @return Mage_Catalog_Model_Product_Type_Abstract */ 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 { $this->_filesystem->createDirectory($path, 0777); } catch (Magento_Filesystem_Exception $e) { Mage::throwException($this->_helper('Mage_Catalog_Helper_Data')->__("Cannot create writeable directory '%s'.", $path)); } $uploader->setDestination($path); if (empty($src) || empty($dst) || !$uploader->receive($src)) { /** * @todo: show invalid option */ if (isset($queueOptions['option'])) { $queueOptions['option']->setIsValid(false); } Mage::throwException($this->_helper('Mage_Catalog_Helper_Data')->__("File upload failed")); } $this->_helper('Mage_Core_Helper_File_Storage_Database')->saveFile($dst); break; case 'move_uploaded_file': $src = $queueOptions['src_name']; $dst = $queueOptions['dst_name']; move_uploaded_file($src, $dst); $this->_helper('Mage_Core_Helper_File_Storage_Database')->saveFile($dst); break; default: break; } } $queueOptions = null; } return $this; }
/** * Turn off store maintenance mode */ public function turnOffMaintenanceMode() { $maintenanceFlagFile = $this->getMaintenanceFlagFilePath(); $this->_filesystem->delete($maintenanceFlagFile, Mage::getBaseDir()); }
/** * @dataProvider isPathInDirectoryDataProvider * @param string $path * @param string $directory * @param boolean $expectedValue */ public function testIsPathInDirectory($path, $directory, $expectedValue) { $this->assertEquals($expectedValue, Magento_Filesystem::isPathInDirectory($path, $directory)); }
/** * Look for base template and read its contents * * @param string $module A fully qualified module name (<Namespace>_<Name>) * @param string $filename File path relative to module/view folder * @return string * @throws Exception if the requested filename is not found */ public function loadBaseContents($module, $filename) { $includeFilename = Mage::getConfig()->getModuleDir('view', $module) . DIRECTORY_SEPARATOR . $filename; $contents = $this->_filesystem->read($includeFilename); if (!$contents) { throw new Exception(sprintf('Failed to include file "%s".', $includeFilename)); } return $contents; }