Skip to main content

bilingua_php/
lib.rs

1//! Bilingua filter for PHP array resource files: Laravel `lang/*.php` (`return [...]`), CodeIgniter 4 and CodeIgniter 3
2//! (`$lang['key'] = '...'`) language files. See the README.
3//!
4//! The file is tokenised, never executed. Every string value with a letter or digit is a unit, in source order; keys
5//! never. Code, comments, numbers and symbol strings stay in the skeleton byte for byte, and only the literal of a
6//! changed unit is rewritten, in the same quote style.
7
8/// Skeleton schema number: bump only when this crate's skeleton layout changes (see `bilingua_model::check_parser`).
9pub const SKELETON_SCHEMA: u32 = 1;
10
11mod lex;
12mod parse;
13mod ph;
14
15use bilingua_model::*;
16
17const ID: &str = "php";
18/// The one hidden code of a unit: `standalone` = the original literal (quotes included, a concatenation whole),
19/// `open` = the quote style (`'`, `"`, `h` heredoc, `n` nowdoc).
20const HIDDEN: &str = "$php";
21
22/// One translatable string as a key-based project sees it.
23#[derive(Debug, Clone, PartialEq, Eq)]
24#[non_exhaustive]
25pub struct Record {
26    /// Dotted key path (`nested.deep.title`; a `$lang` variable is dropped).
27    pub key: String,
28    /// The decoded value.
29    pub value: String,
30    /// Index of the unit.
31    pub unit_index: usize,
32}
33
34/// The PHP array resource filter.
35pub struct Php;
36
37struct Loaded {
38    text: String,
39    encoding: String,
40    warnings: Vec<Warning>,
41}
42
43fn load(bytes: &[u8], opts: &ExtractOptions, limits: &Limits) -> Result<Loaded, Error> {
44    guard::check_input(bytes, limits)?;
45    let dec = enc::decode_text(
46        bytes,
47        &enc::DecodeOptions::with_limits(*limits).with_source_lang(opts.source_lang.as_deref()),
48    )?;
49    if !matches!(
50        enc::base(&dec.encoding),
51        "utf-8" | "utf-8-bom" | "utf-16le" | "utf-16be"
52    ) && enc::encode_text(&dec.text, &dec.encoding)? != bytes
53    {
54        // double-mapped bytes of the CJK code pages read to the same character and write back as the other
55        // spelling; an untouched merge must be the original bytes, so the file is refused, never altered
56        return Err(Error::Encoding("This PHP file uses byte sequences of its legacy encoding that cannot be written back unchanged. Re-save the file as UTF-8.".into()));
57    }
58    budget(&dec.text, limits)?;
59    Ok(Loaded {
60        text: dec.text,
61        encoding: dec.encoding,
62        warnings: dec.warnings,
63    })
64}
65
66/// LocOS `_budget`: refuse a file with far more strings or values than the unit limit could ever allow, before lexing.
67fn budget(text: &str, limits: &Limits) -> Result<(), Error> {
68    let lim = limits.max_units;
69    let (mut quotes, mut values) = (0usize, 0usize);
70    for &b in text.as_bytes() {
71        match b {
72            b'\'' | b'"' => quotes += 1,
73            b',' | b'[' | b'(' => values += 1,
74            _ => {}
75        }
76    }
77    let over = |what: &str| -> Error {
78        LimitError::new(
79            LimitKind::Units,
80            format!("This PHP file has far more {what} than {lim} segments allow. Split it into smaller files."),
81        )
82        .into()
83    };
84    if quotes > lim.saturating_mul(40) {
85        return Err(over("strings"));
86    }
87    if values > lim.saturating_mul(20) {
88        return Err(over("values"));
89    }
90    Ok(())
91}
92
93/// Every translatable string with its dotted key, in order (the LocOS `records()` view).
94pub fn records(bytes: &[u8]) -> Result<Vec<Record>, Error> {
95    let opts = ExtractOptions::default();
96    let limits = opts.limits();
97    let l = load(bytes, &opts, &limits)?;
98    let parsed = parse::parse(&l.text, &limits)?;
99    Ok(parsed
100        .units
101        .iter()
102        .filter(|u| u.translatable)
103        .enumerate()
104        .map(|(i, u)| Record {
105            key: u.key.clone(),
106            value: u.value.clone(),
107            unit_index: i,
108        })
109        .collect())
110}
111
112/// The text a list of inline pieces writes (tags give back their original placeholder).
113fn out_text(u: &Unit, v: &[Inline]) -> String {
114    let mut s = String::new();
115    for i in v {
116        match i {
117            Inline::Text(t) => s.push_str(t),
118            Inline::Tag { id, .. } => {
119                if let Some(c) = u.codes.get(id).and_then(|c| c.standalone.as_deref()) {
120                    s.push_str(c);
121                }
122            }
123        }
124    }
125    s
126}
127
128/// The literal for `s`: double-quoted for a double-quoted original, single-quoted for everything else (LocOS).
129fn escape(s: &str, double: bool) -> String {
130    let mut out = String::with_capacity(s.len() + 2);
131    if double {
132        out.push('"');
133        for ch in s.chars() {
134            match ch {
135                '\\' | '"' | '$' => {
136                    out.push('\\');
137                    out.push(ch);
138                }
139                '\n' => out.push_str("\\n"),
140                '\r' => out.push_str("\\r"),
141                '\t' => out.push_str("\\t"),
142                c if (c as u32) < 0x20 || c as u32 == 0x7F => {
143                    out.push_str(&format!("\\x{:02x}", c as u32))
144                }
145                c => out.push(c),
146            }
147        }
148        out.push('"');
149    } else {
150        out.push('\'');
151        for ch in s.chars() {
152            if ch == '\\' || ch == '\'' {
153                out.push('\\');
154            }
155            out.push(ch);
156        }
157        out.push('\'');
158    }
159    out
160}
161
162fn hidden(u: &Unit) -> Option<&CodeData> {
163    u.codes.get(HIDDEN)
164}
165
166/// The literal to write for a unit: `None` when it is unchanged (the original literal stays).
167fn new_literal(u: &Unit) -> Option<String> {
168    if u.segments.iter().all(|s| !s.has_target()) {
169        return None;
170    }
171    let out = out_text(u, &u.output());
172    if out == out_text(u, &u.source()) {
173        return None;
174    }
175    let double = hidden(u)?.open.as_deref() == Some("\"");
176    Some(escape(&out, double))
177}
178
179impl Php {
180    /// `extract` with explicit size limits.
181    pub fn extract_with(
182        &self,
183        bytes: &[u8],
184        opts: &ExtractOptions,
185        limits: &Limits,
186    ) -> Result<Document, Error> {
187        let l = load(bytes, opts, limits)?;
188        let text = l.text.as_str();
189        let parsed = parse::parse(text, limits)?;
190        let mut parts: Vec<SkelPart> = Vec::new();
191        let mut units: Vec<Unit> = Vec::new();
192        let mut pos = 0usize;
193        let (mut line_pos, mut line) = (0usize, 1usize);
194        for ru in &parsed.units {
195            if !(ru.translatable || opts.include_locked) {
196                continue;
197            }
198            guard::check_unit_count(units.len() + 1, limits)?;
199            if ru.value.len() > limits.max_unit_chars {
200                guard::check_unit_chars(ru.value.chars().count(), limits)?;
201            }
202            if ru.start > pos {
203                parts.push(SkelPart::Raw(text[pos..ru.start].to_string()));
204            }
205            pos = ru.end;
206            line += text.as_bytes()[line_pos..ru.start]
207                .iter()
208                .filter(|&&b| b == b'\n')
209                .count();
210            line_pos = ru.start;
211            let (inl, codes) = ph::unit_inlines(&ru.value);
212            let mut u = Unit::new(format!("u{}", units.len() + 1), inl);
213            u.codes = codes;
214            u.codes.insert(
215                HIDDEN.into(),
216                CodeData::new().with_open(ru.quote.as_char().to_string()).with_standalone(text[ru.start..ru.end].to_string()),
217            );
218            u.context.kind = Some("string".into());
219            u.context.style = Some("php".into());
220            u.context.key = Some(ru.key.clone());
221            u.context.location = Some(format!("line {line}"));
222            u.translate = ru.translatable;
223            if !ru.translatable {
224                u.lock_reason = Some("no letter or digit".into());
225            }
226            parts.push(SkelPart::Unit(units.len()));
227            units.push(u);
228        }
229        if pos < text.len() {
230            parts.push(SkelPart::Raw(text[pos..].to_string()));
231        }
232        let doc = Document::new(ID, units, Skeleton::text(parts, l.encoding, bilingua_model::parser_info!())).with_options(opts);
233        guard::finish(doc, l.warnings, limits)
234    }
235}
236
237impl Filter for Php {
238    fn id(&self) -> &'static str {
239        ID
240    }
241
242    fn extensions(&self) -> &'static [&'static str] {
243        &["php"]
244    }
245
246    /// True when the whole file is a static PHP language file: it starts with `<?php`, parses, and holds at least one
247    /// `return` or assignment statement. Tight enough to be put anywhere in the filter list.
248    fn sniff(&self, bytes: &[u8]) -> bool {
249        // cheap exit for every other format: UTF-16 files are decoded, anything else must open with `<?php`
250        if !(bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF])) {
251            let b = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
252            let skip = b.iter().take_while(|c| c.is_ascii_whitespace()).count();
253            if !b[skip..].get(..5).is_some_and(|h| h.eq_ignore_ascii_case(b"<?php")) {
254                return false;
255            }
256        }
257        let opts = ExtractOptions::default();
258        let limits = opts.limits();
259        let Ok(l) = load(bytes, &opts, &limits) else {
260            return false;
261        };
262        parse::parse(&l.text, &limits).is_ok_and(|p| p.statements > 0)
263    }
264
265    fn extract(&self, bytes: &[u8], opts: &ExtractOptions) -> Result<Document, Error> {
266        bilingua_model::check_own_options(self, &opts.format_options)?;
267        self.extract_with(bytes, opts, &opts.limits())
268    }
269
270    fn merge_with(&self, doc: &Document, opts: &bilingua_model::MergeOptions) -> Result<Vec<u8>, Error> {
271        bilingua_model::check_own_options(self, &opts.format_options)?;
272        bilingua_model::check_parser(doc, &bilingua_model::parser_info!())?;
273        let Skeleton::Text {
274            parts, encoding, ..
275        } = &doc.skeleton
276        else {
277            return Err(Error::Write("php needs a text skeleton".into()));
278        };
279        let mut out = String::new();
280        let mut rewritten = false;
281        for p in parts {
282            match p {
283                SkelPart::Raw(s) => out.push_str(s),
284                SkelPart::Unit(i) => {
285                    let u = doc
286                        .units
287                        .get(*i)
288                        .ok_or_else(|| Error::Write(format!("skeleton points at missing unit {i}")))?;
289                    match new_literal(u) {
290                        Some(lit) => {
291                            rewritten = true;
292                            out.push_str(&lit)
293                        }
294                        None => out.push_str(
295                            hidden(u).and_then(|h| h.standalone.as_deref()).ok_or_else(
296                                || Error::Write(format!("unit {} lost its literal", u.id)),
297                            )?,
298                        ),
299                    }
300                }
301            }
302        }
303        // The decoder takes the byte order mark off and the encoder takes one leading U+FEFF off the text before it
304        // writes the mark back, so a U+FEFF that is file content (a file that starts with two marks) needs one more
305        // in front of it to survive an untouched merge.
306        if out.starts_with('\u{feff}') {
307            out.insert(0, '\u{feff}');
308        }
309        if !rewritten && opts.is_profile(bilingua_model::profile::LOCOS) {
310            // LocOS `PhpArrayFilter.build`: with no value rewritten the file comes back as it was (its own code page),
311            // a localized build included; only a rewritten file is written as UTF-8
312            return enc::encode_text(&out, encoding);
313        }
314        enc::encode_text_with(&out, encoding, opts)
315    }
316}