1use std::collections::{BTreeMap, BTreeSet};
12use std::sync::OnceLock;
13
14use awp_types::{
15 ContentId, ContentItem, ContentKind, ContentState, LanguageTag, Markdown, Redirect, Schedule,
16};
17use bytes::Bytes;
18use regex::Regex;
19use serde_json::Value;
20use url::Url;
21
22use super::error::Result;
23use super::inventory::{ItemStatus, SiteInventory, SourceKind};
24use super::sanitize::{DropReason, Dropped, Sanitiser, UrlUse};
25use crate::content::kind_directory;
26use crate::media::{MediaPipeline, MediaPolicy, MediaUpload};
27use crate::redirects::GONE_PAGE;
28
29pub const LEGACY_RUNTIME_PREFIXES: &[&str] = &[
32 "/wp-admin/",
33 "/wp-includes/",
34 "/wp-content/themes/",
35 "/wp-content/plugins/",
36 "/wp-content/cache/",
37 "/wp-content/mu-plugins/",
38 "/wp-json/",
39 "/cgi-bin/",
40];
41
42pub const WORDPRESS_ENDPOINTS: &[&str] = &[
45 "/wp-login.php",
46 "/xmlrpc.php",
47 "/wp-admin/",
48 "/wp-cron.php",
49 "/wp-comments-post.php",
50 "/wp-trackback.php",
51 "/wp-signup.php",
52 "/wp-activate.php",
53];
54
55pub fn legacy_runtime_path(path: &str) -> bool {
69 let path = path.split(['?', '#']).next().unwrap_or_default().to_ascii_lowercase();
70 LEGACY_RUNTIME_PREFIXES.iter().any(|prefix| path.starts_with(prefix))
71 || [".php", ".phtml", ".php5", ".asp", ".aspx", ".jsp", ".cgi"]
72 .iter()
73 .any(|extension| path.ends_with(extension))
74}
75
76fn read_paths(inventory: &SiteInventory) -> BTreeSet<String> {
78 let mut read: BTreeSet<String> = BTreeSet::from(["/".to_string()]);
79 read.extend(inventory.items.iter().map(|item| item.path.clone()));
80 read.extend(inventory.media.iter().map(|media| media.path.clone()));
81 read.extend(
82 inventory
83 .urls
84 .iter()
85 .filter(|url| matches!(url.status, 200..=299 | 301 | 302 | 303 | 307 | 308))
86 .map(|url| url.path.split('?').next().unwrap_or_default().to_string()),
87 );
88 read.extend(
89 inventory
90 .taxonomies
91 .iter()
92 .flat_map(|t| t.terms.iter().filter_map(|term| term.path.clone())),
93 );
94 read
95}
96
97fn was_read(read: &BTreeSet<String>, path: &str) -> bool {
100 let path = path.split(['?', '#']).next().unwrap_or_default();
101 let bare = path.strip_suffix("index.html").unwrap_or(path);
102 let slashed = if bare.ends_with('/') { bare.to_string() } else { format!("{bare}/") };
103 [path, bare, slashed.as_str(), slashed.trim_end_matches('/')]
104 .iter()
105 .any(|candidate| !candidate.is_empty() && read.contains(*candidate))
106}
107
108#[derive(Debug, Clone)]
110pub struct ConvertOptions {
111 pub language: LanguageTag,
113 pub sanitiser: Sanitiser,
115 pub excluded: BTreeSet<String>,
117 pub media: MediaPolicy,
119}
120
121impl ConvertOptions {
122 pub fn new(language: LanguageTag) -> Self {
124 Self {
125 language,
126 sanitiser: Sanitiser::new(),
127 excluded: BTreeSet::new(),
128 media: MediaPolicy::default(),
129 }
130 }
131
132 #[must_use]
134 pub fn excluding(mut self, keys: impl IntoIterator<Item = String>) -> Self {
135 self.excluded.extend(keys);
136 self
137 }
138}
139
140#[derive(Debug, Clone, Default)]
142pub struct Converted {
143 pub items: Vec<ContentItem>,
145 pub documents: BTreeMap<String, Bytes>,
148 pub redirects: Vec<Redirect>,
151 pub ids: BTreeMap<String, ContentId>,
153 pub paths: BTreeMap<String, String>,
155 pub dropped: BTreeMap<String, Vec<Dropped>>,
157 pub notes: Vec<String>,
159}
160
161fn tag_slug(text: &str) -> String {
163 let slug = slug_part(text);
164 if slug.is_empty() { "tag".into() } else { slug }
165}
166
167fn slug_part(text: &str) -> String {
168 let mut out = String::new();
169 for c in text.chars().flat_map(char::to_lowercase) {
170 if c.is_alphanumeric() {
171 out.push(c);
172 } else if !out.ends_with('-') && !out.is_empty() {
173 out.push('-');
174 }
175 }
176 out.trim_matches('-').to_string()
177}
178
179fn strip_shortcodes(content: &str) -> String {
182 static SHORTCODE: OnceLock<Regex> = OnceLock::new();
183 let shortcode = SHORTCODE.get_or_init(|| {
184 Regex::new(r#"\[/?[a-z][a-z0-9_-]*(?:\s+[^\]]*)?/?\]"#).expect("static regex")
185 });
186 shortcode.replace_all(content, "").into_owned()
187}
188
189fn keepable_path(path: &str) -> bool {
190 path.starts_with('/') && path.ends_with('/') && !path.contains("..") && !path.contains('?')
191}
192
193fn text_of(html: &str) -> String {
194 let document = scraper::Html::parse_fragment(html);
195 super::html::collapse(&document.root_element().text().collect::<String>())
196}
197
198pub fn to_content(inventory: &SiteInventory, options: &ConvertOptions) -> Result<Converted> {
224 let mut converted = Converted::default();
225 let origin = inventory.origin.as_deref().and_then(|o| Url::parse(o).ok());
226 let raw_content = inventory.source == SourceKind::Wxr;
227 let mut used: BTreeSet<(ContentKind, String, String)> = BTreeSet::new();
228 let read = matches!(inventory.source, SourceKind::Crawl | SourceKind::IsolatedReplay)
230 .then(|| read_paths(inventory));
231 let nav: BTreeMap<String, usize> = inventory
232 .menus
233 .first()
234 .map(|menu| {
235 menu.entries
236 .iter()
237 .enumerate()
238 .filter(|(_, e)| e.parent.is_none())
239 .map(|(i, e)| (e.target.clone(), i + 1))
240 .collect()
241 })
242 .unwrap_or_default();
243 for item in &inventory.items {
244 if options.excluded.contains(&item.key) {
245 converted.notes.push(format!("{} left out: excluded", item.key));
246 continue;
247 }
248 let primary = |tag: &str| tag.split('-').next().unwrap_or(tag).to_ascii_lowercase();
250 let language = item
251 .language
252 .as_deref()
253 .filter(|l| primary(l) != primary(options.language.as_str()))
254 .and_then(|l| l.parse::<LanguageTag>().ok())
255 .unwrap_or_else(|| options.language.clone());
256 let home = item.path == "/";
257 let mut slug = if home {
258 "index".to_string()
259 } else {
260 let base = if item.kind == ContentKind::Page {
261 item.path
262 .trim_matches('/')
263 .split('/')
264 .map(slug_part)
265 .filter(|s| !s.is_empty())
266 .collect::<Vec<_>>()
267 .join("/")
268 } else {
269 slug_part(&item.slug)
270 };
271 if base.is_empty() { slug_part(&item.title) } else { base }
272 };
273 if slug.is_empty() {
274 slug = slug_part(&item.key);
275 }
276 let mut unique = slug.clone();
277 let mut n = 2;
278 while !used.insert((item.kind, unique.clone(), language.to_string())) {
279 unique = format!("{slug}-{n}");
280 n += 1;
281 }
282 let slug = unique;
283 let id = ContentId(format!("{}/{slug}/{language}", kind_directory(item.kind)));
284 let mut fields: BTreeMap<String, Value> = BTreeMap::new();
285 fields.insert("title".into(), Value::String(item.title.clone()));
286 if let Some(excerpt) = item.excerpt.as_deref().map(text_of).filter(|e| !e.is_empty()) {
287 fields.insert("summary".into(), Value::String(excerpt));
288 }
289 let page_path = if home {
290 "/".to_string()
291 } else if keepable_path(&item.path) {
292 fields.insert("path".into(), Value::String(item.path.clone()));
293 item.path.clone()
294 } else {
295 let default = match item.kind {
296 ContentKind::Page | ContentKind::Collection => format!("/{slug}/"),
297 kind => format!("/{}/{slug}/", kind_directory(kind)),
298 };
299 if item.path.starts_with('/') && !item.path.contains('?') && item.path != default {
300 converted.redirects.push(Redirect {
301 from: item.path.clone(),
302 to: default.clone(),
303 status: 301,
304 });
305 }
306 default
307 };
308 if let Some(at) = item.published_at {
309 fields.insert("publishedAt".into(), Value::String(at.to_rfc3339()));
310 }
311 if let Some(at) = item.modified_at {
312 fields.insert("updatedAt".into(), Value::String(at.to_rfc3339()));
313 }
314 let mut tags: Vec<String> = item.categories.iter().chain(&item.tags).cloned().collect();
315 tags.retain(|t| !t.eq_ignore_ascii_case("uncategorized"));
316 tags.sort();
317 tags.dedup();
318 if !tags.is_empty() {
319 fields
320 .insert("tags".into(), Value::Array(tags.into_iter().map(Value::String).collect()));
321 }
322 if let Some(author) = &item.author {
323 fields.insert("byline".into(), Value::String(author.clone()));
324 }
325 for (key, value) in &item.fields {
326 fields.entry(key.clone()).or_insert_with(|| value.clone());
327 }
328 if let Some(order) = nav.get(&item.path) {
329 fields.insert("navOrder".into(), Value::from(*order as u64));
330 }
331 let page = origin.as_ref().and_then(|o| o.join(&item.path).ok());
332 let body_html = if raw_content { strip_shortcodes(&item.html) } else { item.html.clone() };
333 let mut unread: Vec<String> = Vec::new();
334 let site_origin = page.as_ref().map(super::http::origin_of);
335 let mut sanitised = options.sanitiser.sanitise_mapped(
336 &body_html,
337 page.as_ref(),
338 &mut |_: UrlUse, url: &Url| {
339 let Some(site_origin) = &site_origin else { return url.to_string() };
340 let path = super::html::site_path(url, site_origin);
341 if let Some(read) = &read
343 && path.starts_with('/')
344 && !was_read(read, &path)
345 {
346 unread.push(path);
347 return String::new();
348 }
349 path
350 },
351 );
352 for target in unread {
353 converted.notes.push(format!(
354 "{}: the link to {target} became text; the crawl could not read that page",
355 item.key
356 ));
357 sanitised.dropped.push(Dropped {
358 element: "a".into(),
359 reason: DropReason::UnreadTarget { target },
360 excerpt: String::new(),
361 });
362 }
363 if !sanitised.dropped.is_empty() {
364 converted.dropped.insert(item.key.clone(), sanitised.dropped.clone());
365 }
366 let (state, schedule) = match item.status {
367 ItemStatus::Published => (ContentState::Published, None),
368 ItemStatus::Scheduled => (
369 ContentState::Scheduled,
370 item.published_at
371 .map(|at| Schedule { publish_at: Some(at), ..Schedule::default() }),
372 ),
373 ItemStatus::Draft | ItemStatus::Pending | ItemStatus::Private => {
374 (ContentState::Draft, None)
375 }
376 };
377 let content = ContentItem {
378 id: id.clone(),
379 kind: item.kind,
380 slug,
381 language,
382 fields,
383 volatile: if item.kind == ContentKind::Product && item.fields.contains_key("stock") {
384 vec!["stock".into()]
385 } else {
386 Vec::new()
387 },
388 body: (!sanitised.markdown.trim().is_empty()).then_some(Markdown(sanitised.markdown)),
389 media: Vec::new(),
390 sources: Vec::new(),
391 schedule,
392 state,
393 };
394 converted.ids.insert(item.key.clone(), id);
395 converted.paths.insert(item.key.clone(), page_path);
396 converted.items.push(content);
397 }
398 converted.items.sort_by(|a, b| a.id.cmp(&b.id));
399 let pipeline = MediaPipeline::new(options.media.clone());
400 for media in &inventory.media {
401 if options.excluded.contains(&media.path) {
402 converted.notes.push(format!("{} left out: excluded", media.path));
403 continue;
404 }
405 let Some(bytes) = &media.bytes else {
406 converted.notes.push(format!("{} not copied: its bytes were not read", media.path));
407 continue;
408 };
409 if !media.path.starts_with('/') || media.path.contains("..") || media.path.ends_with('/') {
410 converted.notes.push(format!("{} not copied: not a file path", media.path));
411 continue;
412 }
413 let name = media.path.rsplit('/').next().unwrap_or(&media.path);
414 match pipeline.process(&MediaUpload {
415 name,
416 bytes,
417 alt: media.alt.clone(),
418 generated: false,
419 }) {
420 Ok(processed) => {
422 converted.documents.insert(media.path.clone(), processed.bytes);
423 }
424 Err(error) => converted.notes.push(format!("{} not copied: {error}", media.path)),
425 }
426 }
427 let listing =
428 if inventory.items.iter().any(|i| i.kind == ContentKind::Post) { "/posts/" } else { "/" };
429 let published_tags: BTreeSet<String> = converted
430 .items
431 .iter()
432 .filter(|i| i.state == ContentState::Published)
433 .filter_map(|i| i.fields.get("tags").and_then(Value::as_array))
434 .flatten()
435 .filter_map(Value::as_str)
436 .map(tag_slug)
437 .collect();
438 for taxonomy in &inventory.taxonomies {
439 for term in &taxonomy.terms {
440 let Some(path) = &term.path else { continue };
441 if keepable_path(path) {
442 let tag = tag_slug(&term.name);
443 let to = if published_tags.contains(&tag) {
444 format!("/tags/{tag}/")
445 } else {
446 listing.to_string()
447 };
448 converted.redirects.push(Redirect { from: path.clone(), to, status: 301 });
449 }
450 }
451 }
452 let origin_text = inventory.origin.clone().unwrap_or_default();
453 for url in &inventory.urls {
454 let Some(target) = &url.redirect_to else { continue };
455 if !matches!(url.status, 301 | 308) || url.path.contains('?') {
456 continue;
457 }
458 let to = target.strip_prefix(&origin_text).unwrap_or(target).to_string();
459 if to.starts_with('/') && to != url.path {
460 converted.redirects.push(Redirect { from: url.path.clone(), to, status: 301 });
461 }
462 }
463 let taxonomy_paths: BTreeSet<&String> = inventory
464 .taxonomies
465 .iter()
466 .flat_map(|t| t.terms.iter().filter_map(|term| term.path.as_ref()))
467 .collect();
468 for url in &inventory.urls {
469 if url.status != 200
472 || url.item.is_some()
473 || url.page.is_none()
474 || url.path == "/"
475 || url.path.contains('?')
476 || taxonomy_paths.contains(&url.path)
477 {
478 continue;
479 }
480 let to = if url.path.ends_with(".php") { "/" } else { listing };
481 converted.redirects.push(Redirect { from: url.path.clone(), to: to.into(), status: 301 });
482 }
483 if inventory.urls.iter().any(|u| u.path == "/feed/") {
484 converted.redirects.push(Redirect {
485 from: "/feed/".into(),
486 to: "/feed.xml".into(),
487 status: 301,
488 });
489 }
490 let wordpress = matches!(
493 inventory.source,
494 SourceKind::WordPressRest | SourceKind::Wxr | SourceKind::IsolatedReplay
495 ) || inventory.urls.iter().any(|url| url.path.contains("/wp-"));
496 let mut gone: BTreeSet<String> = inventory
497 .urls
498 .iter()
499 .map(|url| url.path.split('?').next().unwrap_or_default().to_string())
500 .filter(|path| legacy_runtime_path(path))
501 .collect();
502 if wordpress {
503 gone.extend(WORDPRESS_ENDPOINTS.iter().map(|path| (*path).to_string()));
504 }
505 for path in gone {
506 if converted.documents.contains_key(&path) || path.is_empty() {
507 continue;
508 }
509 converted.redirects.push(Redirect { from: path, to: GONE_PAGE.into(), status: 410 });
510 }
511 let kept: BTreeSet<&String> = converted.paths.values().collect();
512 let mut seen = BTreeSet::new();
513 converted.redirects.retain(|r| !kept.contains(&r.from) && seen.insert(r.from.clone()));
514 converted.redirects.sort_by(|a, b| a.from.cmp(&b.from));
515 tracing::info!(
516 items = converted.items.len(),
517 documents = converted.documents.len(),
518 redirects = converted.redirects.len(),
519 "inventory converted"
520 );
521 Ok(converted)
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527
528 #[test]
529 fn shortcodes_are_removed() {
530 assert_eq!(
531 strip_shortcodes(
532 "a [contact-form-7 id=\"1\" title=\"x\"] b [gallery/] [/caption] c [1]"
533 ),
534 "a b c [1]"
535 );
536 }
537
538 #[test]
539 fn slugs_are_url_safe() {
540 assert_eq!(slug_part("Hello, World!"), "hello-world");
541 assert_eq!(slug_part(" über Café "), "über-café");
542 assert_eq!(tag_slug("!!"), "tag");
543 }
544}