ctb_formats_dceutils/
legacy.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//! Legacy character encodings and fallback translation tables.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Result, bail};
30
31/// NOTE: In the original PHP version (both v1/1.43 and 2.51 legacy code), there is a bug where the `3_0a_old`
32/// case branch in `dce_convert` attempts to loop using a `$hex` variable that was never defined/initialized
33/// in that branch. This Rust implementation corrects this bug by properly initializing the hex string from data.
34pub fn onestep_3_0a_old_to_none(data: &[u8]) -> Result<Vec<u8>> {
35    let hex = bin2hex(data).to_lowercase();
36    if !hex.starts_with("444345650201") {
37        bail!("This document is not stored using a supported format.");
38    }
39    let tables = crate::tables::get_tables();
40    let mut txt = String::new();
41    let mut counter = 14_usize;
42    while counter < hex.len() {
43        let end_two = counter.saturating_add(2);
44        if end_two <= hex.len() {
45            if let Some(byte_hex) = hex.get(counter..end_two) {
46                if let Ok(val_dec) = usize::from_str_radix(byte_hex, 16) {
47                    if let Some(val) = tables.dce3_0a_core.get(val_dec) {
48                        txt.push_str(val);
49                    }
50                }
51            }
52        }
53        let end_four = counter.saturating_add(4);
54        if end_four <= hex.len() {
55            if let Some(four_hex) = hex.get(counter..end_four) {
56                if four_hex == "fd03" {
57                    break;
58                }
59            }
60        }
61        counter = counter.saturating_add(2);
62    }
63    Ok(txt.into_bytes())
64}
65
66/// Port of the legacy PHP `dce2txt` function.
67/// NOTE: The `dce2txt` function works correctly in PHP because it properly defines and
68/// initializes the `$hex` variable at the start, unlike the inline `3_0a_old` branch.
69pub fn dce2txt(data: &[u8]) -> String {
70    let hex = bin2hex(data).to_lowercase();
71    if !hex.starts_with("444345650201") {
72        return "This document is not stored using a supported format."
73            .to_string();
74    }
75    let ver = get_dce_version_1_43(data);
76    if ver == "3_0a" {
77        let tables = crate::tables::get_tables();
78        let mut txt = String::new();
79        let mut counter = 14_usize;
80        while counter < hex.len() {
81            let end_two = counter.saturating_add(2);
82            if end_two <= hex.len() {
83                if let Some(byte_hex) = hex.get(counter..end_two) {
84                    if let Ok(val_dec) = usize::from_str_radix(byte_hex, 16) {
85                        if let Some(val) = tables.dce3_0a_core.get(val_dec) {
86                            txt.push_str(val);
87                        }
88                    }
89                }
90            }
91            let end_four = counter.saturating_add(4);
92            if end_four <= hex.len() {
93                if let Some(four_hex) = hex.get(counter..end_four) {
94                    if four_hex == "fd03" {
95                        break;
96                    }
97                }
98            }
99            counter = counter.saturating_add(2);
100        }
101        txt
102    } else {
103        "This document is not stored using a supported version of DCE."
104            .to_string()
105    }
106}
107
108pub fn onestep_dce2txt_to_none(data: &[u8]) -> Result<Vec<u8>> {
109    // Replicates PHP `onestep_dce2txt_to_none` by calling the legacy `dce2txt` function.
110    Ok(dce2txt(data).into_bytes())
111}
112
113fn char_to_hex_val(b: u8) -> u8 {
114    match b {
115        b'0'..=b'9' => b.saturating_sub(b'0'),
116        b'a'..=b'f' => b.saturating_sub(b'a').saturating_add(10),
117        b'A'..=b'F' => b.saturating_sub(b'A').saturating_add(10),
118        _ => 0, // Invalid hex characters default to 0 in PHP
119    }
120}
121
122/// Port of the legacy PHP `dce2hex` function.
123/// NOTE: Replicates the low-nibble-first hex decoding behavior of `pack("h*", ...)` in PHP.
124pub fn dce2hex(hex_bytes: &[u8]) -> Vec<u8> {
125    let capacity = hex_bytes.len().saturating_add(1).saturating_div(2);
126    let mut bin = Vec::with_capacity(capacity);
127    let mut i = 0_usize;
128    while i < hex_bytes.len() {
129        // Reason for fallback: missing nibbles for odd-length hex strings default to 0, matching PHP's implementation.
130        let low = hex_bytes.get(i).copied().map_or(0, char_to_hex_val);
131        let next_idx = i.saturating_add(1);
132        let high = if next_idx < hex_bytes.len() {
133            // Reason for fallback: missing nibbles for odd-length hex strings default to 0, matching PHP's implementation.
134            hex_bytes.get(next_idx).copied().map_or(0, char_to_hex_val)
135        } else {
136            0
137        };
138        bin.push((high << 4) | low);
139        i = i.saturating_add(2);
140    }
141    bin
142}
143
144/// Port of the legacy PHP `hex2dce` function.
145/// NOTE: Replicates high-nibble-first / standard hex decoding of `pack("H*", ...)` in PHP.
146pub fn hex2dce(hex_bytes: &[u8]) -> Vec<u8> {
147    let capacity = hex_bytes.len().saturating_add(1).saturating_div(2);
148    let mut bin = Vec::with_capacity(capacity);
149    let mut i = 0_usize;
150    while i < hex_bytes.len() {
151        // Reason for fallback: missing nibbles for odd-length hex strings default to 0, matching PHP's implementation.
152        let high = hex_bytes.get(i).copied().map_or(0, char_to_hex_val);
153        let next_idx = i.saturating_add(1);
154        let low = if next_idx < hex_bytes.len() {
155            // Reason for fallback: missing nibbles for odd-length hex strings default to 0, matching PHP's implementation.
156            hex_bytes.get(next_idx).copied().map_or(0, char_to_hex_val)
157        } else {
158            0
159        };
160        bin.push((high << 4) | low);
161        i = i.saturating_add(2);
162    }
163    bin
164}
165
166pub fn onestep_dce2hex_to_none(data: &[u8]) -> Result<Vec<u8>> {
167    // Replicates PHP `onestep_dce2hex_to_none` by calling the legacy `dce2hex` function.
168    Ok(dce2hex(data))
169}
170
171pub fn onestep_hex2dce_to_none(data: &[u8]) -> Result<Vec<u8>> {
172    // Replicates PHP `onestep_hex2dce_to_none` by calling the legacy `hex2dce` function.
173    Ok(hex2dce(data))
174}
175
176/// Port of the legacy PHP `legacy_cdce_to_html_snippet` function.
177/// NOTE: Replicates PHP's `legacy_cdce_to_html_snippet`, replacing `@(\d+)@` patterns
178/// with formatting values from `tables.cdce_html_legacy`.
179pub fn legacy_cdce_to_html_snippet(content: &str) -> String {
180    let mut retval = content.to_string();
181    let tables = crate::tables::get_tables();
182
183    let bytes = content.as_bytes();
184    let mut i = 0_usize;
185    let mut matches = Vec::new();
186    while i < bytes.len() {
187        if bytes.get(i).copied() == Some(b'@') {
188            let mut j = i.saturating_add(1);
189            while j < bytes.len() {
190                if let Some(&b) = bytes.get(j) {
191                    if b.is_ascii_digit() {
192                        j = j.saturating_add(1);
193                        continue;
194                    }
195                }
196                break;
197            }
198            let next_i = i.saturating_add(1);
199            if j > next_i
200                && j < bytes.len()
201                && bytes.get(j).copied() == Some(b'@')
202            {
203                if let Some(num_str) = content.get(next_i..j) {
204                    matches.push(num_str.to_string());
205                }
206                i = j.saturating_add(1);
207                continue;
208            }
209        }
210        i = i.saturating_add(1);
211    }
212
213    for num in matches {
214        let pattern = format!("@{num}@");
215        if let Some(match_html) = tables.cdce_html_legacy.get(&num) {
216            retval = retval.replace(&pattern, match_html);
217        }
218    }
219
220    retval
221}
222
223pub fn onestep_legacy_cdce_to_html_snippet_l(data: &[u8]) -> Result<Vec<u8>> {
224    // Replicates PHP `onestep_legacy_cdce_to_html_snippet_l`.
225    let content = String::from_utf8_lossy(data);
226    let snippet = legacy_cdce_to_html_snippet(&content);
227    Ok(snippet.into_bytes())
228}
229
230pub fn onestep_legacy_cdce_to_html_l(data: &[u8]) -> Result<Vec<u8>> {
231    // Replicates PHP `onestep_legacy_cdce_to_html_l` by adding standard HTML tags around the snippet.
232    let content = String::from_utf8_lossy(data);
233    let html_opening = "<html><head><title></title></head><body>";
234    let html_closing = "</body></html>";
235    let snippet = legacy_cdce_to_html_snippet(&content);
236    let full_html = format!("{html_opening}{snippet}{html_closing}");
237    Ok(full_html.into_bytes())
238}
239
240pub fn dce_convert_1_43(
241    data: &[u8],
242    input_format: &str,
243    output_format: &str,
244) -> Result<Vec<u8>> {
245    // NOTE: Replicates PHP `dce_convert_1_43` function by forwarding to modern `crate::dce_convert`.
246    // In PHP, `dce_convert_1_43` compiles to the same core conversions (first to Dc list, then to output)
247    // as modern `dce_convert`, but is updated to hook into the new log management.
248    crate::dce_convert(data, input_format, output_format)
249}
250
251pub fn get_dce_version_1_43(data: &[u8]) -> String {
252    // NOTE: Replicates the PHP `get_dce_version_1_43` logic. It matches version byte 1 as '3_0a'
253    // and version byte 2 as '3_01a', otherwise returning a version error string.
254    let hex = bin2hex(data).to_lowercase();
255    if !hex.starts_with("444345650201") {
256        return "This document is not stored using a supported format."
257            .to_string();
258    }
259    if hex.len() < 14 {
260        return "This document is not stored using a supported version of DCE."
261            .to_string();
262    }
263    if let Some(ver_bytes) = hex.get(12..14) {
264        match ver_bytes {
265            "01" => "3_0a".to_string(),
266            "02" => "3_01a".to_string(),
267            _ => {
268                "This document is not stored using a supported version of DCE."
269                    .to_string()
270            }
271        }
272    } else {
273        "This document is not stored using a supported version of DCE."
274            .to_string()
275    }
276}