/
functions.php
84 lines (74 loc) · 2.1 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
function get_directories_to_search($dirs, $pattern) {
// convert pattern into a regular expression
$pattern = str_replace("*", "[^/]+", $pattern);
$pattern = "#" . $pattern . "$#";
// find all matching directories
$result = array();
foreach ($dirs as $dir) {
if (preg_match($pattern, $dir)) {
$result[] = $dir;
}
}
return $result;
}
function get_all_directories($root, $max_depth = 3) {
$result = array();
if ($handle = opendir($root)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && is_dir($root . "/" . $entry)) {
$result[] = $root . "/" . $entry;
if ($max_depth > 1) {
$result = array_merge($result, get_all_directories($root . "/" . $entry, $max_depth - 1));
}
}
}
closedir($handle);
}
return $result;
}
function make_target_directories($dirs) {
foreach ($dirs as $path) {
// remove any filenames
if (substr($path, -1) !== "/") {
$path = substr($path, 0, strrpos($path, "/"));
}
if (!file_exists($path)) {
echo "Making directory '$path' recursively...\n";
mkdir($path, 0777, true);
}
}
}
function get_matching_paths($root, $dir, $path) {
// a simple way to match paths: just find all files that match, and
// then filter
$result = get_all_files($root, $dir);
// filter out
$filtered = array();
foreach ($result as $value) {
if (fnmatch($dir . "/" . $path, $value)) {
$filtered[] = $value;
}
}
// sort and renumber
sort($filtered);
return $filtered;
}
function get_all_files($root, $dir, $max_depth = 3) {
$result = array();
if ($handle = opendir($root . "/" . $dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($root . "/" . $dir . "/" . $entry)) {
if ($max_depth > 1) {
$result = array_merge($result, get_all_files($root, $dir . "/" . $entry, $max_depth - 1));
}
} else {
$result[] = $dir . "/" . $entry;
}
}
}
closedir($handle);
}
return $result;
}