Skip to main content

php_std/
path.rs

1//! Path functions.
2
3/// PHP `dirname($path)` (one level, Unix separators), as `zend_dirname`.
4pub fn dirname(path: &str) -> String {
5    let b = path.as_bytes();
6    if b.is_empty() {
7        return String::new();
8    }
9    let mut end = b.len() as isize - 1;
10    while end >= 0 && b[end as usize] == b'/' {
11        end -= 1;
12    }
13    if end < 0 {
14        return "/".into();
15    }
16    while end >= 0 && b[end as usize] != b'/' {
17        end -= 1;
18    }
19    if end < 0 {
20        return ".".into();
21    }
22    while end >= 0 && b[end as usize] == b'/' {
23        end -= 1;
24    }
25    if end < 0 {
26        return "/".into();
27    }
28    String::from_utf8_lossy(&b[..=end as usize]).into_owned()
29}
30
31/// PHP `basename($path, $suffix)` (Unix separators), as `php_basename`: the
32/// last component, trailing slashes ignored, with `suffix` removed when the
33/// component ends with it and is longer than it.
34///
35/// ```
36/// use php_std::path::basename;
37///
38/// assert_eq!(basename(b"/tmp/report.pdf/", b""), b"report.pdf");
39/// assert_eq!(basename(b"/tmp/report.pdf", b".pdf"), b"report");
40/// assert_eq!(basename(b"/", b""), b"");
41/// ```
42pub fn basename<'a>(path: &'a [u8], suffix: &[u8]) -> &'a [u8] {
43    let (mut start, mut end) = (0, 0);
44    let mut inside = false;
45    for (i, &b) in path.iter().enumerate() {
46        if b == b'/' {
47            if inside {
48                inside = false;
49                end = i;
50            }
51        } else if !inside {
52            start = i;
53            inside = true;
54        }
55    }
56    if inside {
57        end = path.len();
58    }
59    let name = &path[start..end];
60    if !suffix.is_empty() && suffix.len() < name.len() && name.ends_with(suffix) {
61        return &name[..name.len() - suffix.len()];
62    }
63    name
64}
65
66/// PHP `pathinfo($path, PATHINFO_EXTENSION)`: what follows the last `.` of
67/// [`basename`], or an empty string when it has no `.`.
68///
69/// ```
70/// use php_std::path::pathinfo_extension;
71///
72/// assert_eq!(pathinfo_extension(b"server/pages/index.html"), b"html");
73/// assert_eq!(pathinfo_extension(b"archive.tar.gz"), b"gz");
74/// assert_eq!(pathinfo_extension(b"Dockerfile"), b"");
75/// assert_eq!(pathinfo_extension(b".env"), b"env");
76/// ```
77///
78/// ```php
79/// var_dump(pathinfo('server/pages/index.html', PATHINFO_EXTENSION)); // string(4) "html"
80/// var_dump(pathinfo('Dockerfile', PATHINFO_EXTENSION));              // string(0) ""
81/// ```
82pub fn pathinfo_extension(path: &[u8]) -> &[u8] {
83    let base = basename(path, b"");
84    match base.iter().rposition(|&b| b == b'.') {
85        Some(dot) => &base[dot + 1..],
86        None => b"",
87    }
88}
89
90/// `MAXPATHLEN` on Linux, where PHP runs.
91const MAXPATHLEN: usize = 4096;
92
93/// `expand_filepath()`: the absolute path PHP opens for `path`. A relative
94/// path is resolved against the working directory, then `.` and `..`
95/// components and repeated slashes are removed lexically (a trailing slash
96/// stays),
97/// without resolving symbolic links. `None` for an empty path or one longer
98/// than `MAXPATHLEN`.
99///
100/// ```
101/// use php_std::path::expand_filepath;
102///
103/// assert_eq!(expand_filepath(b"/tmp/a/../b//c/."), Some(b"/tmp/b/c".to_vec()));
104/// assert_eq!(expand_filepath(b"/.."), Some(b"/".to_vec()));
105/// ```
106pub fn expand_filepath(path: &[u8]) -> Option<Vec<u8>> {
107    use std::os::unix::ffi::OsStrExt;
108    if path.is_empty() || path.len() >= MAXPATHLEN - 1 {
109        return None;
110    }
111    let mut full = Vec::with_capacity(path.len());
112    if path[0] != b'/'
113        && let Ok(cwd) = std::env::current_dir()
114    {
115        full.extend_from_slice(cwd.as_os_str().as_bytes());
116        full.push(b'/');
117    }
118    full.extend_from_slice(path);
119    let mut parts: Vec<&[u8]> = Vec::new();
120    for part in full.split(|b| *b == b'/') {
121        match part {
122            b"" | b"." => {}
123            b".." => {
124                parts.pop();
125            }
126            part => parts.push(part),
127        }
128    }
129    let mut out = Vec::with_capacity(full.len());
130    for part in parts {
131        out.push(b'/');
132        out.extend_from_slice(part);
133    }
134    if out.is_empty() {
135        out.push(b'/');
136    }
137    // `virtual_file_ex()` keeps a trailing slash (`CWD_EXPAND`), so a file
138    // named with one does not open.
139    if path.ends_with(b"/") && !out.ends_with(b"/") {
140        out.push(b'/');
141    }
142    (out.len() < MAXPATHLEN).then_some(out)
143}
144
145/// `file_get_contents($path)` for a plain file path: the bytes of the file
146/// at [`expand_filepath`]`(path)`, or `None` where PHP returns `false` (no
147/// such file, a directory, no permission). Paths with a NUL byte are
148/// `None`; PHP functions raise a `\ValueError` for them before opening.
149pub fn file_get_contents(path: &[u8]) -> Option<Vec<u8>> {
150    use std::os::unix::ffi::OsStrExt;
151    if path.contains(&0) {
152        return None;
153    }
154    let path = expand_filepath(path)?;
155    std::fs::read(std::ffi::OsStr::from_bytes(&path)).ok()
156}
157
158#[cfg(test)]
159mod expand_tests {
160    use super::expand_filepath;
161
162    #[test]
163    fn lexical() {
164        assert_eq!(expand_filepath(b"/a/b/../../.."), Some(b"/".to_vec()));
165        assert_eq!(expand_filepath(b"/a/./b/"), Some(b"/a/b/".to_vec()));
166        assert_eq!(expand_filepath(b""), None);
167        assert_eq!(expand_filepath(&[b'a'; 5000]), None);
168        assert!(expand_filepath(b"x").unwrap().ends_with(b"/x"));
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::dirname;
175
176    #[test]
177    fn like_php() {
178        for (input, expected) in [
179            ("/tmp/x.lock", "/tmp"),
180            ("x.lock", "."),
181            ("/x", "/"),
182            ("/", "/"),
183            ("a/b/", "a"),
184            ("a//b", "a"),
185            ("", ""),
186            (".", "."),
187            ("/a/b/../c", "/a/b/.."),
188        ] {
189            assert_eq!(dirname(input), expected, "{input}");
190        }
191    }
192}