1pub const SKELETON_SCHEMA: u32 = 1;
10
11mod lex;
12mod parse;
13mod ph;
14
15use bilingua_model::*;
16
17const ID: &str = "php";
18const HIDDEN: &str = "$php";
21
22#[derive(Debug, Clone, PartialEq, Eq)]
24#[non_exhaustive]
25pub struct Record {
26 pub key: String,
28 pub value: String,
30 pub unit_index: usize,
32}
33
34pub 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 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
66fn 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
93pub 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
112fn 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
128fn 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
166fn 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 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 fn sniff(&self, bytes: &[u8]) -> bool {
249 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 if out.starts_with('\u{feff}') {
307 out.insert(0, '\u{feff}');
308 }
309 if !rewritten && opts.is_profile(bilingua_model::profile::LOCOS) {
310 return enc::encode_text(&out, encoding);
313 }
314 enc::encode_text_with(&out, encoding, opts)
315 }
316}