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);
        }
    }
}
Example #2
0
 /**
  * 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;
 }
 protected function getSubDirectoriesInfos($rootDir, $infoFilename)
 {
     if ($rootDir[0] == '~') {
         if (DIRECTORY_SEPARATOR == '\\') {
             $rootDir = $_SERVER['USERPROFILE'] . substr($rootDir, 1);
         } else {
             $rootDir = $_SERVER['HOME'] . substr($rootDir, 1);
         }
     }
     $infos = array();
     $it = new \FilesystemIterator($rootDir);
     foreach ($it as $subDir) {
         if ($it->isDot() || !$it->isDir()) {
             continue;
         }
         $defaultInfo = array('name' => $subDir->getFilename(), 'description' => '', 'dir' => $subDir->getPathname(), 'source' => $subDir->getPathname());
         $infoPath = $subDir->getPathname() . DIRECTORY_SEPARATOR . $infoFilename;
         if (is_file($infoPath)) {
             $infos[] = array_merge($defaultInfo, Yaml::parse($infoPath));
         } else {
             $infos[] = $defaultInfo;
         }
     }
     return $infos;
 }
Example #4
0
 /**
  *
  */
 public function prepare()
 {
     $this->fetched = $this->fetch();
     $this->fetched->rewind();
     $this->filtered = $this->filter($this->fetched);
     $this->filtered->rewind();
     $this->sorted = $this->sort($this->filtered);
     $this->sorted->rewind();
 }
 private function fileNameExists($currentName)
 {
     $fileIterator = new FilesystemIterator(self::STORAGE_LOCATION);
     while ($fileIterator->valid()) {
         if ($fileIterator->getFilename() === $currentName) {
             return true;
         }
         $fileIterator->next();
     }
     return false;
 }
Example #6
0
    /**
     * Returns the best fit, depending on name, chronology and size, for a new
     * TV episode.
     *
     * @param string $episodeName The full episode name: ShowName - SSEXX - Title
     * @param string $freeSpaceTreshold minimal available space for a disk  to be available
     *
     * @todo Make the treshold depend on the episode Index, maybe even based on previous seasons and episode size
     *
     * @return array string a disk name (HDEXT-1, ARTHAS...)
     **/
    public static function BestTVEpisodeFit( $episodeName, $targetFilesize )
    {
        $return = array();
        $basePath = '/media/aggregateshares/TV Shows';

        $targetEpisodeInfo = self::parseEpisode( $episodeName );
        $showAggregatePath = "{$basePath}/{$targetEpisodeInfo['show']}";

        if ( !file_exists( $showAggregatePath ) )
        {
            $return['bestfit'] = 'none';
        }
        else
        {
            $iterator = new FilesystemIterator( $showAggregatePath );
            $iterator->setFlags( FilesystemIterator::KEY_AS_FILENAME | FilesystemIterator::CURRENT_AS_PATHNAME );
            $maxEpisodeNumber = 0;
            foreach( $iterator as $file => $path )
            {
                $episodeInfo = self::parseEpisode( $file );
                if ( $episodeInfo === false )
                    continue;

                $path = realpath( $path );

                // broken link => ignore
                if ( $path == false )
                    continue;

                // 100 episodes per season really should do it, right ?
                $absoluteEpisodeNumber = ( $episodeInfo['season'] * 100 ) + $episodeInfo['episode'];
                if ( $absoluteEpisodeNumber > $maxEpisodeNumber )
                {
                    $maxEpisodeNumber = $absoluteEpisodeNumber;
                    $latestEpisodePath = $path;
                }
            }
            if ( !isset( $latestEpisodePath ) )
            {
                $return['bestfit'] = 'none';
            }
            else
            {
                $return['LatestEpisode'] = $latestEpisodePath;
                list( , , , $return['RecommendedDisk'] ) = explode( '/', $latestEpisodePath );
                $lastEpisodeDiskFreespace = diskfreespace( $latestEpisodePath );

                $return['RecommendedDiskHasFreeSpace'] = ( $targetFilesize  > $lastEpisodeDiskFreespace ) ? 'false' : 'true';
            }
        }

        return $return;
    }
 /**
  * @param string $dir
  */
 public static function addResourceDir($dir)
 {
     if (in_array($dir, static::$dirs)) {
         return;
     }
     $iterator = new \FilesystemIterator($dir, \FilesystemIterator::SKIP_DOTS);
     foreach ($iterator as $value) {
         if (!$iterator->isFile()) {
             continue;
         }
         list($domain, $locale, $format) = explode('.', $iterator->getBasename(), 3);
         static::$translator->addResource($format, $iterator->getRealPath(), $locale, $domain);
     }
     static::$dirs[] = $dir;
 }
 /**
  * ( excerpt from
  * http://docs.hhvm.com/manual/en/recursivedirectoryiterator.construct.php )
  *
  * Constructs a RecursiveDirectoryIterator() for the provided path.
  *
  * @path       mixed   The path of the directory to be iterated over.
  * @flags      mixed   Flags may be provided which will affect the behavior
  *                     of some methods. A list of the flags can found under
  *                     FilesystemIterator predefined constants. They can
  *                     also be set later with
  *                     FilesystemIterator::setFlags().
  *
  * @return     mixed   Returns the newly created
  *                     RecursiveDirectoryIterator.
  */
 public function __construct($path, $flags = null)
 {
     if ($flags === null) {
         $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO;
     }
     parent::__construct($path, $flags);
 }
 /**
  * Explorer files and folders
  * 
  * @param string $path  Dir path of folder
  * @param int $flags FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS
  */
 public function __construct($path, $flags = null)
 {
     if (!is_null($flags)) {
         parent::__construct($path, $flags);
     } else {
         parent::__construct($path);
     }
 }
Example #10
0
 /**
  * Current.
  * Please, see \FileSystemIterator::current() method.
  *
  * @return  mixed
  */
 public function current()
 {
     $out = parent::current();
     if (null !== $this->_splFileInfoClass && $out instanceof \SplFileInfo) {
         $out->setInfoClass($this->_splFileInfoClass);
         $out = $out->getFileInfo();
     }
     return $out;
 }
 /**
  * Get pathname and create a DataFile object
  *
  * @return \CastlePointAnime\Brancher\Twig\DataFile
  */
 public function current()
 {
     $pathname = parent::current();
     $relPathname = rtrim($this->filesystem->makePathRelative($pathname, $this->root), '/');
     if (is_dir($pathname)) {
         return new self($this->filesystem, $this->parser, $this->root, "{$relPathname}/");
     } else {
         return new DataFile($this->parser, $pathname, $relPathname);
     }
 }
Example #12
0
 /**
  * @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;
 }
Example #13
0
 /**
  * Get list of files/directories from supplied directory.
  *
  * @param array $options
  *        'dir'		=> boolean, include directory paths
  *        'ext'		=> file suffix, no full stop (period) separator should be used.
  *        'path'	=> The path to list from. If left empty it will use whatever the current working directory is.
  *        'regex'	=> Regular expressions that the full path must match to be included,
  *
  * @return array	Always returns array of path-names in unix format (even on Windows).
  */
 public static function getDirFiles(array $options = null)
 {
     $defaults = array('dir' => false, 'ext' => '', 'path' => '', 'regex' => '');
     $options += $defaults;
     $files = array();
     $iterator = new \FilesystemIterator($options['path'], \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS);
     foreach ($iterator as $fileinfo) {
         $file = $iterator->key();
         switch (true) {
             case !$options['dir'] && $fileinfo->isDir():
                 break;
             case !empty($options['ext']) && $fileinfo->getExtension() != $options['ext']:
                 break;
             case empty($options['regex']) || !preg_match($options['regex'], $file):
                 break;
             default:
                 $files[] = $file;
         }
     }
     return $files;
 }
Example #14
0
 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>');
     }
 }
Example #15
0
 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;
         }
     }
 }
Example #16
0
 /**
  * @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();
 }
Example #18
0
 public function scanControllers(\FilesystemIterator $iterator)
 {
     $iterator->rewind();
     foreach ($iterator as $resource) {
         $matches = array();
         if ($resource->isFile()) {
             preg_match('/((\\/?[A-z]*)+(([A-Z]{1})+[a-z])*Controller\\.php)/', $resource->getRealPath(), $matches);
             if (isset($matches[0]) && !is_null($matches[0])) {
                 // To improve later
                 $class = array_filter(preg_split('/\\b[a-z]+\\b/', $resource->getRealPath()));
                 $class = $class[count($class) - 1];
                 $class = $class[0] == '/' ? substr($class, 1, strlen($class)) : $class;
                 $class = str_replace(array('.', '.php'), '', $class);
                 $class = str_replace('/', '\\', $class);
                 $controller = new $class();
                 if ($controller instanceof AbstractController) {
                     $this->controllerStack->attach(new $class($this->application));
                 } else {
                     unset($controller);
                 }
             }
         }
     }
 }
 /**
  * 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;
 }
Example #20
0
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;
    }
}
Example #21
0
    echo 'Caught exception (' . $e->getCode() . ') on line ' . $e->getLine() . ': "' . $e->getMessage() . '"<br>';
}
//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()) {
Example #22
0
 /**
  * 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'));
         }
     }
 }
Example #23
0
 /**
  * Overwrites \FilesystemIterator::current() to return an instance of 
  * \Phig\MigrationStep
  * @return \Phig\MigrationStep
  */
 public function current()
 {
     return new MigrationStep(parent::current()->getPathname());
 }
Example #24
0
 /**
  * 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();
 }
Example #25
0
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);
    }
}
Example #26
0
/**
 * 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;
    }
}
 /**
  * Overwriting the default `next()` method to skip files beginning with a dot if so
  *
  * If the flag `SKIP_DOTTED` is active, this will skip files beginning with a dot.
  *
  * @return void
  */
 public function next()
 {
     parent::next();
     if ($this->valid() && $this->getFlags() & WebFilesystemIterator::SKIP_DOTTED) {
         $this->_skipDottedIfSo();
     }
 }
Example #28
0
 /**
  * @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;
 }
Example #29
0
<?php

$sample_dir = __DIR__ . '/../../sample_dir';
$iterator = new FilesystemIterator($sample_dir, FilesystemIterator::KEY_AS_PATHNAME);
echo "Key as Pathname:\n";
$ret = array();
foreach ($iterator as $key => $fileinfo) {
    $ret[] = $key;
}
asort($ret);
var_dump(array_values($ret));
$iterator->setFlags(FilesystemIterator::KEY_AS_FILENAME);
echo "\nKey as Filename:\n";
$ret = array();
foreach ($iterator as $key => $fileinfo) {
    $ret[] = $key;
}
asort($ret);
var_dump(array_values($ret));
Example #30
0
$chanLimit = 1;
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];