Example #1
0
 /**
  * Parse a tarball of .gcov files.
  **/
 public function Parse($handle)
 {
     global $CDASH_BACKUP_DIRECTORY;
     // This function receives an open file handle, but we really just need
     // the path to this file so that we can extract it.
     $meta_data = stream_get_meta_data($handle);
     $filename = $meta_data["uri"];
     fclose($handle);
     // Create a new directory where we can extract our tarball.
     $pathParts = pathinfo($filename);
     $dirName = $CDASH_BACKUP_DIRECTORY . "/" . $pathParts['filename'];
     mkdir($dirName);
     // Extract the tarball.
     $phar = new PharData($filename);
     $phar->extractTo($dirName);
     // Find the data.json file and extract the source directory from it.
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirName), RecursiveIteratorIterator::CHILD_FIRST);
     foreach ($iterator as $fileinfo) {
         if ($fileinfo->getFilename() == "data.json") {
             $jsonContents = file_get_contents($fileinfo->getRealPath());
             $jsonDecoded = json_decode($jsonContents, true);
             if (is_null($jsonDecoded) || !array_key_exists("Source", $jsonDecoded) || !array_key_exists("Binary", $jsonDecoded)) {
                 $this->DeleteDirectory($dirName);
                 return false;
             }
             $this->SourceDirectory = $jsonDecoded['Source'];
             $this->BinaryDirectory = $jsonDecoded['Binary'];
             break;
         }
     }
     if (empty($this->SourceDirectory) || empty($this->BinaryDirectory)) {
         $this->DeleteDirectory($dirName);
         return false;
     }
     // Check if any Labels.json files were included
     $iterator->rewind();
     foreach ($iterator as $fileinfo) {
         if ($fileinfo->getFilename() == "Labels.json") {
             $this->ParseLabelsFile($fileinfo);
         }
     }
     // Recursively search for .gcov files and parse them.
     $iterator->rewind();
     foreach ($iterator as $fileinfo) {
         if (pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION) == "gcov") {
             $this->ParseGcovFile($fileinfo);
         }
     }
     // Insert coverage summary (removing any old results first)
     //$this->CoverageSummary->RemoveAll();
     $this->CoverageSummary->Insert();
     $this->CoverageSummary->ComputeDifference();
     // Delete the directory when we're done.
     $this->DeleteDirectory($dirName);
     return true;
 }
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $CFG;
     $tmpdir = $CFG->tempdir;
     // Default to last weeks time.
     $time = time() - $CFG->tempdatafoldercleanup * 3600;
     $dir = new \RecursiveDirectoryIterator($tmpdir);
     // Show all child nodes prior to their parent.
     $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);
     // An array of the full path (key) and date last modified.
     $modifieddateobject = array();
     // Get the time modified for each directory node. Nodes will be updated
     // once a file is deleted, so we need a list of the original values.
     for ($iter->rewind(); $iter->valid(); $iter->next()) {
         $node = $iter->getRealPath();
         if (!is_readable($node)) {
             continue;
         }
         $modifieddateobject[$node] = $iter->getMTime();
     }
     // Now loop through again and remove old files and directories.
     for ($iter->rewind(); $iter->valid(); $iter->next()) {
         $node = $iter->getRealPath();
         if (!is_readable($node)) {
             continue;
         }
         // Check if file or directory is older than the given time.
         if ($modifieddateobject[$node] < $time) {
             if ($iter->isDir() && !$iter->isDot()) {
                 // Don't attempt to delete the directory if it isn't empty.
                 if (!glob($node . DIRECTORY_SEPARATOR . '*')) {
                     if (@rmdir($node) === false) {
                         mtrace("Failed removing directory '{$node}'.");
                     }
                 }
             }
             if ($iter->isFile()) {
                 if (@unlink($node) === false) {
                     mtrace("Failed removing file '{$node}'.");
                 }
             }
         } else {
             // Return the time modified to the original date only for real files.
             if ($iter->isDir() && !$iter->isDot()) {
                 touch($node, $modifieddateobject[$node]);
             }
         }
     }
 }
function array_flatten(array $array, $key_separator = '/')
{
    $result = array();
    // a stack of strings
    $keys = array();
    $prev_depth = -1;
    $iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
    // rewind() is necessary
    for ($iter->rewind(); $iter->valid(); $iter->next()) {
        $curr_depth = $iter->getDepth();
        $diff_depth = $prev_depth - $curr_depth + 1;
        //##### TODO: It would be nice to do this with a single function.
        while ($diff_depth > 0) {
            array_pop($keys);
            --$diff_depth;
        }
        /*
        Note:
        http://bugs.php.net/bug.php?id=52425
        array_shift/array_pop: add parameter that tells how many to elements to pop
        */
        array_push($keys, $iter->key());
        if (is_scalar($iter->current())) {
            $result[implode($key_separator, $keys)] = $iter->current();
        }
        $prev_depth = $curr_depth;
    }
    return $result;
}
Example #4
0
 private static function is_extension_changed($name)
 {
     $name = strtolower($name);
     $extension_build_dir = ROOT_PATH . DS . 'build' . DS . $name;
     $extension_path = ROOT_PATH . DS . 'extensions' . DS . $name . '.tar.gz';
     if (file_exists($extension_build_dir) && file_exists($extension_path)) {
         $dir_iterator = new \RecursiveDirectoryIterator($extension_build_dir);
         /**
          * @var $iterator \RecursiveDirectoryIterator
          */
         $iterator = new \RecursiveIteratorIterator($dir_iterator);
         $iterator->rewind();
         while ($iterator->valid()) {
             if (!$iterator->isDot()) {
                 $file = $extension_build_dir . DS . $iterator->getSubPathName();
                 $phar_file = "phar://{$extension_path}/" . $iterator->getSubPathName();
                 if (!file_exists($phar_file)) {
                     return true;
                 } else {
                     $build_file_hash = md5(file_get_contents($file));
                     $phar_file_hash = md5(file_get_contents($phar_file));
                     if ($build_file_hash != $phar_file_hash) {
                         return true;
                     }
                 }
             }
             $iterator->next();
         }
         return false;
     } else {
         return false;
     }
 }
Example #5
0
 /**
  * Executes a specific Selenium System Tests in your machine
  *
  * @param string $seleniumPath   Optional path to selenium-standalone-server-x.jar
  * @param string $pathToTestFile Optional name of the test to be run
  * @param string $suite          Optional name of the suite containing the tests, Acceptance by default.
  *
  * @return mixed
  */
 public function runTest($pathToTestFile = null, $suite = 'acceptance')
 {
     $this->runSelenium();
     // Make sure to Run the Build Command to Generate AcceptanceTester
     $this->_exec("php vendor/bin/codecept build");
     if (!$pathToTestFile) {
         $this->say('Available tests in the system:');
         $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('tests/' . $suite, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
         $tests = array();
         $iterator->rewind();
         $i = 1;
         while ($iterator->valid()) {
             if (strripos($iterator->getSubPathName(), 'cept.php') || strripos($iterator->getSubPathName(), 'cest.php')) {
                 $this->say('[' . $i . '] ' . $iterator->getSubPathName());
                 $tests[$i] = $iterator->getSubPathName();
                 $i++;
             }
             $iterator->next();
         }
         $this->say('');
         $testNumber = $this->ask('Type the number of the test  in the list that you want to run...');
         $test = $tests[$testNumber];
     }
     $pathToTestFile = 'tests/' . $suite . '/' . $test;
     $this->taskCodecept()->test($pathToTestFile)->arg('--steps')->arg('--debug')->run()->stopOnFail();
     // Kill selenium server
     // $this->_exec('curl http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer');
 }
Example #6
0
 /**
  * @return \RecursiveIteratorIterator
  */
 public function getIterator()
 {
     //$iterator = new FileSearchIterator($this->baseDir, $this->pattern, $this->buildFlag());
     if (!is_null($this->iterator)) {
         $this->iterator->rewind();
         return $this->iterator;
     }
     $iterator = new \RecursiveDirectoryIterator($this->baseDir, $this->buildFlag());
     if ($this->ignoreVcsFiles) {
         $this->ignore = array_merge($this->ignore, static::$vcsFiles);
     }
     if (!empty($this->ignore)) {
         $iterator = new DirectoryExcludeFilter($iterator, $this->ignore);
     }
     if ($this->searchFor === static::SEARCH_FILES) {
         $iterator = new FilenameRegexFilter($iterator, $this->pattern);
     } else {
         $iterator = new DirectoryRegexFilter($iterator, $this->pattern);
     }
     if (!empty($this->filters)) {
         $iterator = $this->addFilters($iterator);
     }
     $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
     return $this->iterator = $iterator;
 }
 /**
  * @param $target
  * @return array
  */
 public function locate($target)
 {
     $paths = [];
     $target = sprintf("%s/%s", self::RESOURCE_SUFFIX, $target);
     foreach ($this->locations as $location) {
         if (!is_dir($location)) {
             continue;
         }
         $location = realpath($location);
         $dir = new \RecursiveDirectoryIterator($location, \FilesystemIterator::FOLLOW_SYMLINKS);
         $filter = new \RecursiveCallbackFilterIterator($dir, function (\SplFileInfo $current) use(&$paths, $target) {
             $fileName = strtolower($current->getFilename());
             if ($this->isExcluded($fileName) || $current->isFile()) {
                 return false;
             }
             if (!is_dir($current->getPathname() . '/Resources')) {
                 return true;
             } else {
                 $file = $current->getPathname() . sprintf("/Resources/%s", $target);
                 if (is_file($file)) {
                     $paths[] = $file;
                 }
                 return false;
             }
         });
         $iterator = new \RecursiveIteratorIterator($filter);
         $iterator->rewind();
     }
     return $paths;
 }
Example #8
0
 private static function unlinkDirectory($path)
 {
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);
     $iterator->rewind();
     $files = array();
     $directories = array();
     foreach ($iterator as $path => $directory) {
         if (is_file($path)) {
             $files[] = $path;
         } elseif (is_dir($path)) {
             $directories[] = $path;
         }
     }
     // Remove the files, then the directories
     foreach ($files as $filePath) {
         self::unlinkFile($filePath);
     }
     foreach ($directories as $dirPath) {
         rmdir($dirPath);
     }
     // Finally, remove the path itself
     if (is_dir($path)) {
         rmdir($path);
     }
 }
Example #9
0
 public function testRecursiveIterator()
 {
     $document = $this->createDocument();
     $iterator = new RecursiveDomIterator($document);
     $iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
     $iterator->rewind();
     $this->assertEquals('html', $iterator->current()->tagName);
     $iterator->next();
     $this->assertEquals('head', $iterator->current()->tagName);
     $iterator->next();
     $this->assertEquals('title', $iterator->current()->tagName);
     $iterator->next();
     $this->assertEquals('Hello World', $iterator->current()->textContent);
     $iterator->next();
     $this->assertEquals('body', $iterator->current()->tagName);
     $iterator->next();
     $this->assertEquals('div', $iterator->current()->tagName);
     $iterator->next();
     $this->assertEquals('p', $iterator->current()->tagName);
     $iterator->next();
     $this->assertEquals('foo', $iterator->current()->textContent);
     $iterator->next();
     $this->assertEquals('div', $iterator->current()->tagName);
     $iterator->next();
     $this->assertEquals('p', $iterator->current()->tagName);
     $iterator->next();
     $this->assertEquals('bar', $iterator->current()->textContent);
 }
Example #10
0
	public function rmdir($path) {
		if (!$this->isDeletable($path)) {
			return false;
		}
		try {
			$it = new \RecursiveIteratorIterator(
				new \RecursiveDirectoryIterator($this->getSourcePath($path)),
				\RecursiveIteratorIterator::CHILD_FIRST
			);
			/**
			 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
			 * This bug is fixed in PHP 5.5.9 or before
			 * See #8376
			 */
			$it->rewind();
			while ($it->valid()) {
				/**
				 * @var \SplFileInfo $file
				 */
				$file = $it->current();
				if (in_array($file->getBasename(), array('.', '..'))) {
					$it->next();
					continue;
				} elseif ($file->isDir()) {
					rmdir($file->getPathname());
				} elseif ($file->isFile() || $file->isLink()) {
					unlink($file->getPathname());
				}
				$it->next();
			}
			return rmdir($this->getSourcePath($path));
		} catch (\UnexpectedValueException $e) {
			return false;
		}
	}
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $CFG;
     $tmpdir = $CFG->tempdir;
     // Default to last weeks time.
     $time = strtotime('-1 week');
     $dir = new \RecursiveDirectoryIterator($tmpdir);
     // Show all child nodes prior to their parent.
     $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);
     for ($iter->rewind(); $iter->valid(); $iter->next()) {
         $node = $iter->getRealPath();
         if (!is_readable($node)) {
             continue;
         }
         // Check if file or directory is older than the given time.
         if ($iter->getMTime() < $time) {
             if ($iter->isDir() && !$iter->isDot()) {
                 // Don't attempt to delete the directory if it isn't empty.
                 if (!glob($node . DIRECTORY_SEPARATOR . '*')) {
                     if (@rmdir($node) === false) {
                         mtrace("Failed removing directory '{$node}'.");
                     }
                 }
             }
             if ($iter->isFile()) {
                 if (@unlink($node) === false) {
                     mtrace("Failed removing file '{$node}'.");
                 }
             }
         }
     }
 }
 function endChildren()
 {
     global $count;
     echo $this->getDepth();
     if (--$count > 0) {
         // Trigger use-after-free
         parent::rewind();
     }
 }
Example #13
0
 protected function countThemePages($path)
 {
     $result = 0;
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
     $it->setMaxDepth(1);
     $it->rewind();
     while ($it->valid()) {
         if (!$it->isDot() && !$it->isDir() && $it->getExtension() == 'htm') {
             $result++;
         }
         $it->next();
     }
     return $result;
 }
 public function delete()
 {
     if (!$this->loadData()) {
         $this->dataError();
         sendBack();
     }
     $moduleobject = $this->_uses[$this->modeltype];
     $db = DB::Instance();
     $db->StartTrans();
     if ($moduleobject->isLoaded()) {
         $modulename = $moduleobject->name;
         $modulelocation = FILE_ROOT . $moduleobject->location;
         if ($moduleobject->enabled && !$moduleobject->disable()) {
             $errors[] = 'Failed to disable module';
         }
         if ($moduleobject->registered && !$moduleobject->unregister()) {
             $errors[] = 'Failed to unregister module';
         }
         if (!$moduleobject->delete()) {
             $errors[] = 'Failed to delete module';
         } else {
             $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($modulelocation), RecursiveIteratorIterator::CHILD_FIRST);
             for ($dir->rewind(); $dir->valid(); $dir->next()) {
                 if ($dir->isDir()) {
                     rmdir($dir->getPathname());
                 } else {
                     unlink($dir->getPathname());
                 }
             }
             rmdir($modulelocation);
         }
     } else {
         $errors[] = 'Cannot find module';
     }
     $flash = Flash::Instance();
     if (count($errors) > 0) {
         $db->FailTrans();
         $flash->addErrors($errors);
         if (isset($this->_data['id'])) {
             $db->CompleteTrans();
             sendTo($this->name, 'view', $this->_modules, array('id' => $this->_data['id']));
         }
     } else {
         $flash->addMessage('Module ' . $modulename . ' deleted OK');
     }
     $db->CompleteTrans();
     sendTo($this->name, 'index', $this->_modules);
 }
Example #15
0
 public static function suite()
 {
     $suite = new PHPUnit_Framework_TestSuite('Test Suite');
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname(__FILE__) . '/Test'));
     for ($it->rewind(); $it->valid(); $it->next()) {
         // Something like: Test\Application\Modules\Main\Controllers\Index.php
         $path = "Test\\" . $it->getInnerIterator()->getSubPathname();
         // Replace all of the \ with _
         $className = str_replace('\\', "_", $path);
         // Take off the extension
         $className = substr($className, 0, -4);
         require_once $path;
         $suite->addTestSuite($className);
     }
     return $suite;
 }
 /**
  * Parse a tarball of JSON files.
  **/
 public function Parse($handle)
 {
     global $CDASH_BACKUP_DIRECTORY;
     // This function receives an open file handle, but we really just need
     // the path to this file so that we can extract it.
     $meta_data = stream_get_meta_data($handle);
     $filename = $meta_data["uri"];
     fclose($handle);
     // Create a new directory where we can extract our tarball.
     $pathParts = pathinfo($filename);
     $dirName = $CDASH_BACKUP_DIRECTORY . "/" . $pathParts['filename'];
     mkdir($dirName);
     // Extract the tarball.
     $phar = new PharData($filename);
     $phar->extractTo($dirName);
     // Check if this submission included a  package_map.json file.
     // This tells us how Java packages correspond to CDash subprojects.
     $mapFound = false;
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirName), RecursiveIteratorIterator::CHILD_FIRST);
     foreach ($iterator as $fileinfo) {
         if ($fileinfo->getFilename() == "package_map.json") {
             $this->ParsePackageMap($fileinfo);
         }
     }
     // Recursively search for .java.json files and parse them.
     $iterator->rewind();
     foreach ($iterator as $fileinfo) {
         // need the longest extension, so getExtension() won't do here.
         $ext = substr(strstr($fileinfo->getFilename(), '.'), 1);
         if ($ext === "java.json") {
             $this->ParseJavaJSONFile($fileinfo);
         }
     }
     // Insert coverage summaries
     $completedSummaries = array();
     foreach ($this->CoverageSummaries as $coverageSummary) {
         if (in_array($coverageSummary->BuildId, $completedSummaries)) {
             continue;
         }
         $coverageSummary->Insert();
         $coverageSummary->ComputeDifference();
         $completedSummaries[] = $coverageSummary->BuildId;
     }
     // Delete the directory when we're done.
     $this->DeleteDirectory($dirName);
     return true;
 }
 public function search($query, $path)
 {
     $searchPath = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] . $path : $path;
     $result = "searching for " . $query . " in path " . $searchPath . "<br/>";
     if (is_dir($searchPath) && is_readable($searchPath)) {
         $dir = new \RecursiveDirectoryIterator($searchPath);
         $files = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST, \RecursiveIteratorIterator::CATCH_GET_CHILD);
         $files->rewind();
         while ($files->valid()) {
             if (self::searchByContent($files, $query)) {
                 $result .= "found in: " . $files->getSubPathName() . "<br/>";
             }
             $files->next();
         }
     }
     return $result;
 }
Example #18
0
 public function testIterate()
 {
     $sitemap = new Sitemap("h-1", "home", null);
     $n1 = $sitemap->getRoot()->addChild(new Node("h-1-1", "n1", null));
     $n2 = $n1->addChild(new Node("h-1-1-1", "n2", null));
     $n3 = $n1->addChild(new Node("h-1-1-2", "n3", null));
     $it = new \RecursiveIteratorIterator($sitemap->getIterator(), \RecursiveIteratorIterator::SELF_FIRST);
     $it->rewind();
     $this->assertEquals($sitemap->getRoot(), $it->current(), "Se esperaba que el primer elemento del iterador sea la raiz.");
     $it->next();
     $this->assertEquals($n1, $it->current(), "Se esperaba que el segundo elemento del iterador sea el primer hijo de la raiz.");
     $it->next();
     $this->assertEquals($n2, $it->current(), "Se esperaba que el tercer elemento del iterador sea el primer hijo del primer hijo de la raiz.");
     $it->next();
     $this->assertEquals($n3, $it->current(), "Se esperaba que el cuarto elemento del iterador sea el segundo hijo del primer hijo de la raiz.");
     $it->next();
     $this->assertFalse($it->valid(), "Se esperaba que el luego del cuarto elemento el iterador quede inválido.");
 }
 public function execute()
 {
     if (is_file($this->getPath())) {
         return array(basename($this->getPath()));
     }
     /** @var \RecursiveIteratorIterator $it */
     $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->getPath()));
     $result = array();
     // iterate over the directory and its subdirectories
     $it->rewind();
     while ($it->valid()) {
         if (!$it->isDot()) {
             $result[] = $it->getSubPathName();
         }
         $it->next();
     }
     return $result;
 }
Example #20
0
 private function findControllers()
 {
     $path = constant('APPLICATION_PATH') . '/modules';
     $found = [];
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
     $it->rewind();
     while ($it->valid()) {
         if (!$it->isDot()) {
             if (false !== strpos($it->getSubPathName(), 'Controller') && false == strpos($it->getSubPathName(), 'Abstract')) {
                 //echo 'SubPathName: ' . $it->getSubPathName() . "\n";
                 //echo 'SubPath:     ' . $it->getSubPath() . "\n";
                 //echo 'Key:         ' . $it->key() . "\n\n";
                 $found[] = $it->key();
             }
         }
         $it->next();
     }
     return $found;
 }
Example #21
0
 /**
  * Parse a tarball of JSON files.
  **/
 public function Parse($filename)
 {
     // Create a new directory where we can extract our tarball.
     $dirName = sys_get_temp_dir() . '/' . pathinfo($filename, PATHINFO_FILENAME);
     mkdir($dirName);
     // Extract the tarball.
     $result = extract_tar($filename, $dirName);
     if ($result === false) {
         add_log('Could not extract ' . $filename . ' into ' . $dirName, 'JavaJSONTarHandler::Parse', LOG_ERR);
         return false;
     }
     // Check if this submission included a  package_map.json file.
     // This tells us how Java packages correspond to CDash subprojects.
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirName), RecursiveIteratorIterator::CHILD_FIRST);
     foreach ($iterator as $fileinfo) {
         if ($fileinfo->getFilename() == 'package_map.json') {
             $this->ParsePackageMap($fileinfo);
         }
     }
     // Recursively search for .java.json files and parse them.
     $iterator->rewind();
     foreach ($iterator as $fileinfo) {
         // need the longest extension, so getExtension() won't do here.
         $ext = substr(strstr($fileinfo->getFilename(), '.'), 1);
         if ($ext === 'java.json') {
             $this->ParseJavaJSONFile($fileinfo);
         }
     }
     // Insert coverage summaries
     $completedSummaries = array();
     foreach ($this->CoverageSummaries as $coverageSummary) {
         if (in_array($coverageSummary->BuildId, $completedSummaries)) {
             continue;
         }
         $coverageSummary->Insert();
         $coverageSummary->ComputeDifference();
         $completedSummaries[] = $coverageSummary->BuildId;
     }
     // Delete the directory when we're done.
     DeleteDirectory($dirName);
     return true;
 }
Example #22
0
 /**
  * @param string $directoryPath
  * @param array $settings
  */
 public function setPermissions($directoryPath, array $settings)
 {
     $filePermissions = !empty($settings['file']) ? $settings['file'] : 0;
     $filePermissions = is_array($filePermissions) ? array_filter($filePermissions) : $filePermissions;
     $folderPermissions = !empty($settings['folder']) ? $settings['folder'] : 0;
     $folderPermissions = is_array($folderPermissions) ? array_filter($folderPermissions) : $folderPermissions;
     if (empty($filePermissions) && empty($folderPermissions)) {
         return;
     }
     if (!empty($folderPermissions)) {
         $this->ensureFileOrFolderPermissions($directoryPath, $folderPermissions);
     }
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directoryPath, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);
     $iterator->rewind();
     foreach ($iterator as $object) {
         if (!empty($filePermissions) && $object->isFile()) {
             $this->ensureFileOrFolderPermissions($object->getPathname(), $filePermissions);
         } elseif (!empty($folderPermissions) && $object->isDir()) {
             $this->ensureFileOrFolderPermissions($object->getPathname(), $folderPermissions);
         }
     }
 }
 public function calculate_wp_default_path()
 {
     global $phpbb_root_path;
     //find wp install
     $wp_path = $phpbb_root_path;
     $i = 0;
     $found = false;
     do {
         //http://php.net/manual/en/class.recursivedirectoryiterator.php#114504
         $directory = new \RecursiveDirectoryIterator($wp_path, \FilesystemIterator::FOLLOW_SYMLINKS);
         //OH WAIT? this PIECE OF SHI*T doesnt work for recursive directory that arent the parent. GOD. WHY.
         $filter = new \RecursiveCallbackFilterIterator($directory, function ($current, $key, $iterator) {
             //in case we take the time to exclude the self from the previous loop
             //well, it's ez, but im lazy
             return true;
         });
         $iterator = new \RecursiveIteratorIterator($filter);
         //directory dependance of the callback request us to ... redefine the whole goddam thing each loop. cmon..
         $files = array();
         $iterator->rewind();
         while ($iterator->valid() || !$found) {
             $info = $iterator->current();
             $iterator->next();
             //alasfiltering must be done here cause filter doesnt filter.meh.
             if (strpos($info->getFilename(), 'wp-config.php') === 0) {
                 $files[] = $info->getPath();
             }
             //actually, yeah, we stop once we found one.
             $found = true;
         }
         //We got up 1 lvl in hierarchy
         $wp_path = $wp_path . '../';
         $i++;
     } while ($i < 2 || !$found);
     return !empty($files) ? $files[0] : "";
 }
Example #24
0
 protected function parseContents(\SimpleXMLIterator $iterator, FileCollection $files)
 {
     // Load files
     $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
     $iterator->rewind();
     $lastDepth = -1;
     $path = array();
     while ($iterator->valid()) {
         if ($lastDepth > $iterator->getDepth()) {
             array_pop($path);
             while ($lastDepth != $iterator->getDepth()) {
                 array_pop($path);
                 $lastDepth--;
             }
         } elseif ($lastDepth === $iterator->getDepth()) {
             array_pop($path);
         }
         $elt = $iterator->current();
         if ($elt->getName() === 'file') {
             $path[] = (string) $elt['name'];
             $filePath = implode('/', $path);
             $file = new File($filePath, $filePath, $elt['role']);
             // Find file tasks
             $tasks = $elt->children('http://pear.php.net/dtd/tasks-1.0');
             foreach ($tasks as $task) {
                 $options = current((array) $task->attributes());
                 $file->addTask($task->getName(), $options);
             }
             $files[] = $file;
         } elseif ($elt->getName() === 'dir') {
             $path[] = ((string) $elt['name'] === '/' ? '' : $elt['name']) . (isset($elt['baseinstalldir']) && (string) $elt['baseinstalldir'] !== '/' ? '/' . $elt['baseinstalldir'] : '');
         }
         $lastDepth = $iterator->getDepth();
         $iterator->next();
     }
 }
Example #25
0
 /**
  * Executes the command
  * @param  InputInterface  $input  The Input Interface
  * @param  OutputInterface $output The Output Interface
  * @return void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('');
     $output->writeln('<info>---------------</info>');
     $output->writeln('ICS File Merger');
     $output->writeln('<info>---------------</info>');
     $output->writeln('');
     // --------------------------------------------------------------------------
     //  Get variables
     $srcDir = $input->getOption('src');
     $destDir = $input->getOption('dest');
     $fileName = $input->getOption('file');
     // --------------------------------------------------------------------------
     //  Test source directory
     if (!is_dir($destDir)) {
         $output->writeln('<error>Source directory does not exist</error>');
         $output->writeln($srcDir);
         $output->writeln('');
         return;
     }
     //  Test output destination
     if (!is_writable($destDir)) {
         $output->writeln('<error>Destination is not writeable</error>');
         $output->writeln($destDir);
         $output->writeln('');
         return;
     }
     // --------------------------------------------------------------------------
     //  Look for .ics files
     $output->writeln('<info>Searching for .ics in:</info> ' . $srcDir);
     $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($srcDir));
     $numFiles = 0;
     $it->rewind();
     while ($it->valid()) {
         if (!$it->isDot() && strtolower(substr($it->key(), -4)) === '.ics') {
             $numFiles++;
         }
         $it->next();
     }
     if ($numFiles === 0) {
         $output->writeln('<info>Did not find any .ics files</info>');
         $output->writeln('');
         return;
     }
     $output->writeln('<info>Found ' . $numFiles . ' .ics files</info>');
     // --------------------------------------------------------------------------
     //  Begin merging files
     $output->writeln('');
     $output->writeln('<info>Merging .ics files</info>');
     $output->writeln('');
     //  Create the merge file and write the initial lines to it
     if (!$this->makeFile($destDir, $fileName)) {
         $output->writeln('<error>Failed to create merge file</error>');
         $output->writeln('');
         return;
     }
     //  write file header
     $this->writeFileLine('BEGIN:VCALENDAR');
     $this->writeFileLine('VERSION:2.0');
     $this->writeFileLine('PRODID:XXX');
     $this->writeFileLine('CALSCALE:GREGORIAN');
     //  Set up the progress helper
     $progress = $this->getHelper('progress');
     $progress->start($output, $numFiles);
     $it->rewind();
     while ($it->valid()) {
         if (!$it->isDot() && strtolower(substr($it->key(), -4)) === '.ics') {
             //  Open the file and extract the event data
             $fileContents = file_get_contents($it->key());
             if (!empty($fileContents)) {
                 preg_match_all('/BEGIN\\:VEVENT(.*?)END\\:VEVENT/s', $fileContents, $matches);
                 if (!empty($matches[1])) {
                     foreach ($matches[1] as $event) {
                         $this->writeFileLine('BEGIN:VEVENT');
                         $lines = explode("\r\n", $event);
                         $lines = array_map('trim', $lines);
                         $lines = array_filter($lines);
                         foreach ($lines as $line) {
                             $this->writeFileLine($line);
                         }
                         $this->writeFileLine('END:VEVENT');
                     }
                 }
             }
             $progress->advance();
         }
         $it->next();
     }
     $progress->finish();
     //  Write file footer
     $this->writeFileLine('END:VCALENDAR');
     $output->writeln('');
     $output->writeln('<info>Completed merging .ics files</info>');
     $output->writeln('<info>Output available at:</info> ' . $destDir);
     $output->writeln('');
 }
Example #26
0
/**
 * Delete files and directories older than one week from directory provided by $CFG->tempdir.
 *
 * @exception Exception Failed reading/accessing file or directory
 * @return bool True on successful file and directory deletion; otherwise, false on failure
 */
function cron_delete_from_temp()
{
    global $CFG;
    $tmpdir = $CFG->tempdir;
    // Default to last weeks time.
    $time = strtotime('-1 week');
    try {
        $dir = new RecursiveDirectoryIterator($tmpdir);
        // Show all child nodes prior to their parent.
        $iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
        for ($iter->rewind(); $iter->valid(); $iter->next()) {
            $node = $iter->getRealPath();
            if (!is_readable($node)) {
                continue;
            }
            // Check if file or directory is older than the given time.
            if ($iter->getMTime() < $time) {
                if ($iter->isDir() && !$iter->isDot()) {
                    if (@rmdir($node) === false) {
                        mtrace("Failed removing directory '{$node}'.");
                    }
                }
                if ($iter->isFile()) {
                    if (@unlink($node) === false) {
                        mtrace("Failed removing file '{$node}'.");
                    }
                }
            }
        }
    } catch (Exception $e) {
        mtrace('Failed reading/accessing file or directory.');
        return false;
    }
    return true;
}
Example #27
0
 /**
  * get the size from a given root folder
  * @param \OC\Files\View $view file view on the root folder
  * @return integer size of the folder
  */
 private static function calculateSize($view)
 {
     $root = \OCP\Config::getSystemValue('datadirectory') . $view->getAbsolutePath('');
     if (!file_exists($root)) {
         return 0;
     }
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
     $size = 0;
     /**
      * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
      * This bug is fixed in PHP 5.5.9 or before
      * See #8376
      */
     $iterator->rewind();
     while ($iterator->valid()) {
         $path = $iterator->current();
         $relpath = substr($path, strlen($root) - 1);
         if (!$view->is_dir($relpath)) {
             $size += $view->filesize($relpath);
         }
         $iterator->next();
     }
     return $size;
 }
Example #28
0
     break;
 case 'download-file':
     if (Params::getParam('file') != '') {
         $tmp = explode("/", Params::getParam('file'));
         $filename = end($tmp);
         osc_downloadFile(Params::getParam('file'), $filename);
         $message = __('File downloaded correctly');
     } else {
         $message = __('Missing filename');
     }
     break;
 case 'empty-temp':
     $message = __("Removing temp-directory");
     $path = ABS_PATH . 'oc-temp';
     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
     for ($dir->rewind(); $dir->valid(); $dir->next()) {
         if ($dir->isDir()) {
             if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                 rmdir($dir->getPathname());
             }
         } else {
             unlink($dir->getPathname());
         }
     }
     rmdir($path);
     break;
 case 'db-backup':
     osc_dbdump();
     break;
 case 'zip-osclass':
     $archive_name = ABS_PATH . "OSClass_backup." . date('YmdHis') . ".zip";
Example #29
0
 /**
  * Take an array of mixed strings and arrays, assuming that they are all
  * relevant to ONE command and create a string that conforms to the Redis
  * protocol
  * @return string
  */
 protected function protocol(array $args)
 {
     $iter1 = new \RecursiveArrayIterator($args);
     $iter2 = new \RecursiveIteratorIterator($iter1);
     $cmd = "";
     $i = 0;
     for ($iter2->rewind(); $iter2->valid(); $iter2->next()) {
         if (is_null($iter2->current())) {
             continue;
         }
         ++$i;
         $cmd .= "\$" . strlen($iter2->current());
         $cmd .= $this->DELIM;
         $cmd .= $iter2->current();
         $cmd .= $this->DELIM;
     }
     $command = sprintf("*%d%s%s", $i, $this->DELIM, $cmd);
     return $command;
 }
Example #30
0
 /**
  * Finds all .../Resource/config/oro/bundles.yml in given root folders
  *
  * @param array $roots
  *
  * @return array
  */
 protected function findBundles($roots = array())
 {
     $paths = array();
     foreach ($roots as $root) {
         if (!is_dir($root)) {
             continue;
         }
         $root = realpath($root);
         $dir = new \RecursiveDirectoryIterator($root, \FilesystemIterator::FOLLOW_SYMLINKS);
         $filter = new \RecursiveCallbackFilterIterator($dir, function (\SplFileInfo $current) use(&$paths) {
             $fileName = strtolower($current->getFilename());
             if ($fileName === '.' || $fileName === '..' || $fileName === 'tests' || $current->isFile()) {
                 return false;
             }
             if (!is_dir($current->getPathname() . '/Resources')) {
                 return true;
             } else {
                 $file = $current->getPathname() . '/Resources/config/oro/bundles.yml';
                 if (is_file($file)) {
                     $paths[] = $file;
                 }
                 return false;
             }
         });
         $iterator = new \RecursiveIteratorIterator($filter);
         $iterator->rewind();
     }
     return $paths;
 }