public function copyRecursive($from, $to) { foreach ($iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($from, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item) { if ($item->isDir()) { mkdir($to . DIRECTORY_SEPARATOR . $iterator->getSubPathname()); } else { copy($item, $to . DIRECTORY_SEPARATOR . $iterator->getSubPathname()); } } }
/** * @inheritDoc */ public function getFiles($only_root = false) { $files = array(); $tgz = new \PharData($this->file, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_PATHNAME); if ($only_root) { $iterator = $tgz; } else { $iterator = new \RecursiveIteratorIterator($tgz, \RecursiveIteratorIterator::SELF_FIRST); } foreach ($iterator as $path => $file_info) { /** @var \SplFileInfo $file_info */ $files[] = $file_info->isDir() ? rtrim($iterator->getSubPathname(), '\\/') . DIRECTORY_SEPARATOR : $iterator->getSubPathname(); } $tgz = null; $iterator = null; sort($files); return $files; }
public static function enumerateRecursive($path) { $files = array(); if (!file_exists($path) || self::isEmptyDir($path)) { return $files; } $flags = FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, $flags)); foreach ($iterator as $fileInfo) { $files[$iterator->getSubPathname()] = FilesHelper::readFile($fileInfo->getPathName()); } return $files; }
/** * Looks for files in "core" code pool */ protected function _checkCoreCodePool() { $files = array(); /** @var \RecursiveDirectoryIterator $dir */ $dir = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->_extensionPath)); while ($dir->valid()) { if (!$dir->isDot() && strpos($dir->getSubPath(), 'app/code/core') !== false) { $files[] = $dir->getSubPathname(); } $dir->next(); } if (!empty($files)) { $this->_addIssue(array('type' => 'corehack', 'comment' => 'Usage of "core" code pool', 'files' => $files, 'occurrences' => count($files))); } }
/** * @inheritDoc */ public function addDir($dir) { $result = true; /** * @var \RecursiveDirectoryIterator|\RecursiveIteratorIterator|\SplFileInfo $iterator */ $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_PATHNAME), \RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $key => $item) { $path = trim($iterator->getSubPathname(), '\\/'); /** @var \SplFileInfo $item */ if ($item->isDir()) { $result = $this->zip->addEmptyDir($path); } else { $result = $this->zip->addFile($item->getPathname(), $path); } if (!$result) { break; } } return $result; }
function zip_dir($zip_dir, $zip_archive) { if (!is_dir($zip_dir)) { if (!defined('SUGAR_PHPUNIT_RUNNER')) { die("Specified directory '{$zip_dir}' for zip file '{$zip_archive}' extraction does not exist."); } return false; } $zip = new ZipArchive(); // we need this for shadow path resolution to work $zip->open(UploadFile::realpath($zip_archive), ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE); // we need realpath here for PHP streams support $path = UploadFile::realpath($zip_dir); /** @var RecursiveIteratorIterator|RecursiveDirectoryIterator $it */ $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS), RecursiveIteratorIterator::SELF_FIRST); foreach ($it as $fileinfo) { $subPathName = $it->getSubPathname(); if ($fileinfo->isDir()) { $zip->addEmptyDir($subPathName); } else { $zip->addFile($fileinfo->getPathname(), $subPathName); } } }
/** * Add theme data from an app/theme combo. * * @param string $app The application name. * @param string $theme The theme name. * @param integer $mask Mask for the app/theme combo. */ protected function _build($app, $theme, $mask) { $path = $GLOBALS['registry']->get('themesfs', $app) . '/' . $theme; try { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); } catch (UnexpectedValueException $e) { return; } foreach ($it as $val) { if (!$val->isDir()) { $sub = $it->getSubPathname(); if (isset($this->_data[$sub])) { $this->_data[$sub] |= $mask; } else { $this->_data[$sub] = $mask; } } } }
<?php // creates tracy.phar if (!class_exists('Phar') || ini_get('phar.readonly')) { echo "Enable Phar extension and set directive 'phar.readonly=off'.\n"; die(1); } @unlink('tracy.phar'); // @ - file may not exist $phar = new Phar('tracy.phar'); $phar->setStub("<?php\nrequire 'phar://' . __FILE__ . '/tracy.php';\n__HALT_COMPILER();\n"); $phar->startBuffering(); foreach ($iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/../../src', RecursiveDirectoryIterator::SKIP_DOTS)) as $file) { echo "adding: {$iterator->getSubPathname()}\n"; $s = php_strip_whitespace($file); if (in_array($file->getExtension(), array('js', 'css'))) { continue; } elseif ($file->getExtension() === 'phtml') { $s = preg_replace_callback('#<\\?php (require |readfile\\(|.*file_get_contents\\().*?(/.+\\.(js|css))\'\\)* \\?>#', function ($m) use($file) { return file_get_contents($file->getPath() . $m[2]); }, $s); $s = preg_replace_callback('#(<(script|style).*>)(.*)(</)#Uis', function ($m) { list(, $begin, $type, $s, $end) = $m; if (strpos($s, '<?php') !== FALSE) { return $m[0]; } elseif ($type === 'script' && function_exists('curl_init')) { $curl = curl_init('http://closure-compiler.appspot.com/compile'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, 'output_info=compiled_code&js_code=' . urlencode($s)); $s = curl_exec($curl);
/** * Return the MD5 hash of the folder * * @return string The MD5 has */ protected function getHash() { $arrFiles = array(); $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(TL_ROOT . '/' . $this->strFolder, \FilesystemIterator::UNIX_PATHS)); while ($it->valid()) { if ($it->isFile() && $it->getFilename() != '.DS_Store') { $arrFiles[] = $it->getSubPathname(); $arrFiles[] = md5_file($it->getPathname()); } $it->next(); } return md5(implode('-', $arrFiles)); }
/** * Return the MD5 hash of the folder * * @return string The MD5 has */ protected function getHash() { $arrFiles = array(); $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(TL_ROOT . '/' . $this->strFolder, \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST); while ($it->valid()) { if ($it->getFilename() != '.DS_Store') { $arrFiles[] = $it->getSubPathname(); } $it->next(); } return md5(implode('-', $arrFiles)); }
public static function getTreeAsFlatList($path) { if (!is_dir($path)) { return array(); } $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST); $files = array(); foreach ($iterator as $fileinfo) { $tmp = $iterator->getSubPathname(); if ($fileinfo->isFile()) { $files[] = $iterator->getSubPathname(); } } return $files; }
/** * Collect the list of the deleted files from a list of deleted files and folders. * * @param string $deleted_filename The full path to a file containing the list of deleted files and directories * @param string $package_name The name of the package * @return array */ public function collect_deleted_files($deleted_filename, $package_name) { $result = array(); $file_contents = file($deleted_filename); foreach ($file_contents as $filename) { $filename = trim($filename); if (!$filename) { continue; } $filename = str_replace('Only in ' . $package_name, '', $filename); $filename = ltrim($filename, '/'); if (substr($filename, 0, 1) == ':') { $replace = ''; } else { $replace = '/'; } $filename = str_replace(': ', $replace, $filename); if (is_dir("{$this->locations['old_versions']}{$package_name}/{$filename}")) { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator("{$this->locations['old_versions']}{$package_name}/{$filename}", \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY); foreach ($iterator as $file_info) { $result[] = "{$filename}/{$iterator->getSubPathname()}"; } } else { $result[] = $filename; } } return $result; }
$counterStart = microtime(true); require 'vendor/autoload.php'; $config = (require 'config/application.php'); // Initialize all services in the container $app = new Pimple(); $debug = $app['debug'] = isset($argv[1]) && $argv[1] === '--debug' || $config['debug']; require 'src/services.php'; // Initialize index storage $index = []; // Clear sheet cache directory $app['sheet_cache']->clear(); $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('sheets/')); $iterator->rewind(); while ($iterator->valid()) { if (!$iterator->isDot()) { $path = str_replace(['\\', '.xml'], ['/', ''], $iterator->getSubPathname()); $sheet = new SheetParser($path, $iterator->getPathname(), $config, $debug); $meta = $sheet->parseMeta(); $content = $sheet->parseContent(); $index['sheets'][$path] = ['title' => $meta->title, 'summary' => $meta->summary, 'keywords' => $meta->keywords, 'category' => $iterator->getSubPath(), 'path' => $path]; $index['categories'][] = $iterator->getSubPath(); $app['sheet_cache']->write($path, $content); unset($sheet, $path, $meta, $content); } $iterator->next(); } $index['categories'] = array_unique($index['categories']); $index['category_names'] = (require 'config/categories.php'); // Write index in JSON format if ($debug) { $jsonFlags = JSON_PRETTY_PRINT;
/** * Gets archive file tree without unpacking * * @param string $file_path Path to packed file * @param bool $only_root gets only root folders and files * @return mixed List of files in packed archive or false if archive cannot be read or archive does not support */ public static function getCompressedFilesList($file_path, $only_root = false) { $files_list = array(); $ext = fn_get_file_ext($file_path); switch ($ext) { case 'zip': $validators = new Validators(); if (!$validators->isZipArchiveAvailable()) { return $files_list; } $zip = new \ZipArchive(); if ($zip->open($file_path)) { $num_files = $zip->numFiles; $counter = 0; for ($i = 0; $i < $num_files; $i++) { $file_name = $zip->getNameIndex($i); $parent_directories = fn_get_parent_directory_stack($file_name); if ($only_root) { if (empty($parent_directories)) { $files_list[$file_name] = $counter++; } else { $files_list[end($parent_directories)] = $counter++; } } else { $files_list[$file_name] = $counter++; foreach ($parent_directories as $parent_dir_path) { $files_list[$parent_dir_path] = $counter++; } } } $files_list = array_flip($files_list); $zip->close(); } break; case 'tgz': $tgz = new \PharData($file_path, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_PATHNAME); if ($only_root) { $iterator = $tgz; } else { $iterator = new \RecursiveIteratorIterator($tgz, \RecursiveIteratorIterator::SELF_FIRST); } foreach ($iterator as $path_name => $spl_file_info) { /** @var \SplFileInfo $spl_file_info */ $files_list[] = $spl_file_info->isDir() ? rtrim($iterator->getSubPathname(), '\\/') . DIRECTORY_SEPARATOR : $iterator->getSubPathname(); } $tgz = null; $iterator = null; break; default: break; } sort($files_list); return $files_list; }
/** * @param string $root_directory_path * @param null|array $file_list * * @return array */ public static function revealFilePathsList($root_directory_path, $file_list = null) { $root_directory_path = rtrim(realpath($root_directory_path), '\\/') . DIRECTORY_SEPARATOR; if ($file_list === null) { $file_list = array('.'); } $output_structure = array(); $counter = 0; foreach ($file_list as $relative_path) { $relative_path = ltrim($relative_path, '\\/'); $absolute_path = realpath($root_directory_path . $relative_path); if (is_dir($absolute_path)) { $absolute_path = rtrim($absolute_path, '\\/') . DIRECTORY_SEPARATOR; if ($absolute_path == $root_directory_path) { $relative_path = null; } else { $relative_path = rtrim($relative_path, '\\/') . DIRECTORY_SEPARATOR; } } $parent_directory_stack = fn_get_parent_directory_stack($relative_path); foreach ($parent_directory_stack as $parent_directory_relative_path) { $output_structure[$parent_directory_relative_path] = $counter++; } if (is_file($absolute_path)) { $output_structure[$relative_path] = $counter++; } elseif (is_dir($absolute_path)) { if ($relative_path !== null) { $output_structure[$relative_path] = $counter++; } $directory_iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($absolute_path, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_PATHNAME), \RecursiveIteratorIterator::SELF_FIRST); foreach ($directory_iterator as $sub_absolute_path => $spl_file_info) { /** @var \SplFileInfo $spl_file_info */ if ($spl_file_info->isDir()) { $sub_relative_path = $relative_path . trim($directory_iterator->getSubPathname(), '\\/') . DIRECTORY_SEPARATOR; } else { $sub_relative_path = $relative_path . $directory_iterator->getSubPathname(); } $sub_relative_path = ltrim($sub_relative_path, '\\/'); $output_structure[$sub_relative_path] = $counter++; } } } $output_structure = array_flip($output_structure); sort($output_structure, SORT_STRING); return $output_structure; }
/** * Folder equivalent to copyFileWithinStorage(). * * @param string $sourceFolderIdentifier * @param string $targetFolderIdentifier * @param string $newFolderName * * @return bool * @throws Exception\FileOperationErrorException */ public function copyFolderWithinStorage($sourceFolderIdentifier, $targetFolderIdentifier, $newFolderName) { // This target folder path already includes the topmost level, i.e. the folder this method knows as $folderToCopy. // We can thus rely on this folder being present and just create the subfolder we want to copy to. $newFolderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($targetFolderIdentifier . '/' . $newFolderName); $sourceFolderPath = $this->getAbsolutePath($sourceFolderIdentifier); $targetFolderPath = $this->getAbsolutePath($newFolderIdentifier); mkdir($targetFolderPath); /** @var $iterator \RecursiveDirectoryIterator */ $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourceFolderPath), \RecursiveIteratorIterator::SELF_FIRST); // Rewind the iterator as this is important for some systems e.g. Windows $iterator->rewind(); while ($iterator->valid()) { /** @var $current \RecursiveDirectoryIterator */ $current = $iterator->current(); $fileName = $current->getFilename(); $itemSubPath = GeneralUtility::fixWindowsFilePath($iterator->getSubPathname()); if ($current->isDir() && !($fileName === '..' || $fileName === '.')) { GeneralUtility::mkdir($targetFolderPath . '/' . $itemSubPath); } elseif ($current->isFile()) { $result = copy($sourceFolderPath . '/' . $itemSubPath, $targetFolderPath . '/' . $itemSubPath); if ($result === false) { // rollback GeneralUtility::rmdir($targetFolderIdentifier, true); throw new Exception\FileOperationErrorException('Copying file "' . $sourceFolderPath . $itemSubPath . '" to "' . $targetFolderPath . $itemSubPath . '" failed.', 1330119452); } } $iterator->next(); } GeneralUtility::fixPermissions($targetFolderPath, true); return true; }
/** * Folder equivalent to copyFileWithinStorage(). * * @param \TYPO3\CMS\Core\Resource\Folder $folderToCopy * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder * @param string $newFolderName * @return boolean */ public function copyFolderWithinStorage(\TYPO3\CMS\Core\Resource\Folder $folderToCopy, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $newFolderName) { // This target folder path already includes the topmost level, i.e. the folder this method knows as $folderToCopy. // We can thus rely on this folder being present and just create the subfolder we want to copy to. $targetFolderPath = $this->getAbsolutePath($targetFolder) . $newFolderName . '/'; mkdir($targetFolderPath); $sourceFolderPath = $this->getAbsolutePath($folderToCopy); /** @var $iterator RecursiveDirectoryIterator */ $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourceFolderPath)); while ($iterator->valid()) { /** @var $current RecursiveDirectoryIterator */ $current = $iterator->current(); $itemSubPath = $iterator->getSubPathname(); if ($current->isDir() && !($itemSubPath === '..' || $itemSubPath === '.')) { mkdir($targetFolderPath . $itemSubPath); } elseif ($current->isFile()) { $result = copy($sourceFolderPath . $itemSubPath, $targetFolderPath . $itemSubPath); if ($result === FALSE) { throw new \TYPO3\CMS\Core\Resource\Exception\FileOperationErrorException('Copying file "' . $sourceFolderPath . $itemSubPath . '" to "' . $targetFolderPath . $itemSubPath . '" failed.', 1330119452); } } $iterator->next(); } return TRUE; }
$depth0 = "depth0"; $depth1 = "depth1"; $depth2 = "depth2"; $targetDir = __DIR__ . DIRECTORY_SEPARATOR . $depth0 . DIRECTORY_SEPARATOR . $depth1 . DIRECTORY_SEPARATOR . $depth2; mkdir($targetDir, 0777, true); touch($targetDir . DIRECTORY_SEPARATOR . 'getSubPathname_test_2.tmp'); touch(__DIR__ . DIRECTORY_SEPARATOR . $depth0 . DIRECTORY_SEPARATOR . $depth1 . DIRECTORY_SEPARATOR . 'getSubPathname_test_3.tmp'); touch(__DIR__ . DIRECTORY_SEPARATOR . $depth0 . DIRECTORY_SEPARATOR . 'getSubPathname_test_1.tmp'); $iterator = new RecursiveDirectoryIterator(__DIR__ . DIRECTORY_SEPARATOR . $depth0); $it = new RecursiveIteratorIterator($iterator); $list = []; $it->rewind(); //see https://bugs.php.net/bug.php?id=62914 while ($it->valid()) { $list[] = $it->getSubPathname(); $it->next(); } asort($list); foreach ($list as $item) { echo $item . "\n"; } function rrmdir($dir) { foreach (glob($dir . '/*') as $file) { if (is_dir($file)) { rrmdir($file); } else { unlink($file); } }
<?php // creates tester.phar if (!class_exists('Phar') || ini_get('phar.readonly')) { echo "Enable Phar extension and set directive 'phar.readonly=off'.\n"; die(1); } @unlink('tester.phar'); // @ - file may not exist $phar = new Phar('tester.phar'); $phar->setStub("<?php\nrequire 'phar://' . __FILE__ . '/tester.php';\n__HALT_COMPILER();\n"); $phar->startBuffering(); foreach ($iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/../../Tester', RecursiveDirectoryIterator::SKIP_DOTS)) as $file) { echo "adding: {$iterator->getSubPathname()}\n"; $phar[$iterator->getSubPathname()] = php_strip_whitespace($file); } $phar->stopBuffering(); $phar->compressFiles(Phar::GZ); echo "OK\n";
/** * run() method load specified directory * * @param array params * @return array */ public function run(array $aParams) { // test of obligatory validated path if (isset($aParams['path']) && is_dir($aParams['path']) && (isset($aParams['pattern']) || isset($aParams['extension']))) { // init object $oDirRecIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($aParams['path'])); // case of not recursive if (isset($aParams['recursive']) === false || isset($aParams['recursive']) === true && $aParams['recursive'] === false) { $oDirRecIterator->setMaxDepth(1); } // clear array $this->_aFiles = array(); // rewind $this->rewind(); $iCount = 0; // loop on object result while ($oDirRecIterator->valid()) { if ($oDirRecIterator->isDot() === false) { // get file name $sFileName = $oDirRecIterator->getFilename(); if (isset($aParams['pattern']) && preg_match($aParams['pattern'], $sFileName) || isset($aParams['extension']) && substr(strtolower($sFileName), strrpos($sFileName, '.') + 1) == $aParams['extension']) { $this->_aFiles[$iCount]['path'] = $oDirRecIterator->key(); $this->_aFiles[$iCount]['filename'] = $sFileName; // case of subpath if (isset($aParams['subpath']) && $aParams['subpath']) { $this->_aFiles[$iCount]['subpath'] = $oDirRecIterator->getSubPath(); } // case of subpathname if (isset($aParams['subpathname']) && $aParams['subpathname']) { $this->_aFiles[$iCount]['subpathname'] = $oDirRecIterator->getSubPathname(); } // case of size if (isset($aParams['size']) && $aParams['size']) { $this->_aFiles[$iCount]['size'] = $oDirRecIterator->getSize(); } // case of type if (isset($aParams['type']) && $aParams['type']) { $this->_aFiles[$iCount]['type'] = $oDirRecIterator->getType(); } // case of owner if (isset($aParams['owner']) && $aParams['owner']) { $this->_aFiles[$iCount]['owner'] = $oDirRecIterator->getOwner(); } // case of group if (isset($aParams['group']) && $aParams['group']) { $this->_aFiles[$iCount]['group'] = $oDirRecIterator->getGroup(); } // case of time if (isset($aParams['time']) && $aParams['time']) { $this->_aFiles[$iCount]['time'] = $oDirRecIterator->getCTime(); } // case of verbose if (isset($aParams['verbose']) && $aParams['verbose']) { echo '[ ', isset($aParams['service']) ? $aParams['service'] : 'FILE', ' ] ', date("d-m-Y à H:i:s"), ' => matched file : ', $sFileName, "\n"; } ++$iCount; } } $oDirRecIterator->next(); } // destruct object unset($oDirRecIterator); // return return $this->_aFiles; } else { // throw exception if specified directory is not declared throw new Exception('Specified path or extension or pattern are not declared or is not a valid path'); } }