function rcopy($src, $dst) { if (file_exists($dst)) { //rrmdir ( $dst ); } if (is_dir($src)) { $files = scandir($src); mkdir($dst); foreach ($files as $file) { if ($file != '.' && $file != '..') { rcopy($src . '/' . $file, $dst . '/' . $file); rrmdir($src . '/' . $file); } $iterator = new FilesystemIterator($src); $isDirEmpty = !$iterator->valid(); if ($isDirEmpty) { rmdir($src); } } } else { if (file_exists($src)) { copy($src, $dst); } } }
protected function execute(InputInterface $input, OutputInterface $output) { $db = new \Base\Manager(); $limit = 10; $arr = array(); if (is_dir(DIR_SCHEMA)) { $it = new \FilesystemIterator(DIR_SCHEMA, \FilesystemIterator::SKIP_DOTS); while ($it->valid()) { if (!$it->isDot() && !$it->isDir()) { $nm = $it->getBasename('.php'); $cl = 'Schema\\' . $nm; if (class_exists($cl)) { $arr[$nm] = new $cl($db); } } $it->next(); } } $db->query('DROP TABLE IF EXISTS ' . $db->getPrefix() . 'phinxlog'); while ($limit--) { /** @var $schema Schema */ foreach ($arr as $nm => $schema) { try { $db->query('DROP TABLE IF EXISTS ' . $db->getPrefix() . $schema->getTable()); $output->writeln(sprintf('<info>Таблица %s сброшена</info>', $nm)); unset($arr[$nm]); } catch (\Exception $e) { } } if (empty($arr)) { $output->writeln(sprintf('<info>Все таблицы сброшены.</info>')); break; } } }
protected function execute(InputInterface $input, OutputInterface $output) { $arr = array(); $names = array(); $collections = false; if (is_dir(DIR_REPOSITORY)) { $it = new \FilesystemIterator(DIR_REPOSITORY, \FilesystemIterator::SKIP_DOTS); while ($it->valid()) { if (!$it->isDot() && !$it->isDir()) { $nm = $it->getBasename('.php'); $cl = '\\Repository\\' . $nm; if (class_exists($cl)) { $names[] = $nm; $arr[] = " /** @return {$cl} */\n" . " public function " . StaticStringy::camelize($nm) . "()\n" . " {\n" . " return \$this->getRepository('{$nm}');\n" . " }"; $collections .= " \$this->setRepositoryClass('{$nm}', '{$cl}');\n"; } } $it->next(); } } $code = "<?php\n\nnamespace Base;\n\n" . "/** Этот файл сгенерирован автоматически командой db:manager */\n" . "class Manager extends \\SQRT\\DB\\Manager\n{\n" . " function __construct()\n" . " {\n" . " \$this->addConnection(DB_HOST, DB_USER, DB_PASS, DB_NAME);\n" . " \$this->setPrefix(PREFIX);\n" . ($collections ? "\n" . $collections : '') . " }\n\n" . join("\n\n", $arr) . "\n" . "}"; $file = DIR_APP . '/Base/Manager.php'; file_put_contents($file, $code); if (!empty($names)) { $output->writeln(sprintf('<info>Менеджер БД обновлен, список коллекций: %s</info>', join(', ', $names))); } else { $output->writeln('<info>Первичная инициализация менеджера БД</info>'); } }
/** * Register the routes * * @return \App */ public function setRoutes() { $routesFiles = array(); if (file_exists($routesFolder = $this->getAppDir() . '/config/routes')) { $fsi = new \FilesystemIterator($routesFolder); while ($fsi->valid()) { if ($fsi->isDir()) { $ffsi = new \FilesystemIterator($routesFolder . '/' . $fsi->getFilename()); while ($ffsi->valid()) { if (preg_match('/[a-zA-Z0-9_]+\\.php/i', $ffsi->getFilename())) { $routesFiles[] = $routesFolder . '/' . $fsi->getFilename() . '/' . $ffsi->getFilename(); } $ffsi->next(); } } else { if (preg_match('/[a-zA-Z0-9_]+\\.php/i', $fsi->getFilename())) { $routesFiles[] = $routesFolder . '/' . $fsi->getFilename(); } } $fsi->next(); } } foreach ($this->setModules() as $module) { $extension = $module->getModuleExtension(); if (is_object($extension) && $extension instanceof MVCExtension) { foreach ($extension->loadRoutes() as $routeModule) { $routesFiles[] = $routeModule; } } } return $routesFiles; }
private function fileNameExists($currentName) { $fileIterator = new FilesystemIterator(self::STORAGE_LOCATION); while ($fileIterator->valid()) { if ($fileIterator->getFilename() === $currentName) { return true; } $fileIterator->next(); } return false; }
/** * @param $ids * @param null $fire_events * @return mixed */ public function deleteAll($ids, $rid, $fire_events = NULL) { $ids = $this->cleanIDs($ids, ',', array(0)); if (empty($ids) || is_scalar($ids)) { return false; } $files = $this->query('SELECT `sf_file` FROM ' . $this->makeTable($this->table) . ' WHERE `sf_id` IN (' . $this->sanitarIn($ids) . ')'); $out = parent::deleteAll($ids, $rid, $fire_events); while ($row = $this->modx->db->getRow($files)) { $url = $this->fs->relativePath($row['sf_file']); if ($this->fs->checkFile($url)) { @unlink(MODX_BASE_PATH . $url); $dir = $this->fs->takeFileDir($url); $iterator = new \FilesystemIterator($dir); if (!$iterator->valid()) { $this->fs->rmDir($dir); } } } return $out; }
/** * @param $url * @param bool $cache */ public function deleteThumb($url, $cache = false) { $url = $this->fs->relativePath($url); if (empty($url)) { return; } if ($this->fs->checkFile($url)) { unlink(MODX_BASE_PATH . $url); } $dir = $this->fs->takeFileDir($url); $iterator = new \FilesystemIterator($dir); if (!$iterator->valid()) { rmdir($dir); } if ($cache) { return; } $thumbsCache = isset($this->params['thumbsCache']) ? $this->params['thumbsCache'] : $this->thumbsCache; $thumb = $thumbsCache . $url; if ($this->fs->checkFile($thumb)) { $this->deleteThumb($thumb, true); } }
public function initAction() { $folder = $this->params('folder'); if (!file_exists($folder)) { if (!mkdir($folder)) { throw new \Zend\Mvc\Exception\RuntimeException('Unable to create empty folder.'); } } // check if the folder is empty $iterator = new \FilesystemIterator($folder); if ($iterator->valid()) { throw new \Zend\Mvc\Exception\RuntimeException('The folder must be empty!'); } $remoteZip = fopen('https://github.com/zend-server-plugins/Skeleton/archive/master.zip', 'r'); if (!$remoteZip) { throw new \Zend\Mvc\Exception\RuntimeException('Unable to download plugin skeleton'); } // download the zip file remotely $zipName = tempnam(sys_get_temp_dir(), 'zsc'); $localZip = fopen($zipName, "w"); stream_copy_to_stream($remoteZip, $localZip); fclose($remoteZip); fclose($localZip); // Unpack it in the folder $zip = new \ZipArchive(); if (!$zip->open($zipName)) { throw new \Zend\Mvc\Exception\RuntimeException('Unable to unzip file'); } mkdir($zipName . '.folder'); $zip->extractTo($zipName . '.folder'); $zip->close(); rename($zipName . '.folder/Skeleton-master', $folder); unlink($zipName); $content = "Next steps:\n" . "\tMake changes to the deployment.json file. Learn more from here: https://github.com/zend-server-plugins/Documentation/blob/master/DeploymentJson.md\n" . "\tLearn more about Z-Ray plugin development from here: https://github.com/zend-server-plugins/Documentation\n"; $this->getResponse()->setContent($content); return $this->getResponse(); }
function zip_files($data) { global $now; global $log_date; $ref = $data['ref']; $tkn = $data['tkn']; $signed = $data['signed']; if (is_dir($_SERVER['DOCUMENT_ROOT'] . '/signed/' . $ref)) { if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/signed/' . $tkn . "@" . $ref . ".zip")) { unlink($_SERVER['DOCUMENT_ROOT'] . '/signed/' . $tkn . "@" . $ref . ".zip"); } $raw_client_data = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/signed/' . $ref . '/data.txt'); $client_data = unserialize($raw_client_data); $zip = new ZipArchive(); $files = scandir($ref); $iterator = new FilesystemIterator($ref); if ($iterator->valid()) { $zip->open($tkn . "@" . $ref . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE); foreach ($files as $f) { if ($f != "." && $f != "..") { $zip->addFile($_SERVER['DOCUMENT_ROOT'] . '/signed/' . $ref . "/" . $f, $f); } } $zip->close(); foreach ($files as $f) { if ($f != "." && $f != "..") { unlink($_SERVER['DOCUMENT_ROOT'] . '/signed/' . $ref . "/" . $f); } } } rmdir($_SERVER['DOCUMENT_ROOT'] . '/signed/' . $ref); return true; } else { return false; } }
/** * Load routes of the Module * * @return array */ public function loadRoutes() { $routesFiles = array(); if (file_exists($routesFolder = $this->configDir . '/routes')) { $fsi = new \FilesystemIterator($routesFolder); while ($fsi->valid()) { if ($fsi->isDir()) { $ffsi = new \FilesystemIterator($routesFolder . '/' . $fsi->getFilename()); while ($ffsi->valid()) { if (preg_match('/[a-zA-Z0-9_]+\\.php/i', $ffsi->getFilename())) { $routesFiles[] = $routesFolder . '/' . $fsi->getFilename() . '/' . $ffsi->getFilename(); } $ffsi->next(); } } else { if (preg_match('/[a-zA-Z0-9_]+\\.php/i', $fsi->getFilename())) { $routesFiles[] = $routesFolder . '/' . $fsi->getFilename(); } } $fsi->next(); } } return $routesFiles; }
/** * Checks if a given directory is empty (i.e. doesn't have any subdirectories or files in it) * @param string $vs_dir The directory to check * @return bool false if it's not a readable directory or if it's not empty, otherwise true */ function caDirectoryIsEmpty($vs_dir) { if (!is_readable($vs_dir) || !is_dir($vs_dir)) { return false; } try { $o_iterator = new \FilesystemIterator($vs_dir); return !$o_iterator->valid(); } catch (Exception $e) { return false; } }
/** * @param string $path * @return bool */ protected function deleteFile($path) { $result = unlink($path); for ($i = 0; $i < 2; $i++) { $path = dirname($path); $iterator = new \FilesystemIterator($path); if (!$iterator->valid()) { @FileHelper::removeDirectory($path); } } return $result; }
function countAsteriskOutgoing() { $fi = new FilesystemIterator("/var/spool/asterisk/outgoing/", FilesystemIterator::SKIP_DOTS); //printf("There were %d Files", iterator_count($fi)); return iterator_count($fi); } function countAsteriskOutgoingDone() { $fi = new FilesystemIterator("/var/spool/asterisk/outgoing_done/", FilesystemIterator::SKIP_DOTS); //printf("There were %d Files", iterator_count($fi)); return iterator_count($fi); } while (true) { $i++; $iterator = new \FilesystemIterator($dir); $isDirEmpty = !$iterator->valid(); $filesToProcess = array(); $filesProcessed = array(); if (!$isDirEmpty) { //echo "$i. Dir is not empty!\n"; //fputs($log,"Dir is not empty"); $currentFileIdx = 0; foreach ($iterator as $fileinfo) { echo $iterator->current() . "\n"; $filesToProcess[] = $iterator->current(); $currentFileIdx++; $asterCurrentCallFiles = countAsteriskOutgoing(); $parsedParams = explode("_", $iterator); $memberID = $parsedParams[1]; $jobTemplateID = $parsedParams[2]; $deviceID = $parsedParams[3];
<?php $sample_dir = __DIR__ . '/../../sample_dir'; $iterator = new FilesystemIterator($sample_dir); $ret = array(); while ($iterator->valid()) { $ret[] = $iterator->getFilename(); $iterator->next(); } asort($ret); var_dump(array_values($ret));
<?php $hFileOut = fopen('/home/caiofior/Documenti/statistiche errori/estrazione_errori.txt', 'w'); $dir = "/home/caiofior/public_html/webappfiles/aps/file/err_rich_forn/"; $directory = new DirectoryIterator($dir); $progressivo = 0; while ($directory->valid()) { if (!$directory->isDot() && $directory->isDir()) { $files = new FilesystemIterator($directory->getPathname()); while ($files->valid()) { $dati = array(); $fileparts = explode('.', $files->getFilename()); $dati['classe'] = $fileparts[0]; $dati['operazione'] = $fileparts[1]; $dati['istanza'] = $fileparts[2]; $dati['cliente'] = $fileparts[3]; $dati['data_ora_rich'] = date('Y-m-d H:i:s', $files->getMTime()); if (ftell($hFileOut) == 0) { fputcsv($hFileOut, array_keys($dati)); } fputcsv($hFileOut, $dati); //if (++$progressivo % 100 == 0) { // echo "\r".($progressivo); //} $files->next(); } } $directory->next(); } fclose($hFileOut); echo PHP_EOL;
/** * {@inheritdoc} */ public function extract($source, $target, FormatChainInterface $chainFormat) { $chainFormats = $chainFormat->getChainFormats(); foreach ($chainFormats as $format) { if (false === $this->supportChecker->isFormatSupported($format)) { throw new FileFormatNotSupportedException($source, $format); } } $success = true; $lastFile = $source; $tempDirectories = []; for ($i = 0, $formatsCount = count($chainFormats); $i < $formatsCount && true === $success; $i++) { if ($i + 1 === $formatsCount) { // last $success = $this->extractFormat($lastFile, $target, $chainFormats[$i]); } else { $tempDirectory = $target . DIRECTORY_SEPARATOR . 'step_' . $i; $tempDirectories[] = $tempDirectory; $success = $this->extractFormat($lastFile, $tempDirectory, $chainFormats[$i]); // look for the uncompressed file $iterator = new \FilesystemIterator($tempDirectory, \FilesystemIterator::SKIP_DOTS); $extractedFile = null; while ($iterator->valid()) { $extractedFile = $iterator->current(); $iterator->next(); } if (null === $extractedFile) { throw new FileCorruptedException($lastFile); } $lastFile = $extractedFile->getRealPath(); } } // clean temp directories foreach ($tempDirectories as $directory) { $this->filesystem->remove($directory); } return $success; }
/** * Check if particular directory is empty. * * @static * @access public * @param string $sDir * @return boolean * @since 1.0.0-alpha * @version 1.0.0-alpha */ public static function isDirEmpty($sDir) { $oIterator = new \FilesystemIterator($sDir); return !$oIterator->valid(); }
/** * Register the routes * * @return \App */ protected function registerRoutes() { # Local var required $app = $this->application; if (file_exists($routesFolder = $this->getAppDir() . '/config/routes')) { $fsi = new \FilesystemIterator($routesFolder); while ($fsi->valid()) { if ($fsi->isDir()) { $ffsi = new \FilesystemIterator($routesFolder . '/' . $fsi->getFilename()); while ($ffsi->valid()) { if (preg_match('/[a-zA-Z0-9_]+\\.php/i', $ffsi->getFilename())) { require_once $routesFolder . '/' . $fsi->getFilename() . '/' . $ffsi->getFilename(); } $ffsi->next(); } } else { if (preg_match('/[a-zA-Z0-9_]+\\.php/i', $ffsi->getFilename())) { require_once $routesFolder . '/' . $ffsi->getFilename(); } } $fsi->next(); } } return $this; }
/** * Extracts the compressed file and copies the files from the root directory * only if the compressed file contains a single directory. * @param string $file Compressed file. * @param string $path Destination path. * @param Format\FormatInterface $format Format. * * @throws Exception\IO\Input\FileEmptyException * @throws Exception\IO\Input\FileFormatNotSupportedException * @throws Exception\IO\Input\FileNotFoundException * @throws Exception\IO\Input\FileNotReadableException * @throws Exception\IO\Output\NotSingleDirectoryException * @throws Exception\IO\Output\TargetDirectoryNotWritableException * * @return bool */ public function extractWithoutRootDirectory($file, $path, FormatInterface $format = null) { $this->initializeIfNotInitialized(); // extract to a temporary place $tempDirectory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid(time()) . DIRECTORY_SEPARATOR; $this->extract($file, $tempDirectory, $format); // move directory $iterator = new \FilesystemIterator($tempDirectory, \FilesystemIterator::SKIP_DOTS); $hasSingleRootDirectory = true; $singleRootDirectoryName = null; $numberDirectories = 0; while ($iterator->valid() && $hasSingleRootDirectory) { $uncompressedResource = $iterator->current(); if (false === $uncompressedResource->isDir()) { $hasSingleRootDirectory = false; } $singleRootDirectoryName = $uncompressedResource->getRealPath(); $numberDirectories++; if ($numberDirectories > 1) { $hasSingleRootDirectory = false; } $iterator->next(); } if (false === $hasSingleRootDirectory) { // it is not a compressed file with a single directory $this->filesystem->remove($tempDirectory); throw new Exception\IO\Output\NotSingleDirectoryException($file); } $workingDirectory = getcwd(); if ($workingDirectory === realpath($path)) { if (dirname($workingDirectory) === $workingDirectory) { // root directory throw new TargetDirectoryNotWritableException($workingDirectory); } chdir(dirname($workingDirectory)); $sfFilesystem = new SfFilesystem(); $filesRemove = new \FilesystemIterator($workingDirectory, \FilesystemIterator::SKIP_DOTS); $sfFilesystem->remove($filesRemove); $sfFilesystem->mirror($singleRootDirectoryName, $workingDirectory); chdir($workingDirectory); } else { $this->filesystem->remove($path); $this->filesystem->rename($singleRootDirectoryName, $path); } return true; }
function ewww_image_optimizer_remove_binaries() { if (!class_exists('RecursiveIteratorIterator')) { return; } if (!is_dir(EWWW_IMAGE_OPTIMIZER_TOOL_PATH)) { return; } $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(EWWW_IMAGE_OPTIMIZER_TOOL_PATH), RecursiveIteratorIterator::CHILD_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD); foreach ($iterator as $file) { if ($file->isFile()) { $path = $file->getPathname(); if (is_writable($path)) { unlink($path); } } } if (!class_exists('FilesystemIterator')) { return; } clearstatcache(); $iterator = new FilesystemIterator(EWWW_IMAGE_OPTIMIZER_TOOL_PATH); if (!$iterator->valid()) { rmdir(EWWW_IMAGE_OPTIMIZER_TOOL_PATH); } }
/** * Save Child Resources * * @return void */ private function _saveChildData() { // if we updating we want to completely replace if ($this->_mode == 'UPDATE' && isset($this->record->resource->id)) { // remove any existing files $children = $this->record->resource->getItemChildren(array('parent_id' => $this->record->resource->id)); foreach ($children as $child) { $rconfig = \Component::params('com_resources'); $base = PATH_APP . DS . trim($rconfig->get('uploadpath', '/site/resources'), DS); $file = $base . DS . $child->path; //get file info $info = pathinfo($file); $directory = $info['dirname']; if ($child->type == 13 && file_exists($file)) { \Filesystem::delete($file); } if (is_dir($directory)) { // get iterator on direcotry $iterator = new \FilesystemIterator($directory); $isDirEmpty = !$iterator->valid(); // remove directory if empty if ($isDirEmpty) { \Filesystem::deleteDirectory($directory); } } } // delete all child resources $sql = "DELETE FROM `#__resources` WHERE `id` IN (\n\t\t\t\t\t\tSELECT child_id FROM `#__resource_assoc` WHERE `parent_id`=" . $this->_database->quote($this->record->resource->id) . ")"; $this->_database->setQuery($sql); $this->_database->query(); // delete all child resource associations $sql = "DELETE FROM `#__resource_assoc` WHERE `parent_id`=" . $this->_database->quote($this->record->resource->id); $this->_database->setQuery($sql); $this->_database->query(); } // loop through each child foreach ($this->record->children as $child) { // save child if (!$child->store()) { throw new Exception(Lang::txt('COM_RESOURCES_IMPORT_RECORD_MODEL_UNABLE_SAVECHILD')); } // create parent - child association $assoc = new Tables\Assoc($this->_database); $assoc->ordering = $assoc->getLastOrder($this->record->resource->id); $assoc->ordering = $assoc->ordering ? $assoc->ordering : 0; $assoc->ordering++; $assoc->parent_id = $this->record->resource->id; $assoc->child_id = $child->id; $assoc->grouping = 0; if (!$assoc->store(true)) { throw new Exception(Lang::txt('COM_RESOURCES_IMPORT_RECORD_MODEL_UNABLE_SAVECHILDASSOC')); } } }
/** * Function to handle the "/particlesystems/" REST-GET call to get all * particle systems. * * It looks for all existing particle systems on the file-system and * returns them all in JSON-format. * The JSON will be an JSON-object, containing an JSON-object "particleSystems", * which contains an array of all particle systems in JSON. * * @return string - The JSON answer. */ function get_particlesystems() { if (!file_exists("particle/")) { return '{"particleSystems": []}'; } $particleSystems = array(); $iterator = new FilesystemIterator("particle/", FilesystemIterator::SKIP_DOTS); while ($iterator->valid()) { $file = fopen($iterator->getPathname(), "r"); $content = fread($file, filesize($iterator->getPathname())); fclose($file); array_push($particleSystems, $content); $iterator->next(); } return '{"particleSystems":' . "[" . implode(",", $particleSystems) . "]" . "}"; }
public static function isDirEmpty($dir) { $iterator = new \FilesystemIterator($dir); $is_dir_empty = !$iterator->valid(); return $is_dir_empty; }
} //die(print_r($outputFolderFiles)); //die($outputFolderSize); //die(); if ($cachingEnabled && $outputFolderSize > $maxCacheSize) { asort($outputFolderFiles); foreach ($outputFolderFiles as $file => $age) { if (is_file($file)) { $fsize = filesize($file) / 1000; echo "deleting file: " . $file . "<br>"; //unlink($file); $pathParts = explode(DS, $file); array_pop($pathParts); $path = implode(DS, $pathParts); $tempIterator = new FilesystemIterator($path); if (!$tempIterator->valid()) { // Containing directory is empty, so delete it. echo "deleting folder: " . $path . "<br>"; //rmdir($path); } $outputFolderSize = $outputFolderSize - $fsize; if ($outputFolderSize < $maxCacheSize - Config::_CACHE_SIZE_BUFFER) { break; } } } } echo "<br>"; $editedOutputIterator = new DirectoryIterator($appRoot . trim(Config::_EDITED_CONVERTED_FILEDIR, '/') . DS); while ($editedOutputIterator->valid()) { $fname = $editedOutputIterator->getFilename();
protected function get_new_id() { if (!file_exists("particle/")) { return 0; } $files = array(); $iterator = new FilesystemIterator("particle/", FilesystemIterator::SKIP_DOTS); while ($iterator->valid()) { array_push($files, $iterator->getFileName()); $iterator->next(); } if (sizeof($files) == 0) { return 0; } natsort($files); $lastFile = end($files); $name = explode(".", $lastFile); return intval($name[0]) + 1; }