ctb_formats_dceutils/
to_csv.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Utilities for processing and parsing DCE data files.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use anyhow::{Context, Result, anyhow};
30use std::collections::HashMap;
31
32/// Parses the bytes of a PHP data file containing array definitions
33/// and converts them to CSV format.
34///
35/// Returns a map from array names to their CSV file bytes.
36pub fn php_to_csvs(bytes: &[u8]) -> Result<HashMap<String, Vec<u8>>> {
37    let content = std::str::from_utf8(bytes)
38        .map_err(|e| anyhow!("Invalid UTF-8 in PHP file: {e}"))?;
39
40    let arrays = find_arrays(content);
41    let mut result = HashMap::new();
42
43    for (name, array_content) in arrays {
44        let elements = split_elements(&array_content);
45        let mut pairs = Vec::new();
46
47        for (i, elem) in elements.iter().enumerate() {
48            let elem_trimmed = elem.trim();
49            if elem_trimmed.is_empty() {
50                continue;
51            }
52            if let Some(arrow_idx) = find_arrow(elem_trimmed) {
53                #[expect(
54                    clippy::expect_used,
55                    reason = "arrow_idx is returned by find_arrow, guaranteeing a valid char boundary"
56                )]
57                let key_part = elem_trimmed
58                    .get(..arrow_idx)
59                    .expect("arrow_idx is returned by find_arrow")
60                    .trim();
61                let arrow_idx_plus_2 = arrow_idx
62                    .checked_add(2)
63                    .ok_or_else(|| anyhow!("Index overflow"))?;
64                // Reason for fallback: in PHP array syntax, trailing '=>' without a value specifies a key mapped to an empty string value.
65                let val_part =
66                    elem_trimmed.get(arrow_idx_plus_2..).unwrap_or("").trim();
67                let key = parse_php_string(key_part);
68                let val = parse_php_string(val_part);
69                pairs.push((key, val));
70            } else {
71                let val = parse_php_string(elem_trimmed);
72                let key = i.to_string();
73                pairs.push((key, val));
74            }
75        }
76
77        let csv_bytes = generate_csv(&pairs);
78        let _ = result.insert(name, csv_bytes);
79    }
80
81    Ok(result)
82}
83
84/// Reads the PHP file name passed in, calls `php_to_csvs` with the bytes
85/// of the file, and writes out the new CSVs in the current working directory.
86pub fn php_file_to_csv_files<P: AsRef<std::path::Path>>(path: P) -> Result<()> {
87    let path = path.as_ref();
88    let file_name = path
89        .file_name()
90        .and_then(|n| n.to_str())
91        .ok_or_else(|| anyhow!("Invalid path filename"))?;
92
93    let bytes = std::fs::read(path).with_context(|| {
94        format!("Failed to read PHP file from {}", path.display())
95    })?;
96
97    let csvs = php_to_csvs(&bytes)?;
98
99    for (label, csv_bytes) in csvs {
100        let out_filename = format!("{file_name}-{label}.csv");
101        let out_path = std::path::Path::new(&out_filename);
102        std::fs::write(out_path, csv_bytes).with_context(|| {
103            format!("Failed to write CSV file {}", out_path.display())
104        })?;
105    }
106
107    Ok(())
108}
109
110#[expect(
111    clippy::too_many_lines,
112    clippy::while_let_on_iterator,
113    reason = "complex state-machine parser function"
114)]
115fn find_arrays(input: &str) -> Vec<(String, String)> {
116    let mut arrays = Vec::new();
117    let mut chars = input.char_indices().peekable();
118
119    while let Some(&(_, c)) = chars.peek() {
120        if c == '/' {
121            chars.next();
122            if let Some(&(_, '/')) = chars.peek() {
123                chars.next();
124                while let Some((_, nc)) = chars.next() {
125                    if nc == '\n' {
126                        break;
127                    }
128                }
129            } else if let Some(&(_, '*')) = chars.peek() {
130                chars.next();
131                while let Some((_, nc)) = chars.next() {
132                    if nc == '*' {
133                        if let Some(&(_, '/')) = chars.peek() {
134                            chars.next();
135                            break;
136                        }
137                    }
138                }
139            }
140        } else if c == '#' {
141            chars.next();
142            while let Some((_, nc)) = chars.next() {
143                if nc == '\n' {
144                    break;
145                }
146            }
147        } else if c == '$' {
148            chars.next();
149            let mut name = String::new();
150            while let Some(&(_, nc)) = chars.peek() {
151                if nc.is_ascii_alphanumeric() || nc == '_' {
152                    name.push(nc);
153                    chars.next();
154                } else {
155                    break;
156                }
157            }
158            if name.is_empty() {
159                continue;
160            }
161
162            let mut found_eq = false;
163            while let Some(&(_, nc)) = chars.peek() {
164                if nc.is_whitespace() {
165                    chars.next();
166                } else if nc == '=' {
167                    found_eq = true;
168                    chars.next();
169                    break;
170                } else {
171                    break;
172                }
173            }
174            if !found_eq {
175                continue;
176            }
177
178            while let Some(&(_, nc)) = chars.peek() {
179                if nc.is_whitespace() {
180                    chars.next();
181                } else {
182                    break;
183                }
184            }
185
186            let mut is_array = true;
187            for expected in "array".chars() {
188                if let Some(&(_, nc)) = chars.peek() {
189                    if nc == expected {
190                        chars.next();
191                    } else {
192                        is_array = false;
193                        break;
194                    }
195                } else {
196                    is_array = false;
197                    break;
198                }
199            }
200            if !is_array {
201                continue;
202            }
203
204            while let Some(&(_, nc)) = chars.peek() {
205                if nc.is_whitespace() {
206                    chars.next();
207                } else {
208                    break;
209                }
210            }
211
212            if let Some(&(_, '(')) = chars.peek() {
213                chars.next();
214            } else {
215                continue;
216            }
217
218            let mut nesting: usize = 0;
219            let mut content = String::new();
220            let mut in_single_quote = false;
221            let mut in_double_quote = false;
222            let mut escape = false;
223
224            while let Some((_, nc)) = chars.next() {
225                if escape {
226                    content.push(nc);
227                    escape = false;
228                    continue;
229                }
230                if nc == '\\' {
231                    content.push(nc);
232                    escape = true;
233                    continue;
234                }
235                if in_single_quote {
236                    content.push(nc);
237                    if nc == '\'' {
238                        in_single_quote = false;
239                    }
240                } else if in_double_quote {
241                    content.push(nc);
242                    if nc == '"' {
243                        in_double_quote = false;
244                    }
245                } else if nc == '\'' {
246                    in_single_quote = true;
247                    content.push(nc);
248                } else if nc == '"' {
249                    in_double_quote = true;
250                    content.push(nc);
251                } else if nc == '(' {
252                    nesting = nesting.saturating_add(1);
253                    content.push(nc);
254                } else if nc == ')' {
255                    if nesting == 0 {
256                        arrays.push((name.clone(), content));
257                        break;
258                    }
259                    nesting = nesting.saturating_sub(1);
260                    content.push(nc);
261                } else {
262                    content.push(nc);
263                }
264            }
265        } else {
266            chars.next();
267        }
268    }
269    arrays
270}
271
272fn split_elements(content: &str) -> Vec<String> {
273    let mut elements = Vec::new();
274    let mut current = String::new();
275    let mut nesting: usize = 0;
276    let mut in_single_quote = false;
277    let mut in_double_quote = false;
278    let mut escape = false;
279
280    for c in content.chars() {
281        if escape {
282            current.push(c);
283            escape = false;
284            continue;
285        }
286        if c == '\\' {
287            current.push(c);
288            escape = true;
289            continue;
290        }
291        if in_single_quote {
292            current.push(c);
293            if c == '\'' {
294                in_single_quote = false;
295            }
296        } else if in_double_quote {
297            current.push(c);
298            if c == '"' {
299                in_double_quote = false;
300            }
301        } else if c == '\'' {
302            in_single_quote = true;
303            current.push(c);
304        } else if c == '"' {
305            in_double_quote = true;
306            current.push(c);
307        } else if c == '(' {
308            nesting = nesting.saturating_add(1);
309            current.push(c);
310        } else if c == ')' {
311            if nesting > 0 {
312                nesting = nesting.saturating_sub(1);
313            }
314            current.push(c);
315        } else if c == ',' {
316            if nesting == 0 {
317                elements.push(current);
318                current = String::new();
319            } else {
320                current.push(c);
321            }
322        } else {
323            current.push(c);
324        }
325    }
326
327    let trimmed = current.trim();
328    if !trimmed.is_empty() {
329        elements.push(current);
330    }
331
332    elements
333}
334
335fn find_arrow(element: &str) -> Option<usize> {
336    let mut chars = element.char_indices().peekable();
337    let mut nesting: usize = 0;
338    let mut in_single_quote = false;
339    let mut in_double_quote = false;
340    let mut escape = false;
341
342    while let Some((i, c)) = chars.next() {
343        if escape {
344            escape = false;
345            continue;
346        }
347        if c == '\\' {
348            escape = true;
349            continue;
350        }
351        if in_single_quote {
352            if c == '\'' {
353                in_single_quote = false;
354            }
355        } else if in_double_quote {
356            if c == '"' {
357                in_double_quote = false;
358            }
359        } else if c == '\'' {
360            in_single_quote = true;
361        } else if c == '"' {
362            in_double_quote = true;
363        } else if c == '(' {
364            nesting = nesting.saturating_add(1);
365        } else if c == ')' {
366            if nesting > 0 {
367                nesting = nesting.saturating_sub(1);
368            }
369        } else if c == '=' {
370            if nesting == 0 {
371                if let Some(&(_, '>')) = chars.peek() {
372                    return Some(i);
373                }
374            }
375        }
376    }
377    None
378}
379
380#[expect(
381    clippy::expect_used,
382    reason = "s starts and ends with quote chars and has length >= 2"
383)]
384fn parse_php_string(s: &str) -> String {
385    let s = s.trim();
386    if (s.starts_with('\'') && s.ends_with('\''))
387        || (s.starts_with('"') && s.ends_with('"'))
388    {
389        let quote = if s.starts_with('\'') { '\'' } else { '"' };
390        let content = s
391            .get(1..s.len().saturating_sub(1))
392            .expect("s starts and ends with quotes");
393        let mut result = String::new();
394        let mut chars = content.chars().peekable();
395        while let Some(c) = chars.next() {
396            if c == '\\' {
397                if let Some(&next_c) = chars.peek() {
398                    if quote == '\'' {
399                        if next_c == '\'' || next_c == '\\' {
400                            result.push(next_c);
401                            chars.next();
402                        } else {
403                            result.push('\\');
404                        }
405                    } else {
406                        match next_c {
407                            '"' => {
408                                result.push('"');
409                                chars.next();
410                            }
411                            '\\' => {
412                                result.push('\\');
413                                chars.next();
414                            }
415                            'n' => {
416                                result.push('\n');
417                                chars.next();
418                            }
419                            'r' => {
420                                result.push('\r');
421                                chars.next();
422                            }
423                            't' => {
424                                result.push('\t');
425                                chars.next();
426                            }
427                            _ => {
428                                result.push('\\');
429                            }
430                        }
431                    }
432                } else {
433                    result.push('\\');
434                }
435            } else {
436                result.push(c);
437            }
438        }
439        result
440    } else {
441        s.to_string()
442    }
443}
444
445fn generate_csv(pairs: &[(String, String)]) -> Vec<u8> {
446    let mut csv_data = Vec::new();
447    for (key, value) in pairs {
448        let key_escaped = escape_csv_field(key);
449        let val_escaped = escape_csv_field(value);
450        csv_data.extend_from_slice(key_escaped.as_bytes());
451        csv_data.push(b',');
452        csv_data.extend_from_slice(val_escaped.as_bytes());
453        csv_data.push(b'\n');
454    }
455    csv_data
456}
457
458fn escape_csv_field(field: &str) -> String {
459    let needs_quotes = field.contains(',')
460        || field.contains('"')
461        || field.contains('\n')
462        || field.contains('\r');
463    if needs_quotes {
464        let mut escaped = String::new();
465        escaped.push('"');
466        for c in field.chars() {
467            if c == '"' {
468                escaped.push_str("\"\"");
469            } else {
470                escaped.push(c);
471            }
472        }
473        escaped.push('"');
474        escaped
475    } else {
476        field.to_string()
477    }
478}
479
480#[cfg(test)]
481#[allow(
482    clippy::panic,
483    clippy::expect_used,
484    clippy::unwrap_used,
485    clippy::unwrap_in_result,
486    clippy::panic_in_result_fn,
487    clippy::indexing_slicing,
488    clippy::arithmetic_side_effects,
489    reason = "Standard repository test boilerplate"
490)]
491mod tests {
492    use super::*;
493
494    #[crate::ctb_test]
495    fn test_dceutils_parsing() {
496        let php_data = r#"<?php
497// Some comment
498$DcMap_test = array('00' => '0', '01' => '16', '02' => '15', '0A' => '');
499// Other comment
500$sequential = array('first', 'second', 'third', '  whitespace  ', 'escaped\'quote', "escaped\"double");
501?>"#;
502
503        let csvs = php_to_csvs(php_data.as_bytes()).unwrap();
504        assert_eq!(csvs.len(), 2);
505
506        let map_csv = &csvs["DcMap_test"];
507        let map_csv_str = std::str::from_utf8(map_csv).unwrap();
508        assert_eq!(map_csv_str, "00,0\n01,16\n02,15\n0A,\n");
509
510        let seq_csv = &csvs["sequential"];
511        let seq_csv_str = std::str::from_utf8(seq_csv).unwrap();
512        assert_eq!(
513            seq_csv_str,
514            "0,first\n1,second\n2,third\n3,  whitespace  \n4,escaped'quote\n5,\"escaped\"\"double\"\n"
515        );
516    }
517
518    #[crate::ctb_test]
519    fn test_dceutils_file_writing() {
520        let temp_dir = std::env::temp_dir();
521        let random_num = std::time::SystemTime::now()
522            .duration_since(std::time::UNIX_EPOCH)
523            .unwrap_or_default()
524            .as_nanos();
525        let php_filename = format!("test_data_{random_num}.php");
526        let php_path = temp_dir.join(&php_filename);
527
528        let php_content = r"<?php
529$my_test_array = array('a' => '1', 'b' => '2');
530?>";
531        std::fs::write(&php_path, php_content).unwrap();
532
533        let expected_csv_name = format!("{php_filename}-my_test_array.csv");
534        let expected_csv_path = std::path::Path::new(&expected_csv_name);
535
536        if expected_csv_path.exists() {
537            drop(std::fs::remove_file(expected_csv_path));
538        }
539
540        let res = php_file_to_csv_files(&php_path);
541        res.unwrap();
542
543        assert!(expected_csv_path.exists());
544        let csv_content = std::fs::read_to_string(expected_csv_path).unwrap();
545        assert_eq!(csv_content, "a,1\nb,2\n");
546
547        drop(std::fs::remove_file(expected_csv_path));
548        drop(std::fs::remove_file(&php_path));
549    }
550}