/** * Convenience method to cleanup before and after test * * @return void * * @since 1.0 */ private function _cleanupTestFiles() { $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/patcher/lao2tzu.diff')); $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/patcher/lao')); $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/patcher/tzu')); $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/patcher')); }
/** * copy * * @param string $src * @param string $dest * @param array $replace * * @return void */ public function copy($src, $dest, $replace = array()) { $src = Path::clean($src); $dest = Path::clean($dest); $replace = $replace ?: $this->replace; if (is_file($src)) { $this->copyFile($src, $dest, $replace); } else { $this->copyDir($src, $dest, $replace); } }
/** * Constructor. * * @param \Windwalker\DI\Container $container * @param \CodeGenerator\IO\IOInterface $io * @param Registry $config */ public function __construct(Container $container, IOInterface $io, Registry $config = null) { // Get item & list name $ctrl = $config['ctrl'] ?: $io->getArgument(1); $ctrl = explode('.', $ctrl); $inflector = \JStringInflector::getInstance(); if (empty($ctrl[0])) { $ctrl[0] = 'item'; } if (empty($ctrl[1])) { $ctrl[1] = $inflector->toPlural($ctrl[0]); } list($itemName, $listName) = $ctrl; $this->replace['extension.element.lower'] = strtolower($config['element']); $this->replace['extension.element.upper'] = strtoupper($config['element']); $this->replace['extension.element.cap'] = ucfirst($config['element']); $this->replace['extension.name.lower'] = strtolower($config['name']); $this->replace['extension.name.upper'] = strtoupper($config['name']); $this->replace['extension.name.cap'] = ucfirst($config['name']); $this->replace['controller.list.name.lower'] = strtolower($listName); $this->replace['controller.list.name.upper'] = strtoupper($listName); $this->replace['controller.list.name.cap'] = ucfirst($listName); $this->replace['controller.item.name.lower'] = strtolower($itemName); $this->replace['controller.item.name.upper'] = strtoupper($itemName); $this->replace['controller.item.name.cap'] = ucfirst($itemName); // Set replace to config. foreach ($this->replace as $key => $val) { $config->set('replace.' . $key, $val); } // Set copy dir. $config->set('dir.dest', PathHelper::get(strtolower($config['element']), $config['client'])); $config->set('dir.tmpl', GENERATOR_BUNDLE_PATH . '/Template/' . $config['extension'] . '/' . $config['template']); $config->set('dir.src', $config->get('dir.tmpl') . '/' . $config['client']); // Replace DS $config['dir.dest'] = Path::clean($config['dir.dest']); $config['dir.tmpl'] = Path::clean($config['dir.tmpl']); $config['dir.src'] = Path::clean($config['dir.src']); parent::__construct($container, $io, $config); }
/** * Extract a ZIP compressed file to a given path * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive into * @param array $options Extraction options [unused] * * @return boolean True if successful * * @throws RuntimeException * @since 11.1 */ public function extract($archive, $destination, array $options = array()) { $this->_data = null; $this->_metadata = null; $this->_data = file_get_contents($archive); if (!$this->_data) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read archive'); } else { throw new RuntimeException('Unable to read archive'); } } $this->_getTarInfo($this->_data); for ($i = 0, $n = count($this->_metadata); $i < $n; $i++) { $type = strtolower($this->_metadata[$i]['type']); if ($type == 'file' || $type == 'unix file') { $buffer = $this->_metadata[$i]['data']; $path = Path::clean($destination . '/' . $this->_metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(dirname($path))) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to create destination'); } else { throw new RuntimeException('Unable to create destination'); } } if (File::write($path, $buffer) === false) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write entry'); } else { throw new RuntimeException('Unable to write entry'); } } } } return true; }
/** * Add a directory where JHtml should search for helpers. You may * either pass a string or an array of directories. * * @param string $path A path to search. * * @return array An array with directory elements * * @since 11.1 */ public static function addIncludePath($path = '') { // Force path to array settype($path, 'array'); // Loop through the path directories foreach ($path as $dir) { if (!empty($dir) && !in_array($dir, self::$includePaths)) { jimport('joomla.filesystem.path'); array_unshift(self::$includePaths, Path::clean($dir)); } } return self::$includePaths; }
/** * Reset cache position. * * @return void */ public function resetCachePosition() { if ($this->extension) { $params = ExtensionHelper::getParams($this->extension); } else { $params = new Registry(); } $this->config = new Registry(); $this->config['path.cache'] = Path::clean(JPATH_ROOT . $params->get('thumb.cache-path', '/cache/thumbs/cache')); $this->config['path.temp'] = Path::clean(JPATH_ROOT . $params->get('thumb.temp-path', '/cache/thumbs/temp')); $this->config['url.cache'] = $params->get('thumb.cache-url', '/cache/thumbs/cache'); $this->config['url.temp'] = $params->get('thumb.temp-url', '/cache/thumbs/cache'); }
/** * Load a class for one of the form's entities of a particular type. * Currently, it makes sense to use this method for the "field" and "rule" entities * (but you can support more entities in your subclass). * * @param string $entity One of the form entities (field or rule). * @param string $type Type of an entity. * * @return mixed Class name on success or false otherwise. * * @since 1.0 */ protected static function loadClass($entity, $type) { if (strpos($type, '.')) { list($prefix, $type) = explode('.', $type); } else { $prefix = 'Joomla'; } $class = ucfirst($prefix) . '\\Form\\' . ucfirst($entity); if ($entity === 'field') { $class .= '_' . ucfirst($type); } else { $class .= '\\' . ucfirst($type); } if (class_exists($class)) { return $class; } // Get the field search path array. $paths = self::addPath($entity); // If the type is complex, add the base type to the paths. if ($pos = strpos($type, '_')) { // Add the complex type prefix to the paths. for ($i = 0, $n = count($paths); $i < $n; $i++) { // Derive the new path. $path = $paths[$i] . '/' . strtolower(substr($type, 0, $pos)); // If the path does not exist, add it. if (!in_array($path, $paths)) { $paths[] = $path; } } // Break off the end of the complex type. $type = substr($type, $pos + 1); } // Try to find the class file. $type = strtolower($type) . '.php'; foreach ($paths as $path) { if ($file = Path::find($path, $type)) { require_once $file; if (class_exists($class)) { break; } } } // Check for all if the class exists. return class_exists($class) ? $class : false; }
/** * Convenience method to cleanup before and after testFiles * * @return void * * @since 1.0 */ private function _cleanupTestFiles() { $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/test/test/index.html')); $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/test/test/index.txt')); $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/test/test')); $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/test/index.html')); $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/test/index.txt')); $this->_cleanupFile(Path::clean(__DIR__ . '/tmp/test')); }
/** * Wrapper for the standard file_exists function * * @param string $file File path * * @return boolean True if path is a file * * @since 11.1 */ public static function exists($file) { return is_file(Path::clean($file)); }
/** * Extract a ZIP compressed file to a given path using a php based algorithm that only requires zlib support * * @param string $archive Path to ZIP archive to extract. * @param string $destination Path to extract archive into. * * @return mixed True if successful * * @since 11.1 * @throws RuntimeException */ protected function extractCustom($archive, $destination) { $this->_data = null; $this->_metadata = null; if (!extension_loaded('zlib')) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Zlib not supported'); } else { throw new RuntimeException('Zlib not supported'); } } $this->_data = file_get_contents($archive); if (!$this->_data) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read archive (zip)'); } else { throw new RuntimeException('Unable to read archive (zip)'); } } if (!$this->_readZipInfo($this->_data)) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Get ZIP Information failed'); } else { throw new RuntimeException('Get ZIP Information failed'); } } for ($i = 0, $n = count($this->_metadata); $i < $n; $i++) { $lastPathCharacter = substr($this->_metadata[$i]['name'], -1, 1); if ($lastPathCharacter !== '/' && $lastPathCharacter !== '\\') { $buffer = $this->_getFileData($i); $path = Path::clean($destination . '/' . $this->_metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(dirname($path))) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to create destination'); } else { throw new RuntimeException('Unable to create destination'); } } if (File::write($path, $buffer) === false) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write entry'); } else { throw new RuntimeException('Unable to write entry'); } } } } return true; }
/** * Extract a ZIP compressed file to a given path * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive into * * @return boolean True if successful * * @since 1.0 * @throws \RuntimeException */ public function extract($archive, $destination) { $this->data = null; $this->metadata = null; $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $this->getTarInfo($this->data); for ($i = 0, $n = count($this->metadata); $i < $n; $i++) { $type = strtolower($this->metadata[$i]['type']); if ($type == 'file' || $type == 'unix file') { $buffer = $this->metadata[$i]['data']; $path = Path::clean($destination . '/' . $this->metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(dirname($path))) { throw new \RuntimeException('Unable to create destination'); } if (File::write($path, $buffer) === false) { throw new \RuntimeException('Unable to write entry'); } } } return true; }
/** * Extract an archive file to a directory. * * @param string $archivename The name of the archive file * @param string $extractdir Directory to unpack into * * @return boolean True for success * * @since 11.1 * @throws InvalidArgumentException */ public static function extract($archivename, $extractdir) { $untar = false; $result = false; $ext = File::getExt(strtolower($archivename)); // Check if a tar is embedded...gzip/bzip2 can just be plain files! if (File::getExt(File::stripExt(strtolower($archivename))) == 'tar') { $untar = true; } switch ($ext) { case 'zip': $adapter = self::getAdapter('zip'); if ($adapter) { $result = $adapter->extract($archivename, $extractdir); } break; case 'tar': $adapter = self::getAdapter('tar'); if ($adapter) { $result = $adapter->extract($archivename, $extractdir); } break; case 'tgz': // This format is a tarball gzip'd $untar = true; case 'gz': case 'gzip': // This may just be an individual file (e.g. sql script) $adapter = self::getAdapter('gzip'); if ($adapter) { $config = Factory::getConfig(); $tmpfname = $config->get('tmp_path') . '/' . uniqid('gzip'); $gzresult = $adapter->extract($archivename, $tmpfname); if ($gzresult instanceof Exception) { @unlink($tmpfname); return false; } if ($untar) { // Try to untar the file $tadapter = self::getAdapter('tar'); if ($tadapter) { $result = $tadapter->extract($tmpfname, $extractdir); } } else { $path = Path::clean($extractdir); Folder::create($path); $result = File::copy($tmpfname, $path . '/' . File::stripExt(basename(strtolower($archivename))), null, 1); } @unlink($tmpfname); } break; case 'tbz2': // This format is a tarball bzip2'd $untar = true; case 'bz2': case 'bzip2': // This may just be an individual file (e.g. sql script) $adapter = self::getAdapter('bzip2'); if ($adapter) { $config = Factory::getConfig(); $tmpfname = $config->get('tmp_path') . '/' . uniqid('bzip2'); $bzresult = $adapter->extract($archivename, $tmpfname); if ($bzresult instanceof Exception) { @unlink($tmpfname); return false; } if ($untar) { // Try to untar the file $tadapter = self::getAdapter('tar'); if ($tadapter) { $result = $tadapter->extract($tmpfname, $extractdir); } } else { $path = Path::clean($extractdir); Folder::create($path); $result = File::copy($tmpfname, $path . '/' . File::stripExt(basename(strtolower($archivename))), null, 1); } @unlink($tmpfname); } break; default: throw new InvalidArgumentException('Unknown Archive Type'); } if (!$result || $result instanceof Exception) { return false; } return true; }
/** * Static method to get an instance of a JTable class if it can be found in * the table include paths. To add include paths for searching for JTable * classes @see JTable::addIncludePath(). * * @param string $type The type (name) of the JTable class to get an instance of. * @param string $prefix An optional prefix for the table class name. * @param array $config An optional array of configuration values for the JTable object. * * @return mixed A JTable object if found or boolean false if one could not be found. * * @link http://docs.joomla.org/JTable/getInstance * @since 11.1 */ public static function getInstance($type, $prefix = 'JTable', $config = array()) { // Sanitize and prepare the table class name. $type = preg_replace('/[^A-Z0-9_\\.-]/i', '', $type); $tableClass = $prefix . ucfirst($type); // Only try to load the class if it doesn't already exist. if (!class_exists($tableClass)) { // Search for the class file in the JTable include paths. $path = Path::find(self::addIncludePath(), strtolower($type) . '.php'); if ($path) { // Import the class file. include_once $path; // If we were unable to load the proper class, raise a warning and return false. if (!class_exists($tableClass)) { Log::add(Text::sprintf('JLIB_DATABASE_ERROR_CLASS_NOT_FOUND_IN_FILE', $tableClass), Log::WARNING, 'jerror'); return false; } } else { // If we were unable to find the class file in the JTable include paths, raise a warning and return false. Log::add(Text::sprintf('JLIB_DATABASE_ERROR_NOT_SUPPORTED_FILE_NOT_FOUND', $type), Log::WARNING, 'jerror'); return false; } } // If a database object was passed in the configuration array use it, otherwise get the global one from JFactory. $db = isset($config['dbo']) ? $config['dbo'] : Factory::getDbo(); // Instantiate a new table class and return it. return new $tableClass($db); }
/** * Moves an uploaded file to a destination folder * * @param string $src The name of the php (temporary) uploaded file * @param string $dest The path (including filename) to move the uploaded file to * @param boolean $use_streams True to use streams * * @return boolean True on success * * @since 1.0 * @throws FilesystemException */ public static function upload($src, $dest, $use_streams = false) { // Ensure that the path is valid and clean $dest = Path::clean($dest); // Create the destination directory if it does not exist $baseDir = dirname($dest); if (!file_exists($baseDir)) { Folder::create($baseDir); } if ($use_streams) { $stream = Stream::getStream(); if (!$stream->upload($src, $dest)) { throw new FilesystemException(__METHOD__ . ': ' . $stream->getError()); } return true; } else { if (is_writeable($baseDir) && move_uploaded_file($src, $dest)) { // Short circuit to prevent file permission errors if (Path::setPermissions($dest)) { return true; } else { throw new FilesystemException(__METHOD__ . ': Failed to change file permissions.'); } } else { throw new FilesystemException(__METHOD__ . ': Failed to move file.'); } return false; } }
/** * Tests the JPath::clean method with an array as an input. * * @return void * * @expectedException UnexpectedValueException */ public function testCleanArrayPath() { Path::clean(array('/path/to/folder')); }
/** * Method to load the form description from an XML file. * * The reset option works on a group basis. If the XML file references * groups that have already been created they will be replaced with the * fields in the new XML file unless the $reset parameter has been set * to false. * * @param string $file The filesystem path of an XML file. * @param string $reset Flag to toggle whether form fields should be replaced if a field * already exists with the same group/name. * @param string $xpath An optional xpath to search for the fields. * * @return boolean True on success, false otherwise. * * @since 11.1 */ public function loadFile($file, $reset = true, $xpath = false) { // Check to see if the path is an absolute path. if (!is_file($file)) { // Not an absolute path so let's attempt to find one using JPath. $file = Path::find(self::addFormPath(), strtolower($file) . '.xml'); // If unable to find the file return false. if (!$file) { return false; } } // Attempt to load the XML file. $xml = simplexml_load_file($file); return $this->load($xml, $reset, $xpath); }
/** * Extract a ZIP compressed file to a given path using a php based algorithm that only requires zlib support * * @param string $archive Path to ZIP archive to extract. * @param string $destination Path to extract archive into. * * @return mixed True if successful * * @since 1.0 * @throws \RuntimeException */ protected function extractCustom($archive, $destination) { $this->data = null; $this->metadata = null; $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive (zip)'); } if (!$this->readZipInfo($this->data)) { throw new \RuntimeException('Get ZIP Information failed'); } for ($i = 0, $n = count($this->metadata); $i < $n; $i++) { $lastPathCharacter = substr($this->metadata[$i]['name'], -1, 1); if ($lastPathCharacter !== '/' && $lastPathCharacter !== '\\') { $buffer = $this->getFileData($i); $path = Path::clean($destination . '/' . $this->metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(dirname($path))) { throw new \RuntimeException('Unable to create destination'); } if (File::write($path, $buffer) === false) { throw new \RuntimeException('Unable to write entry'); } } } return true; }
/** * Method to get the layout path. * * @param string $layout The base name of the layout file (excluding extension). * @param string $ext The extension of the layout file (default: "php"). * * @return mixed The layout file name if found, false otherwise. * * @since 1.0 */ public function getPath($layout, $ext = 'php') { // Get the layout file name. $file = Path::clean($layout . '.' . $ext); // Find the layout file path. $path = Path::find(clone $this->paths, $file); return $path; }
/** * @package Joomla.Platform * @subpackage FileSystem * * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Filesystem; defined('JPATH_PLATFORM') or die; use Exception; use Iterator; if (!defined('JPATH_ROOT')) { // Define a string constant for the root directory of the file system in native format define('JPATH_ROOT', Path::clean(JPATH_SITE)); } /** * A Path handling class * * @package Joomla.Platform * @subpackage FileSystem * @since 11.1 */ class Path { /** * Checks if a path's permissions can be changed. * * @param string $path Path to check. *
/** * Lists folder in format suitable for tree display. * * @param string $path The path of the folder to read. * @param string $filter A filter for folder names. * @param integer $maxLevel The maximum number of levels to recursively read, defaults to three. * @param integer $level The current level, optional. * @param integer $parent Unique identifier of the parent folder, if any. * * @return array Folders in the given folder. * * @since 1.0 */ public static function listFolderTree($path, $filter, $maxLevel = 3, $level = 0, $parent = 0) { $dirs = array(); if ($level == 0) { $GLOBALS['_JFolder_folder_tree_index'] = 0; } if ($level < $maxLevel) { $folders = self::folders($path, $filter); // First path, index foldernames foreach ($folders as $name) { $id = ++$GLOBALS['_JFolder_folder_tree_index']; $fullName = Path::clean($path . '/' . $name); $dirs[] = array('id' => $id, 'parent' => $parent, 'name' => $name, 'fullname' => $fullName, 'relname' => str_replace(JPATH_ROOT, '', $fullName)); $dirs2 = self::listFolderTree($fullName, $filter, $maxLevel, $level + 1, $id); $dirs = array_merge($dirs, $dirs2); } } return $dirs; }
/** * Add a directory where JCache should search for controllers. You may * either pass a string or an array of directories. * * @param string $path A path to search. * * @return array An array with directory elements * * @since 11.1 */ public static function addIncludePath($path = '') { static $paths; if (!isset($paths)) { $paths = array(); } if (!empty($path) && !in_array($path, $paths)) { array_unshift($paths, Path::clean($path)); } return $paths; }