$stack, 'visited' => 0); } /** * Visit entries until the deadline or the file limit is reached. * $callback($path, $stat, $is_dir) is called for every file (and for directories when * $options['dirs'] is true). Returning false from the callback for a directory skips it. * Options: excludes (array of names), exclude_paths (array of absolute paths), max_files, dirs * Returns the updated cursor; $cursor['stack'] is empty when the walk is complete. */ public static function walk($cursor, $callback, $deadline, $options = array()) { $options = array_merge(array('excludes' => self::default_excludes(), 'exclude_paths' => array(), 'max_files' => 100000, 'dirs' => false), $options); $exclude_paths = array_map(function ($p) { return untrailingslashit(wp_normalize_path($p)); }, $options['exclude_paths']); $listings = array(); $iterations = 0; while (!empty($cursor['stack'])) { if ((++$iterations % 50) === 0 && microtime(true) >= $deadline) { break; } if ($cursor['visited'] >= $options['max_files']) { $cursor['stack'] = array(); $cursor['truncated'] = true; break; } $top = count($cursor['stack']) - 1; list($dir, $offset) = $cursor['stack'][$top]; if (!isset($listings[$dir])) { $entries = @scandir($dir); $listings[$dir] = is_array($entries) ? array_values(array_diff($entries, array('.', '..'))) : array(); } if ($offset >= count($listings[$dir])) { array_pop($cursor['stack']); unset($listings[$dir]); continue; } $cursor['stack'][$top][1]++; $name = $listings[$dir][$offset]; $path = $dir . '/' . $name; $stat = @lstat($path); if ($stat === false || is_link($path)) { continue; } $is_dir = ($stat['mode'] & 0170000) === 0040000; if ($is_dir) { if (in_array($name, $options['excludes'], true) || in_array($path, $exclude_paths, true)) { if ($options['dirs']) { call_user_func($callback, $path, $stat, true); } continue; } if ($options['dirs'] && call_user_func($callback, $path, $stat, true) === false) { continue; } $cursor['stack'][] = array($path, 0); continue; } $cursor['visited']++; call_user_func($callback, $path, $stat, false); } return $cursor; } public static function is_done($cursor) { return empty($cursor['stack']); } /** * Read the first bytes of a file (for signatures) */ public static function head($path, $bytes = 512) { $fp = @fopen($path, 'rb'); if (!$fp) { return ''; } $data = fread($fp, $bytes); fclose($fp); return $data === false ? '' : $data; } }