public function logAction() { $pageSize = 4096; $overlapSize = 128; $dir = APPLICATION_PATH . '/../data/logs/'; $file = $this->_getParam('file', null); $this->view->page = $this->_getParam('page', 0); if ($file === null) { $file = sprintf('%s_application.log', Zend_Date::now()->toString('yyyy.MM.dd')); } $fp = fopen($dir . $file, 'r'); fseek($fp, -$pageSize * ($this->view->page + 1) + $overlapSize, SEEK_END); $this->view->errorLog = fread($fp, $pageSize + $overlapSize * 2); fclose($fp); $iterator = new DirectoryIterator($dir); while ($iterator->valid()) { if (!$iterator->isDot()) { if ($iterator->isFile()) { $files[$iterator->getFilename()] = $iterator->getPathName(); } } $iterator->next(); } $this->view->itemCountPerPage = $pageSize; $this->view->totalItemCount = filesize($dir . $file); $this->view->files = $files; }
/** * @ignore */ public static function fromFileScan($uPattern) { $tSep = quotemeta(DIRECTORY_SEPARATOR); $tPos = strrpos($uPattern, $tSep); if ($tSep !== '/' && $tPos === false) { $tSep = '/'; $tPos = strrpos($uPattern, $tSep); } if ($tPos !== false) { $tPattern = substr($uPattern, $tPos + strlen($tSep)); $tPath = substr($uPattern, 0, $tPos + strlen($tSep)); } else { $tPath = $uPattern; $tPattern = ""; } $tTemp = new static(); $tHandle = new \DirectoryIterator($tPath); $tPatExists = strlen($uPattern) > 0; for (; $tHandle->valid(); $tHandle->next()) { if (!$tHandle->isFile()) { continue; } $tFile = $tHandle->current(); if ($tPatExists && !fnmatch($tPattern, $tFile)) { continue; } $tTemp->add(simplexml_load_file($tPath . $tFile)); } return $tTemp; }
/** * * @param Criterio $filtro * @param string $order * @param integer $limitOffset * @param integer $limitCount * @param string $group * @return mixed Proyecto */ function findBy($filtro = null, $order = null, $limitOffset = null, $limitCount = null, $group = null) { $dir = new DirectoryIterator(DIR_PROYECTOS); while ($dir->valid()) { if ($dir->isFile() && stripos($dir->getFilename(), '.json')) { $proyFilename = DIR_PROYECTOS . $dir->getFilename(); $p = new Proyecto(); $fp = fopen($proyFilename, 'r'); $strJsonProy = fread($fp, filesize($proyFilename)); fclose($fp); $jsonProy = json_decode($strJsonProy); $p->setNombre($jsonProy->nombre); $p->setRuta($jsonProy->ruta); $p->setTieneProyectoEcplipse(file_exists("{$jsonProy->ruta}/.project")); if ($p->getTieneProyectoEclipse()) { $eclipseProy = simplexml_load_file("{$jsonProy->ruta}/.project"); $p->setNombre((string) $eclipseProy->name); } $p->setId($jsonProy->id); $p->setDbConfig($jsonProy->dbConfig); $lista[] = $p; } $dir->next(); } return $lista; }
/** * Carrega todos os arquivos do pacote especificado o carregamento considera o classpath atual da execusão * * @param string $package nome do pacote */ public static function load($package) { self::getCurrentPath(); if (substr($package, -1, 1) != "/") { $package .= "/"; } foreach (self::$classPath as $path) { $dir = $path . $package; if (is_dir($dir)) { $d = new DirectoryIterator($dir); while ($d->valid()) { if ($d->isFile()) { $requireThis = false; //testa a extensão foreach (self::$filesExtensions as $ext) { if (substr($d->getFilename(), strlen($ext) * -1, strlen($ext)) == $ext) { $requireThis = true; break; } } if ($requireThis) { require_once $package . $d->getFilename(); } } $d->next(); } } } }
function valid() { if (parent::valid()) { if (!parent::isFile()) { parent::next(); return $this->valid(); } return TRUE; } return FALSE; }
public function valid() { if (parent::valid()) { if (!parent::isFile()) { parent::next(); return $this->valid(); } return True; } return False; }
function getTestFiles($dir = '') { $file = new DirectoryIterator($dir); $res = array(); while ($file->valid()) { if ($file->isFile() && substr($file->getPathName(), -8) == 'Test.php') { $res[] = $file->getPathName(); } $file->next(); } return $res; }
function getTestFiles($dir = '') { $file = new DirectoryIterator($dir); $res = array(); while ($file->valid()) { if ($file->isFile() && substr($file->getPathName(), -4) == '.php') { $class = str_replace(DIRECTORY_SEPARATOR, '_', substr($file->getPathName(), 0, -4)); $res[] = array($file->getPathName(), $class); } $file->next(); } return $res; }
public function pushItem(&$listing, DirectoryIterator $item) { // dot would be for morse code locale? if (!$item->isDot() && $item->isFile()) { // explode and extract name & type list($name, $type) = explode('.', $item->getFilename()); assert('!empty($name) && !empty($type); // invalid locale files'); // push name to stack if ($type == 'yml') { array_push($listing, $name); } } }
public function indexAction() { // Get path $this->view->path = $path = $this->_getPath(); $this->view->relPath = $relPath = $this->_getRelPath($path); // List files $files = array(); $dirs = array(); $contents = array(); $it = new DirectoryIterator($path); foreach ($it as $key => $file) { $filename = $file->getFilename(); if ($it->isDot() && $this->_basePath == $path || $filename == '.' || $filename != '..' && $filename[0] == '.') { continue; } $relPath = trim(str_replace($this->_basePath, '', realpath($file->getPathname())), '/\\'); $ext = strtolower(ltrim(strrchr($file->getFilename(), '.'), '.')); if ($file->isDir()) { $ext = null; } $type = 'generic'; switch (true) { case in_array($ext, array('jpg', 'png', 'gif', 'jpeg', 'bmp', 'tif', 'svg')): $type = 'image'; break; case in_array($ext, array('txt', 'log', 'js')): $type = 'text'; break; case in_array($ext, array('html', 'htm')): $type = 'markup'; break; } $dat = array('name' => $file->getFilename(), 'path' => $file->getPathname(), 'info' => $file->getPathInfo(), 'rel' => $relPath, 'ext' => $ext, 'type' => $type, 'is_dir' => $file->isDir(), 'is_file' => $file->isFile(), 'is_image' => $type == 'image', 'is_text' => $type == 'text', 'is_markup' => $type == 'markup'); if ($it->isDir()) { $dirs[$relPath] = $dat; } else { if ($it->isFile()) { $files[$relPath] = $dat; } } $contents[$relPath] = $dat; } ksort($contents); $this->view->paginator = $paginator = Zend_Paginator::factory($contents); $paginator->setItemCountPerPage(20); $paginator->setCurrentPageNumber($this->_getParam('page', 1)); $this->view->files = $files; $this->view->dirs = $dirs; $this->view->contents = $contents; }
function __construct() { $dir = new DirectoryIterator(dirname(__FILE__)); foreach ($dir as $file) { if (!$dir->isFile()) { continue; } list($code, $bs) = explode('.', $file); if (strlen($code) != 2) { continue; } include $file; $this->names[$code] = $this->codes[$code]; } }
/** * doExecute * * @return mixed */ public function doExecute() { try { $lanDir = new \DirectoryIterator($this->config['dir.src'] . '/language'); } catch (\UnexpectedValueException $e) { return; } // Each languages foreach ($lanDir as $dir) { if ($lanDir->isDot() || $lanDir->isFile()) { continue; } $this->handleINIFile($dir->getBasename()); } }
/** * This should provide the feature that the lang package can be used from * everywhere without to import it. Currently this is not working. */ private function initLang() { if ($this->initialized) { return; } $dir = new \DirectoryIterator(__DIR__); while ($dir->valid()) { $file = $dir->getFilename(); if ($dir->isFile() && ($len = strpos($file, '.php')) === strlen($file) - 4) { $name = substr($file, 0, $len); $fullName = 'blaze\\lang\\' . $name; $this->loadClass($fullName); @class_alias($fullName, $name); } $dir->next(); } }
/** * Scan the files in the configured path for controllers * * To dynamically scan controllers from the source files * use PHP Reflection to find the controllers. * * The returning result is an array of Admin_Model_DbRow_Controller elements * * @return array */ public function getControllers() { $resources = array(); $directory = new DirectoryIterator($this->path); $CcFilter = new Zend_Filter_Word_CamelCaseToDash(); while ($directory->valid()) { if ($directory->isFile() && !in_array($directory->getFilename(), $this->skip, TRUE)) { // load the file require_once $directory->getPathname(); $reflect = new Zend_Reflection_File($directory->getPathName()); $name = substr($reflect->getClass()->getName(), strrpos($reflect->getClass()->getName(), "_") + 1); $controller = new Admin_Model_DbRow_Controller(array('moduleName' => 'webdesktop', 'controllerName' => strtolower($name), 'virtual' => 1)); $resources[] = $controller; } $directory->next(); } return $resources; }
/** * scans the directory and returns all files * @param string $directory * @param string exclude * @return array|null */ public function scanDir($directory, $exclude = '') { try { $file = null; $it = new DirectoryIterator($directory); for ($it->rewind(); $it->valid(); $it->next()) { if (!$it->isDir() && !$it->isDot() && $it->isFile()) { if ($it->getFilename() == $exclude) { continue; } $file[] = $it->getFilename(); } } return $file; } catch (Exception $e) { $logger = new debug_logger(MP_LOG_DIR); $logger->log('error', 'php', 'An error has occured : ' . $e->getMessage(), debug_logger::LOG_VOID); } }
function getDirInfo($dir) { $iterator = new DirectoryIterator($dir); #先输出文件夹 while ($iterator->valid()) { if ($iterator->isDir() && $iterator->getFilename() != '.' && $iterator->getFilename() != '..' && $iterator->getFilename() != '.git') { echo '<li class="flist filedir"><i class="fa fa-folder-open"></i> ' . $iterator->getFilename(); echo '<ul class="dirlist">'; getDirInfo($iterator->getPathname()); echo '</ul></li>'; } $iterator->next(); } #再输出文件 $iterator->Rewind(); while ($iterator->valid()) { if ($iterator->isFile()) { echo '<li class="flist file"><i class="fa fa-file-text"></i> ' . $iterator->getFilename() . '</li>'; } $iterator->next(); } }
/** * @param string $src_dir * @param string $dst_dir * * @throws \Exception */ protected static function copyHooksDir($src_dir, $dst_dir) { $fs = new Filesystem(); $fs->mirror($src_dir, $dst_dir, null, ['override' => true]); $file = new \DirectoryIterator($src_dir); $mask = umask(); while ($file->valid()) { if ($file->isFile() && is_executable($file->getPathname())) { $fs->chmod("{$dst_dir}/" . $file->getBasename(), 0777, $mask); } $file->next(); } }
<?php $targetDir = __DIR__ . DIRECTORY_SEPARATOR . md5('directoryIterator::getbasename2'); mkdir($targetDir); touch($targetDir . DIRECTORY_SEPARATOR . 'getBasename_test.txt'); $dir = new DirectoryIterator($targetDir . DIRECTORY_SEPARATOR); while (!$dir->isFile()) { $dir->next(); } echo $dir->getBasename(array()); $targetDir = __DIR__ . DIRECTORY_SEPARATOR . md5('directoryIterator::getbasename2'); unlink($targetDir . DIRECTORY_SEPARATOR . 'getBasename_test.txt'); rmdir($targetDir);
/** * Run Both Unit-test and Code-coverage analysist * * @param string Path to Test (Juriya idiomatic style directory structure is required) * @return stream */ public static function runTest($target = '') { $paths = explode(PATH_SEPARATOR, get_include_path()); $pwd = $_SERVER['PWD']; if (!$target) { self::out('--test command missed target folder'); } else { // Find configuration definition $configuration = ''; $configurationExists = FALSE; if (file_exists($pwd . DIRECTORY_SEPARATOR . 'phpunit.xml')) { $configuration = $pwd . DIRECTORY_SEPARATOR . 'phpunit.xml'; $configurationExists = TRUE; } elseif (($path = $pwd . DIRECTORY_SEPARATOR . $target) && is_dir($path)) { if (($testSrc = $path . DIRECTORY_SEPARATOR . 'Tests') && is_dir($testSrc)) { $configuration = $testSrc . DIRECTORY_SEPARATOR . 'phpunit.xml'; } } else { foreach ($paths as $path) { if (($testSrc = $path . DIRECTORY_SEPARATOR . $target . DIRECTORY_SEPARATOR . 'Tests') && is_dir($testSrc)) { $configuration = $testSrc . DIRECTORY_SEPARATOR . 'phpunit.xml'; break 1; } } } // Garbage collection $coveragePhp = '/tmp/coverage.php'; file_exists($coveragePhp) and File::delete($coveragePhp); // Try to read the configuration try { $configurationInstance = \PHPUnit_Util_Configuration::getInstance($configuration); } catch (\Exception $e) { print $e->getMessage() . "\n"; exit(\PHPUnit_TextUI_TestRunner::FAILURE_EXIT); } $configurationArray = $configurationInstance->getPHPUnitConfiguration(); // Validate test suites before start processing furthermore $testDirectory = new \DirectoryIterator(str_replace('phpunit.xml', '', $configuration)); $validTestSuite = FALSE; while ($testDirectory->valid()) { if ($testDirectory->isFile() && strpos($testDirectory->getFilename(), 'Test.php') !== FALSE) { $validTestSuite = TRUE; } $testDirectory->next(); } if (!$validTestSuite) { $errorText = 'ERROR: ' . I18n::translate('command_testsuite_not_found'); if ($configurationArray['colors'] === TRUE) { $errorText = Utility::getColoredString($errorText, 'black', 'red'); } self::out($errorText); exit(\PHPUnit_TextUI_TestRunner::FAILURE_EXIT); } // Reset server arguments $_SERVER['argv'] = array('--configuration', $configuration, '--coverage-php', $coveragePhp); // Preparing reports $strippedText = 'Generating code coverage report in PHP format ... done'; $reportTestTitle = 'PHPUnit Report : '; self::out($configurationArray['colors'] ? Utility::getColoredString($reportTestTitle, 'yellow') : $reportTestTitle); $reportCcTitle = 'CodeCoverage Report : '; $reportCcTitle = $configurationArray['colors'] ? Utility::getColoredString($reportCcTitle, 'yellow') : $reportCcTitle; // Get phpunit report ob_start(); $exitCode = \PHPUnit_TextUI_Command::main(FALSE); $out = ob_get_clean(); $report = substr($out, strpos($out, "\n\n") + 1); $unitTestReport = str_replace($strippedText, $reportCcTitle, $report); $codeCoverage = @unserialize(File::read($coveragePhp)); $codeCoverageData = $codeCoverage->getData(); $codeCoverageRoot = $codeCoverage->getReport(); $codeCoverageNodes = $codeCoverageRoot->getChildNodes(); // Generate code coverage report $classCoverage = array(); $overallCoverage = array('totalClasses' => 0, 'totalCoveredClasses' => 0, 'totalMethods' => 0, 'totalCoveredMethods' => 0, 'totalLines' => 0, 'totalCoveredLines' => 0); // Closure for calculate the level $calculate = function ($percentages) { $level = 'gray'; if ($percentages >= 75) { $level = 'green'; } elseif ($percentages < 75 && $percentages >= 50) { $level = 'yellow'; } elseif ($percentages < 50 && $percentages >= 25) { $level = 'magenta'; } else { $level = 'red'; } return $level; }; $collectFromNode = function ($node) { $classes = array_merge($node->getClasses(), $node->getTraits()); $coverage = $node->getCoverageData(); $lines = array(); $ignoredLines = $node->getIgnoredLines(); foreach ($classes as $className => $class) { $classStatements = 0; $coveredClassStatements = 0; $coveredMethods = 0; foreach ($class['methods'] as $methodName => $method) { $methodCount = 0; $methodLines = 0; $methodLinesCovered = 0; for ($z = $method['startLine']; $z <= $method['endLine']; $z++) { if (isset($ignoredLines[$z])) { continue; } $add = TRUE; $count = 0; if (isset($coverage[$z])) { if ($coverage[$z] !== NULL) { $classStatements++; $methodLines++; } else { $add = FALSE; } $count = count($coverage[$z]); if ($count > 0) { $coveredClassStatements++; $methodLinesCovered++; } } else { $add = FALSE; } $methodCount = max($methodCount, $count); if ($add) { $lines[$z] = array('count' => $count, 'type' => 'stmt'); } } if ($methodCount > 0) { $coveredMethods++; } } if (!empty($class['package']['namespace'])) { $namespace = '\\' . $class['package']['namespace'] . '\\'; } elseif (!empty($class['package']['fullPackage'])) { $namespace = '@' . $class['package']['fullPackage'] . '\\'; } else { $namespace = ''; } return array('namespace' => $namespace, 'className' => $className, 'methodsCovered' => $coveredMethods, 'methodCount' => count($class['methods']), 'statementsCovered' => $coveredClassStatements, 'statementCount' => $classStatements); } }; for ($i = 0, $max = count($codeCoverageNodes); $i < $max; $i++) { $item = $codeCoverageNodes[$i]; if ($item instanceof \PHP_CodeCoverage_Report_Node_File) { array_push($classCoverage, $collectFromNode($item)); } elseif ($item instanceof \PHP_CodeCoverage_Report_Node_Directory) { foreach ($item->getChildNodes() as $itemNode) { array_push($classCoverage, $collectFromNode($itemNode)); } } else { continue; } } ksort($classCoverage); $codeCoverageReport = ''; for ($x = 0, $max = count($classCoverage); $x < $max; $x++) { $classInfo = $classCoverage[$x]; $fullQualifiedPath = $classInfo['namespace'] . $classInfo['className']; if ($classInfo['statementsCovered'] != 0) { // Increase overallCoverage $overallCoverage['totalClasses']++; $overallCoverage['totalMethods'] = $overallCoverage['totalMethods'] + $classInfo['methodCount']; $overallCoverage['totalCoveredMethods'] = $overallCoverage['totalCoveredMethods'] + $classInfo['methodsCovered']; $overallCoverage['totalLines'] = $overallCoverage['totalLines'] + $classInfo['statementCount']; $overallCoverage['totalCoveredLines'] = $overallCoverage['totalCoveredLines'] + $classInfo['statementsCovered']; // Build item Code-coverage main report $ccPath = $fullQualifiedPath; $ccMethods = str_pad(' Methods(' . $classInfo['methodsCovered'] . '/' . $classInfo['methodCount'] . ')', 18, ' '); $ccLines = str_pad(' Lines(' . $classInfo['statementsCovered'] . '/' . $classInfo['statementCount'] . ')', 18, ' '); // Calculate the percentage $ccMethodsPercentages = round((int) $classInfo['methodsCovered'] / (int) $classInfo['methodCount'] * 100, 2); $ccLinesPercentages = round((int) $classInfo['statementsCovered'] / (int) $classInfo['statementCount'] * 100, 2); // Normalize the pad $ccMethodsPercentagesText = $ccMethods . ': ' . str_pad($ccMethodsPercentages . '% ', 8, ' ', STR_PAD_LEFT); $ccLinesPercentagesText = $ccLines . ': ' . str_pad($ccLinesPercentages . '% ', 8, ' ', STR_PAD_LEFT); // Increase classed covered for 100% classes if ($ccMethodsPercentages == 100 && $ccLinesPercentages == 100) { $overallCoverage['totalCoveredClasses']++; } // Colorize if necessary if ($configurationArray['colors'] === TRUE) { $ccPath = Utility::getColoredString($ccPath, 'light_cyan'); $ccMethodsLevel = $calculate($ccMethodsPercentages); $ccLinesLevel = $calculate($ccLinesPercentages); $ccMethodsPercentagesText = Utility::getColoredString($ccMethodsPercentagesText, 'black', $ccMethodsLevel); $ccLinesPercentagesText = Utility::getColoredString($ccLinesPercentagesText, 'black', $ccLinesLevel); } $codeCoverageReport .= PHP_EOL . $ccPath . PHP_EOL . $ccMethodsPercentagesText . PHP_EOL . $ccLinesPercentagesText . PHP_EOL; } } // Finalize Code-coverage report if ($overallCoverage['totalCoveredClasses'] > 0) { $overallPercentage = round((int) $overallCoverage['totalCoveredClasses'] / (int) $overallCoverage['totalClasses'] * 100, 2); } else { $overallPercentage = 0; } if ($overallPercentage >= 75) { $overallPercentageText = 'OK'; } elseif ($overallPercentage < 75 && $overallPercentage >= 50) { $overallPercentageText = 'MEDIUM'; } else { $overallPercentageText = 'LOW'; } $overallCoverageReport = $overallPercentageText . ' ('; $overallCoverageReport .= $overallPercentage; $overallCoverageReport .= '% classes, '; if ($overallCoverage['totalCoveredMethods'] > 0) { $overallCoverageReport .= round((int) $overallCoverage['totalCoveredMethods'] / (int) $overallCoverage['totalMethods'] * 100, 2); } else { $overallCoverageReport .= 0; } $overallCoverageReport .= '% methods, '; if ($overallCoverage['totalCoveredLines'] > 0) { $overallCoverageReport .= round((int) $overallCoverage['totalCoveredLines'] / (int) $overallCoverage['totalLines'] * 100, 2); } else { $overallCoverageReport .= 0; } $overallCoverageReport .= '% lines were covered)'; // Colorize if necessary if ($configurationArray['colors'] === TRUE) { $coverageStatus = $calculate($overallPercentage); $overallCoverageReport = Utility::getColoredString($overallCoverageReport, 'black', $coverageStatus); } $codeCoverageReport .= PHP_EOL . $overallCoverageReport . PHP_EOL; // Output all tests reports self::out($unitTestReport . $codeCoverageReport); exit($exitCode); } }
/** * {@inheritDoc} */ protected function determinePresentFiles($language) { $iterator = new \DirectoryIterator($this->getDestinationBasePath() . DIRECTORY_SEPARATOR . $language); $files = array(); while ($iterator->valid()) { if (!$iterator->isDot() && $iterator->isFile() && $this->isValidDestinationFile($iterator->getPathname())) { $files[] = $iterator->getFilename(); } $iterator->next(); } return $files; }
$filesToProcess = isset($argv[3]) ? $argv[3] : ''; if (empty($lPrimary) || empty($lSecondary) || empty($filesToProcess)) { $rc = 1; $msg = '***** Script to clean language files *****' . "\n"; $msg .= 'Usage: ./dev/translation/strip_language_file.php xx_XX xx_YY [file.lang|all]' . "\n"; print $msg . "(rc={$rc}).\n"; exit($rc); } $aPrimary = array(); $aSecondary = array(); $aEnglish = array(); // Define array $filesToProcess if ($filesToProcess == 'all') { $dir = new DirectoryIterator('htdocs/langs/' . $lPrimary); while ($dir->valid()) { if (!$dir->isDot() && $dir->isFile() && !preg_match('/^\\./', $dir->getFilename())) { $files[] = $dir->getFilename(); } $dir->next(); } $filesToProcess = $files; } else { $filesToProcess = explode(',', $filesToProcess); } // Arguments should be OK here. // Loop on each file foreach ($filesToProcess as $fileToProcess) { $lPrimaryFile = 'htdocs/langs/' . $lPrimary . '/' . $fileToProcess; $lSecondaryFile = 'htdocs/langs/' . $lSecondary . '/' . $fileToProcess; $lEnglishFile = 'htdocs/langs/' . $lEnglish . '/' . $fileToProcess; $output = $lSecondaryFile . '.delta';
$foto = PegarPeloId('pizzas', 'pizza_id', $id); $fotosPastas = array(); if (empty($foto)) { $erro = "Foto já deletada"; } else { $fotoInicial = $foto['pizza_foto_inicio']; $fotoInicio = explode("/", $fotoInicial); $fotoDetalhes = $foto['pizza_foto_detalhes']; $fotoD = explode("/", $fotoDetalhes); $dir = "../../fotos"; //$directories = array("../../fotos", "../../detalhes"); // foreach($directories as $dir) // { $d = new DirectoryIterator("../../fotos"); while ($d->valid()) { if ($d->isFile()) { $fotosPastas[] = $d->getFilename(); } $d->next(); } if (in_array($fotoInicio[1], $fotosPastas) and in_array($fotoD[1], $fotosPastas)) { if (unlink("../../fotos/" . $fotoInicio[1])) { if (unlink("../../detalhes/" . $fotoD[1])) { $mensagem = "Foto deletada com sucesso"; } else { $erro = "Erro ao deletar foto detalhes"; } } else { $erro = "Erro ao deletar foto inicial"; } }
/** * Entity/Model * @param DirectoryIterator $fileInfo */ private function patchEntityModel(\DirectoryIterator $fileInfo) { if ($fileInfo->isFile()) { $filePath = $fileInfo->getPathname(); $content = file_get_contents($filePath); $imeplements = ['\\Common\\CoreBundle\\Type\\EntityInterface']; if (preg_match('#(abstract class [^\\\\]*?\\s+?implements\\s+?)(.*)#', $content, $m)) { $m = explode(',', $m[2]); array_walk($m, 'trim'); $imeplements = array_merge($imeplements, $m); } if (preg_match('/toArray/', $content)) { $imeplements[] = '\\Common\\CoreBundle\\Type\\ArraybleInterface'; } $imeplements = array_values($imeplements); $imeplements = array_map('trim', $imeplements); $imeplements = implode(', ', $imeplements); $content = preg_replace("#(abstract class [^\\\\]*?)(\\s+?implements\\s+?)(.*)(\n\\{)#", '\\1\\4', $content); $content = preg_replace("/(abstract class .*?)(\n\\{)/", '\\1 implements ' . $imeplements . '\\2', $content); if (preg_match('/Type\\\\/', $content)) { $content = preg_replace('#\\\\Common\\\\CoreBundle\\\\Type#', 'Type', $content); $content = preg_replace('/namespace (.*?);/', 'namespace \\1;' . "\n\n" . 'use Common\\CoreBundle\\Type;', $content); } $isObservable = (bool) strpos($imeplements, 'ObservableInterface'); $contentMap = ['/\\\\DateInterval/' => 'Type\\DateInterval', '/\\?\\s+?(\\$this->.*?)->format\\(\'Y-m-d\'\\)\\s+?:/' => '? \\1->format(Type\\Date::DEFAULT_FORMAT) :', '/\\?\\s+?(\\$this->.*?)->format\\(\'Y-m-d H:i:s\'\\)\\s+?:/' => '? \\1->format(Type\\DateTime::DEFAULT_FORMAT) :', '/\\?\\s+?(\\$this->.*?)->format\\(\'Y-m-d H:i:s\\.u\'\\)\\s+?:/' => '? Type\\DateTime::_foramt(\\1) :', '/\\?\\s+?(\\$this->.*?)->format\\(\'P%yY%mM%dDT%hH%iI%sS\'\\)\\s+?:/' => '? \\1->format(null) :', '/(\\s+)(\\*)(\\s+)\\n/' => '\\1\\2' . "\n"]; if ($isObservable) { $contentMap['/(abstract class .*?)(\\n\\{)/'] = '\\1\\2' . <<<PHP use Type\\ModelTrait; use Type\\ObservableTrait; PHP; } else { $contentMap['/(abstract class .*?)(\\n\\{)/'] = '\\1\\2' . <<<PHP use Type\\ModelTrait; PHP; } $from = array_keys($contentMap); $to = array_values($contentMap); $content = preg_replace($from, $to, $content); $content = preg_replace("/(use .*?;)\n{2}(use .*?;)/", '\\1' . "\n" . '\\2', $content); file_put_contents($filePath, $content); if ($isObservable) { $this->removeObservable($filePath); } } }
function deletarFoto($fotoInicial, $fotoDetalhes, $dir) { global $erro; $fotoInicio = explode("/", $fotoInicial); $fotoD = explode("/", $fotoDetalhes); //$dir = "../../fotos"; $d = new DirectoryIterator($dir); while ($d->valid()) { if ($d->isFile()) { $fotosPastas[] = $d->getFilename(); } $d->next(); } // var_dump($fotoInicio); // var_dump($fotoD); // var_dump($fotosPastas); if (in_array($fotoInicio[1], $fotosPastas) and in_array($fotoD[1], $fotosPastas)) { if (unlink("../../fotos/" . $fotoInicio[1])) { if (unlink("../../detalhes/" . $fotoD[1])) { return true; } else { return false; } } else { $erro = "Erro ao deletar foto inicial"; } } }
/** * Get list of files for file browser * @param int $seek * @param int $limit * @param string $filter * @param bool $secure use secure folder instead of repository root * @return array */ public function getAvailableFiles($seek, $limit, $filter, $filterExtensions, $secure = false, $subdir = null) { $answer = array(); if ($subdir && substr($subdir, -1) != '/') { $subdir .= '/'; } $repositoryDir = $this->getPath($secure, $subdir); $iterator = new \DirectoryIterator($repositoryDir); $iterator->seek($seek); while ($iterator->valid() && count($answer) < $limit) { if ($iterator->isFile()) { $fileData = $this->getFileData($iterator->getFilename(), $secure, $subdir); $append = null; switch ($filter) { case 'image': if (in_array($fileData['ext'], $this->supportedImageExtensions)) { $append = $fileData; } break; default: $append = $fileData; break; } if ($filterExtensions && !in_array($fileData['ext'], $filterExtensions)) { $append = null; } if ($append) { $answer[] = $append; } } $iterator->next(); } return $answer; }
/** * Process active directory * * @param string $path * @param SeekR_Row $directoryRow */ protected final function _processDirectoryActive($path, SeekR_Row $directoryRow = null) { $entries = new DirectoryIterator($path); $directoryChanged = false; $data = array('modifyDate' => $this->_normalizeDate(filemtime($path)), 'owner' => $this->_normalizeUser(fileowner($path)), 'group' => $this->_normalizeGroup(filegroup($path)), 'permissions' => fileperms($path), 'linkTarget' => is_link($path) ? readlink($path) : null); // New directory row if (!$directoryRow) { fwrite(STDOUT, "\t{$path} is new.\n"); $directoryRow = $this->_createDirectoryRow(array('path' => $path) + $data); } else { // Check directory data if ($this->_isDirectoryChanged($directoryRow, $data)) { fwrite(STDOUT, "\t{$path} has been changed.\n"); $directoryChanged = true; } } // Entries of non-linked directories if (!is_link($path)) { foreach ($entries as $entry) { $pathname = $entries->getPathname(); if (!$entries->isDot() && !$this->_isEntryOfSkipPatterns($pathname)) { // Subdirectory if ($entries->isDir()) { $this->_processDirectory($pathname . '/'); } else { // File if ($entries->isFile()) { $this->_processFile($directoryRow->directoryID, $entries); } } } } } // Removed files $this->_processDirectoryRemovedFiles($directoryRow); // Transaction $this->_db->beginTransaction(); // Update row if ($directoryChanged) { $this->_updateDirectoryRow($directoryRow, $data); } $directoryRow->lastScanID = $this->_scanRow->scanID; $directoryRow->save(); // Scan row update $this->_scanRow->lastOperationDate = new SeekR_Expression('NOW()'); $this->_scanRow->save(); // Transaction $this->_db->commit(); }
/** * Delete old cached files based on cache time and cache gc probability set * in the config file. */ private function clean_cache() { //gc probability $gc = rand(1, Kohana::config($this->type . '.cache_gc')); if ($gc != 1) { return FALSE; } $cache = new DirectoryIterator(Kohana::config($this->type . '.cache_folder')); while ($cache->valid()) { // if file is past maximum cache settings delete file $cached = date('U', $cache->getMTime()); $max = time() + Kohana::config($this->type . '.cache_clean_time'); if ($cache->isFile() and $cached > $max) { unlink($cache->getPathname()); } $cache->next(); } }
protected function execute(InputInterface $input, OutputInterface $output) { // Fetch all the aliases $aliases = $this->mimetypeDetector->getAllAliases(); // Remove comments $keys = array_filter(array_keys($aliases), function ($k) { return $k[0] === '_'; }); foreach ($keys as $key) { unset($aliases[$key]); } // Fetch all files $dir = new \DirectoryIterator(\OC::$SERVERROOT . '/core/img/filetypes'); $files = []; foreach ($dir as $fileInfo) { if ($fileInfo->isFile()) { $file = preg_replace('/.[^.]*$/', '', $fileInfo->getFilename()); $files[] = $file; } } //Remove duplicates $files = array_values(array_unique($files)); // Fetch all themes! $themes = []; $dirs = new \DirectoryIterator(\OC::$SERVERROOT . '/themes/'); foreach ($dirs as $dir) { //Valid theme dir if ($dir->isFile() || $dir->isDot()) { continue; } $theme = $dir->getFilename(); $themeDir = $dir->getPath() . '/' . $theme . '/core/img/filetypes/'; // Check if this theme has its own filetype icons if (!file_exists($themeDir)) { continue; } $themes[$theme] = []; // Fetch all the theme icons! $themeIt = new \DirectoryIterator($themeDir); foreach ($themeIt as $fileInfo) { if ($fileInfo->isFile()) { $file = preg_replace('/.[^.]*$/', '', $fileInfo->getFilename()); $themes[$theme][] = $file; } } //Remove Duplicates $themes[$theme] = array_values(array_unique($themes[$theme])); } //Generate the JS $js = '/** * This file is automatically generated * DO NOT EDIT MANUALLY! * * You can update the list of MimeType Aliases in config/mimetypealiases.json * The list of files is fetched from core/img/filetypes * To regenerate this file run ./occ maintenance:mimetypesjs */ OC.MimeTypeList={ aliases: ' . json_encode($aliases, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . ', files: ' . json_encode($files, JSON_PRETTY_PRINT) . ', themes: ' . json_encode($themes, JSON_PRETTY_PRINT) . ' }; '; //Output the JS file_put_contents(\OC::$SERVERROOT . '/core/js/mimetypelist.js', $js); $output->writeln('<info>mimetypelist.js is updated'); }
/** * getTranslationFilesArray * * @param string $lang Language code * @return array Array */ private function getTranslationFilesArray($lang) { $dir = new DirectoryIterator($this->_langDir . $lang); while ($dir->valid()) { if (!$dir->isDot() && $dir->isFile() && !preg_match('/^\\./', $dir->getFilename())) { $files[] = $dir->getFilename(); } $dir->next(); } return $files; }
/** * Directory iterator * * @param string $fullpath - full path to the director we wish to iterate * @return array - numerical index of returned pages */ private function dirIterator($fullpath) { $it = new DirectoryIterator($fullpath); while ($it->valid()) { if (!$it->isDot() && $it->isFile() && $it->isReadable() && substr($it->getFilename(), -4, 4) == '.php') { $files[] = $it->getFilename(); } $it->next(); } return $files; }