base.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. """
  2. Base validator with common validation logic for document files.
  3. """
  4. import re
  5. from pathlib import Path
  6. import defusedxml.minidom
  7. import lxml.etree
  8. class BaseSchemaValidator:
  9. IGNORED_VALIDATION_ERRORS = [
  10. "hyphenationZone",
  11. "purl.org/dc/terms",
  12. ]
  13. UNIQUE_ID_REQUIREMENTS = {
  14. "comment": ("id", "file"),
  15. "commentrangestart": ("id", "file"),
  16. "commentrangeend": ("id", "file"),
  17. "bookmarkstart": ("id", "file"),
  18. "bookmarkend": ("id", "file"),
  19. "sldid": ("id", "file"),
  20. "sldmasterid": ("id", "global"),
  21. "sldlayoutid": ("id", "global"),
  22. "cm": ("authorid", "file"),
  23. "sheet": ("sheetid", "file"),
  24. "definedname": ("id", "file"),
  25. "cxnsp": ("id", "file"),
  26. "sp": ("id", "file"),
  27. "pic": ("id", "file"),
  28. "grpsp": ("id", "file"),
  29. }
  30. EXCLUDED_ID_CONTAINERS = {
  31. "sectionlst",
  32. }
  33. ELEMENT_RELATIONSHIP_TYPES = {}
  34. SCHEMA_MAPPINGS = {
  35. "word": "ISO-IEC29500-4_2016/wml.xsd",
  36. "ppt": "ISO-IEC29500-4_2016/pml.xsd",
  37. "xl": "ISO-IEC29500-4_2016/sml.xsd",
  38. "[Content_Types].xml": "ecma/fouth-edition/opc-contentTypes.xsd",
  39. "app.xml": "ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd",
  40. "core.xml": "ecma/fouth-edition/opc-coreProperties.xsd",
  41. "custom.xml": "ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd",
  42. ".rels": "ecma/fouth-edition/opc-relationships.xsd",
  43. "people.xml": "microsoft/wml-2012.xsd",
  44. "commentsIds.xml": "microsoft/wml-cid-2016.xsd",
  45. "commentsExtensible.xml": "microsoft/wml-cex-2018.xsd",
  46. "commentsExtended.xml": "microsoft/wml-2012.xsd",
  47. "chart": "ISO-IEC29500-4_2016/dml-chart.xsd",
  48. "theme": "ISO-IEC29500-4_2016/dml-main.xsd",
  49. "drawing": "ISO-IEC29500-4_2016/dml-main.xsd",
  50. }
  51. MC_NAMESPACE = "http://schemas.openxmlformats.org/markup-compatibility/2006"
  52. XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"
  53. PACKAGE_RELATIONSHIPS_NAMESPACE = (
  54. "http://schemas.openxmlformats.org/package/2006/relationships"
  55. )
  56. OFFICE_RELATIONSHIPS_NAMESPACE = (
  57. "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
  58. )
  59. CONTENT_TYPES_NAMESPACE = (
  60. "http://schemas.openxmlformats.org/package/2006/content-types"
  61. )
  62. MAIN_CONTENT_FOLDERS = {"word", "ppt", "xl"}
  63. OOXML_NAMESPACES = {
  64. "http://schemas.openxmlformats.org/officeDocument/2006/math",
  65. "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
  66. "http://schemas.openxmlformats.org/schemaLibrary/2006/main",
  67. "http://schemas.openxmlformats.org/drawingml/2006/main",
  68. "http://schemas.openxmlformats.org/drawingml/2006/chart",
  69. "http://schemas.openxmlformats.org/drawingml/2006/chartDrawing",
  70. "http://schemas.openxmlformats.org/drawingml/2006/diagram",
  71. "http://schemas.openxmlformats.org/drawingml/2006/picture",
  72. "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",
  73. "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
  74. "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
  75. "http://schemas.openxmlformats.org/presentationml/2006/main",
  76. "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
  77. "http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes",
  78. "http://www.w3.org/XML/1998/namespace",
  79. }
  80. def __init__(self, unpacked_dir, original_file=None, verbose=False):
  81. self.unpacked_dir = Path(unpacked_dir).resolve()
  82. self.original_file = Path(original_file) if original_file else None
  83. self.verbose = verbose
  84. self.schemas_dir = Path(__file__).parent.parent / "schemas"
  85. patterns = ["*.xml", "*.rels"]
  86. self.xml_files = [
  87. f for pattern in patterns for f in self.unpacked_dir.rglob(pattern)
  88. ]
  89. if not self.xml_files:
  90. print(f"Warning: No XML files found in {self.unpacked_dir}")
  91. def validate(self):
  92. raise NotImplementedError("Subclasses must implement the validate method")
  93. def repair(self) -> int:
  94. return self.repair_whitespace_preservation()
  95. def repair_whitespace_preservation(self) -> int:
  96. repairs = 0
  97. for xml_file in self.xml_files:
  98. try:
  99. content = xml_file.read_text(encoding="utf-8")
  100. dom = defusedxml.minidom.parseString(content)
  101. modified = False
  102. for elem in dom.getElementsByTagName("*"):
  103. if elem.tagName.endswith(":t") and elem.firstChild:
  104. text = elem.firstChild.nodeValue
  105. if text and (text.startswith((' ', '\t')) or text.endswith((' ', '\t'))):
  106. if elem.getAttribute("xml:space") != "preserve":
  107. elem.setAttribute("xml:space", "preserve")
  108. text_preview = repr(text[:30]) + "..." if len(text) > 30 else repr(text)
  109. print(f" Repaired: {xml_file.name}: Added xml:space='preserve' to {elem.tagName}: {text_preview}")
  110. repairs += 1
  111. modified = True
  112. if modified:
  113. xml_file.write_bytes(dom.toxml(encoding="UTF-8"))
  114. except Exception:
  115. pass
  116. return repairs
  117. def validate_xml(self):
  118. errors = []
  119. for xml_file in self.xml_files:
  120. try:
  121. lxml.etree.parse(str(xml_file))
  122. except lxml.etree.XMLSyntaxError as e:
  123. errors.append(
  124. f" {xml_file.relative_to(self.unpacked_dir)}: "
  125. f"Line {e.lineno}: {e.msg}"
  126. )
  127. except Exception as e:
  128. errors.append(
  129. f" {xml_file.relative_to(self.unpacked_dir)}: "
  130. f"Unexpected error: {str(e)}"
  131. )
  132. if errors:
  133. print(f"FAILED - Found {len(errors)} XML violations:")
  134. for error in errors:
  135. print(error)
  136. return False
  137. else:
  138. if self.verbose:
  139. print("PASSED - All XML files are well-formed")
  140. return True
  141. def validate_namespaces(self):
  142. errors = []
  143. for xml_file in self.xml_files:
  144. try:
  145. root = lxml.etree.parse(str(xml_file)).getroot()
  146. declared = set(root.nsmap.keys()) - {None}
  147. for attr_val in [
  148. v for k, v in root.attrib.items() if k.endswith("Ignorable")
  149. ]:
  150. undeclared = set(attr_val.split()) - declared
  151. errors.extend(
  152. f" {xml_file.relative_to(self.unpacked_dir)}: "
  153. f"Namespace '{ns}' in Ignorable but not declared"
  154. for ns in undeclared
  155. )
  156. except lxml.etree.XMLSyntaxError:
  157. continue
  158. if errors:
  159. print(f"FAILED - {len(errors)} namespace issues:")
  160. for error in errors:
  161. print(error)
  162. return False
  163. if self.verbose:
  164. print("PASSED - All namespace prefixes properly declared")
  165. return True
  166. def validate_unique_ids(self):
  167. errors = []
  168. global_ids = {}
  169. for xml_file in self.xml_files:
  170. try:
  171. root = lxml.etree.parse(str(xml_file)).getroot()
  172. file_ids = {}
  173. mc_elements = root.xpath(
  174. ".//mc:AlternateContent", namespaces={"mc": self.MC_NAMESPACE}
  175. )
  176. for elem in mc_elements:
  177. elem.getparent().remove(elem)
  178. for elem in root.iter():
  179. tag = (
  180. elem.tag.split("}")[-1].lower()
  181. if "}" in elem.tag
  182. else elem.tag.lower()
  183. )
  184. if tag in self.UNIQUE_ID_REQUIREMENTS:
  185. in_excluded_container = any(
  186. ancestor.tag.split("}")[-1].lower() in self.EXCLUDED_ID_CONTAINERS
  187. for ancestor in elem.iterancestors()
  188. )
  189. if in_excluded_container:
  190. continue
  191. attr_name, scope = self.UNIQUE_ID_REQUIREMENTS[tag]
  192. id_value = None
  193. for attr, value in elem.attrib.items():
  194. attr_local = (
  195. attr.split("}")[-1].lower()
  196. if "}" in attr
  197. else attr.lower()
  198. )
  199. if attr_local == attr_name:
  200. id_value = value
  201. break
  202. if id_value is not None:
  203. if scope == "global":
  204. if id_value in global_ids:
  205. prev_file, prev_line, prev_tag = global_ids[
  206. id_value
  207. ]
  208. errors.append(
  209. f" {xml_file.relative_to(self.unpacked_dir)}: "
  210. f"Line {elem.sourceline}: Global ID '{id_value}' in <{tag}> "
  211. f"already used in {prev_file} at line {prev_line} in <{prev_tag}>"
  212. )
  213. else:
  214. global_ids[id_value] = (
  215. xml_file.relative_to(self.unpacked_dir),
  216. elem.sourceline,
  217. tag,
  218. )
  219. elif scope == "file":
  220. key = (tag, attr_name)
  221. if key not in file_ids:
  222. file_ids[key] = {}
  223. if id_value in file_ids[key]:
  224. prev_line = file_ids[key][id_value]
  225. errors.append(
  226. f" {xml_file.relative_to(self.unpacked_dir)}: "
  227. f"Line {elem.sourceline}: Duplicate {attr_name}='{id_value}' in <{tag}> "
  228. f"(first occurrence at line {prev_line})"
  229. )
  230. else:
  231. file_ids[key][id_value] = elem.sourceline
  232. except (lxml.etree.XMLSyntaxError, Exception) as e:
  233. errors.append(
  234. f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}"
  235. )
  236. if errors:
  237. print(f"FAILED - Found {len(errors)} ID uniqueness violations:")
  238. for error in errors:
  239. print(error)
  240. return False
  241. else:
  242. if self.verbose:
  243. print("PASSED - All required IDs are unique")
  244. return True
  245. def validate_file_references(self):
  246. errors = []
  247. rels_files = list(self.unpacked_dir.rglob("*.rels"))
  248. if not rels_files:
  249. if self.verbose:
  250. print("PASSED - No .rels files found")
  251. return True
  252. all_files = []
  253. for file_path in self.unpacked_dir.rglob("*"):
  254. if (
  255. file_path.is_file()
  256. and file_path.name != "[Content_Types].xml"
  257. and not file_path.name.endswith(".rels")
  258. ):
  259. all_files.append(file_path.resolve())
  260. all_referenced_files = set()
  261. if self.verbose:
  262. print(
  263. f"Found {len(rels_files)} .rels files and {len(all_files)} target files"
  264. )
  265. for rels_file in rels_files:
  266. try:
  267. rels_root = lxml.etree.parse(str(rels_file)).getroot()
  268. rels_dir = rels_file.parent
  269. referenced_files = set()
  270. broken_refs = []
  271. for rel in rels_root.findall(
  272. ".//ns:Relationship",
  273. namespaces={"ns": self.PACKAGE_RELATIONSHIPS_NAMESPACE},
  274. ):
  275. target = rel.get("Target")
  276. if target and not target.startswith(
  277. ("http", "mailto:")
  278. ):
  279. if target.startswith("/"):
  280. target_path = self.unpacked_dir / target.lstrip("/")
  281. elif rels_file.name == ".rels":
  282. target_path = self.unpacked_dir / target
  283. else:
  284. base_dir = rels_dir.parent
  285. target_path = base_dir / target
  286. try:
  287. target_path = target_path.resolve()
  288. if target_path.exists() and target_path.is_file():
  289. referenced_files.add(target_path)
  290. all_referenced_files.add(target_path)
  291. else:
  292. broken_refs.append((target, rel.sourceline))
  293. except (OSError, ValueError):
  294. broken_refs.append((target, rel.sourceline))
  295. if broken_refs:
  296. rel_path = rels_file.relative_to(self.unpacked_dir)
  297. for broken_ref, line_num in broken_refs:
  298. errors.append(
  299. f" {rel_path}: Line {line_num}: Broken reference to {broken_ref}"
  300. )
  301. except Exception as e:
  302. rel_path = rels_file.relative_to(self.unpacked_dir)
  303. errors.append(f" Error parsing {rel_path}: {e}")
  304. unreferenced_files = set(all_files) - all_referenced_files
  305. if unreferenced_files:
  306. for unref_file in sorted(unreferenced_files):
  307. unref_rel_path = unref_file.relative_to(self.unpacked_dir)
  308. errors.append(f" Unreferenced file: {unref_rel_path}")
  309. if errors:
  310. print(f"FAILED - Found {len(errors)} relationship validation errors:")
  311. for error in errors:
  312. print(error)
  313. print(
  314. "CRITICAL: These errors will cause the document to appear corrupt. "
  315. + "Broken references MUST be fixed, "
  316. + "and unreferenced files MUST be referenced or removed."
  317. )
  318. return False
  319. else:
  320. if self.verbose:
  321. print(
  322. "PASSED - All references are valid and all files are properly referenced"
  323. )
  324. return True
  325. def validate_all_relationship_ids(self):
  326. import lxml.etree
  327. errors = []
  328. for xml_file in self.xml_files:
  329. if xml_file.suffix == ".rels":
  330. continue
  331. rels_dir = xml_file.parent / "_rels"
  332. rels_file = rels_dir / f"{xml_file.name}.rels"
  333. if not rels_file.exists():
  334. continue
  335. try:
  336. rels_root = lxml.etree.parse(str(rels_file)).getroot()
  337. rid_to_type = {}
  338. for rel in rels_root.findall(
  339. f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship"
  340. ):
  341. rid = rel.get("Id")
  342. rel_type = rel.get("Type", "")
  343. if rid:
  344. if rid in rid_to_type:
  345. rels_rel_path = rels_file.relative_to(self.unpacked_dir)
  346. errors.append(
  347. f" {rels_rel_path}: Line {rel.sourceline}: "
  348. f"Duplicate relationship ID '{rid}' (IDs must be unique)"
  349. )
  350. type_name = (
  351. rel_type.split("/")[-1] if "/" in rel_type else rel_type
  352. )
  353. rid_to_type[rid] = type_name
  354. xml_root = lxml.etree.parse(str(xml_file)).getroot()
  355. r_ns = self.OFFICE_RELATIONSHIPS_NAMESPACE
  356. rid_attrs_to_check = ["id", "embed", "link"]
  357. for elem in xml_root.iter():
  358. for attr_name in rid_attrs_to_check:
  359. rid_attr = elem.get(f"{{{r_ns}}}{attr_name}")
  360. if not rid_attr:
  361. continue
  362. xml_rel_path = xml_file.relative_to(self.unpacked_dir)
  363. elem_name = (
  364. elem.tag.split("}")[-1] if "}" in elem.tag else elem.tag
  365. )
  366. if rid_attr not in rid_to_type:
  367. errors.append(
  368. f" {xml_rel_path}: Line {elem.sourceline}: "
  369. f"<{elem_name}> r:{attr_name} references non-existent relationship '{rid_attr}' "
  370. f"(valid IDs: {', '.join(sorted(rid_to_type.keys())[:5])}{'...' if len(rid_to_type) > 5 else ''})"
  371. )
  372. elif attr_name == "id" and self.ELEMENT_RELATIONSHIP_TYPES:
  373. expected_type = self._get_expected_relationship_type(
  374. elem_name
  375. )
  376. if expected_type:
  377. actual_type = rid_to_type[rid_attr]
  378. if expected_type not in actual_type.lower():
  379. errors.append(
  380. f" {xml_rel_path}: Line {elem.sourceline}: "
  381. f"<{elem_name}> references '{rid_attr}' which points to '{actual_type}' "
  382. f"but should point to a '{expected_type}' relationship"
  383. )
  384. except Exception as e:
  385. xml_rel_path = xml_file.relative_to(self.unpacked_dir)
  386. errors.append(f" Error processing {xml_rel_path}: {e}")
  387. if errors:
  388. print(f"FAILED - Found {len(errors)} relationship ID reference errors:")
  389. for error in errors:
  390. print(error)
  391. print("\nThese ID mismatches will cause the document to appear corrupt!")
  392. return False
  393. else:
  394. if self.verbose:
  395. print("PASSED - All relationship ID references are valid")
  396. return True
  397. def _get_expected_relationship_type(self, element_name):
  398. elem_lower = element_name.lower()
  399. if elem_lower in self.ELEMENT_RELATIONSHIP_TYPES:
  400. return self.ELEMENT_RELATIONSHIP_TYPES[elem_lower]
  401. if elem_lower.endswith("id") and len(elem_lower) > 2:
  402. prefix = elem_lower[:-2]
  403. if prefix.endswith("master"):
  404. return prefix.lower()
  405. elif prefix.endswith("layout"):
  406. return prefix.lower()
  407. else:
  408. if prefix == "sld":
  409. return "slide"
  410. return prefix.lower()
  411. if elem_lower.endswith("reference") and len(elem_lower) > 9:
  412. prefix = elem_lower[:-9]
  413. return prefix.lower()
  414. return None
  415. def validate_content_types(self):
  416. errors = []
  417. content_types_file = self.unpacked_dir / "[Content_Types].xml"
  418. if not content_types_file.exists():
  419. print("FAILED - [Content_Types].xml file not found")
  420. return False
  421. try:
  422. root = lxml.etree.parse(str(content_types_file)).getroot()
  423. declared_parts = set()
  424. declared_extensions = set()
  425. for override in root.findall(
  426. f".//{{{self.CONTENT_TYPES_NAMESPACE}}}Override"
  427. ):
  428. part_name = override.get("PartName")
  429. if part_name is not None:
  430. declared_parts.add(part_name.lstrip("/"))
  431. for default in root.findall(
  432. f".//{{{self.CONTENT_TYPES_NAMESPACE}}}Default"
  433. ):
  434. extension = default.get("Extension")
  435. if extension is not None:
  436. declared_extensions.add(extension.lower())
  437. declarable_roots = {
  438. "sld",
  439. "sldLayout",
  440. "sldMaster",
  441. "presentation",
  442. "document",
  443. "workbook",
  444. "worksheet",
  445. "theme",
  446. }
  447. media_extensions = {
  448. "png": "image/png",
  449. "jpg": "image/jpeg",
  450. "jpeg": "image/jpeg",
  451. "gif": "image/gif",
  452. "bmp": "image/bmp",
  453. "tiff": "image/tiff",
  454. "wmf": "image/x-wmf",
  455. "emf": "image/x-emf",
  456. }
  457. all_files = list(self.unpacked_dir.rglob("*"))
  458. all_files = [f for f in all_files if f.is_file()]
  459. for xml_file in self.xml_files:
  460. path_str = str(xml_file.relative_to(self.unpacked_dir)).replace(
  461. "\\", "/"
  462. )
  463. if any(
  464. skip in path_str
  465. for skip in [".rels", "[Content_Types]", "docProps/", "_rels/"]
  466. ):
  467. continue
  468. try:
  469. root_tag = lxml.etree.parse(str(xml_file)).getroot().tag
  470. root_name = root_tag.split("}")[-1] if "}" in root_tag else root_tag
  471. if root_name in declarable_roots and path_str not in declared_parts:
  472. errors.append(
  473. f" {path_str}: File with <{root_name}> root not declared in [Content_Types].xml"
  474. )
  475. except Exception:
  476. continue
  477. for file_path in all_files:
  478. if file_path.suffix.lower() in {".xml", ".rels"}:
  479. continue
  480. if file_path.name == "[Content_Types].xml":
  481. continue
  482. if "_rels" in file_path.parts or "docProps" in file_path.parts:
  483. continue
  484. extension = file_path.suffix.lstrip(".").lower()
  485. if extension and extension not in declared_extensions:
  486. if extension in media_extensions:
  487. relative_path = file_path.relative_to(self.unpacked_dir)
  488. errors.append(
  489. f' {relative_path}: File with extension \'{extension}\' not declared in [Content_Types].xml - should add: <Default Extension="{extension}" ContentType="{media_extensions[extension]}"/>'
  490. )
  491. except Exception as e:
  492. errors.append(f" Error parsing [Content_Types].xml: {e}")
  493. if errors:
  494. print(f"FAILED - Found {len(errors)} content type declaration errors:")
  495. for error in errors:
  496. print(error)
  497. return False
  498. else:
  499. if self.verbose:
  500. print(
  501. "PASSED - All content files are properly declared in [Content_Types].xml"
  502. )
  503. return True
  504. def validate_file_against_xsd(self, xml_file, verbose=False):
  505. xml_file = Path(xml_file).resolve()
  506. unpacked_dir = self.unpacked_dir.resolve()
  507. is_valid, current_errors = self._validate_single_file_xsd(
  508. xml_file, unpacked_dir
  509. )
  510. if is_valid is None:
  511. return None, set()
  512. elif is_valid:
  513. return True, set()
  514. original_errors = self._get_original_file_errors(xml_file)
  515. assert current_errors is not None
  516. new_errors = current_errors - original_errors
  517. new_errors = {
  518. e for e in new_errors
  519. if not any(pattern in e for pattern in self.IGNORED_VALIDATION_ERRORS)
  520. }
  521. if new_errors:
  522. if verbose:
  523. relative_path = xml_file.relative_to(unpacked_dir)
  524. print(f"FAILED - {relative_path}: {len(new_errors)} new error(s)")
  525. for error in list(new_errors)[:3]:
  526. truncated = error[:250] + "..." if len(error) > 250 else error
  527. print(f" - {truncated}")
  528. return False, new_errors
  529. else:
  530. if verbose:
  531. print(
  532. f"PASSED - No new errors (original had {len(current_errors)} errors)"
  533. )
  534. return True, set()
  535. def validate_against_xsd(self):
  536. new_errors = []
  537. original_error_count = 0
  538. valid_count = 0
  539. skipped_count = 0
  540. for xml_file in self.xml_files:
  541. relative_path = str(xml_file.relative_to(self.unpacked_dir))
  542. is_valid, new_file_errors = self.validate_file_against_xsd(
  543. xml_file, verbose=False
  544. )
  545. if is_valid is None:
  546. skipped_count += 1
  547. continue
  548. elif is_valid and not new_file_errors:
  549. valid_count += 1
  550. continue
  551. elif is_valid:
  552. original_error_count += 1
  553. valid_count += 1
  554. continue
  555. new_errors.append(f" {relative_path}: {len(new_file_errors)} new error(s)")
  556. for error in list(new_file_errors)[:3]:
  557. new_errors.append(
  558. f" - {error[:250]}..." if len(error) > 250 else f" - {error}"
  559. )
  560. if self.verbose:
  561. print(f"Validated {len(self.xml_files)} files:")
  562. print(f" - Valid: {valid_count}")
  563. print(f" - Skipped (no schema): {skipped_count}")
  564. if original_error_count:
  565. print(f" - With original errors (ignored): {original_error_count}")
  566. print(
  567. f" - With NEW errors: {len(new_errors) > 0 and len([e for e in new_errors if not e.startswith(' ')]) or 0}"
  568. )
  569. if new_errors:
  570. print("\nFAILED - Found NEW validation errors:")
  571. for error in new_errors:
  572. print(error)
  573. return False
  574. else:
  575. if self.verbose:
  576. print("\nPASSED - No new XSD validation errors introduced")
  577. return True
  578. def _get_schema_path(self, xml_file):
  579. if xml_file.name in self.SCHEMA_MAPPINGS:
  580. return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.name]
  581. if xml_file.suffix == ".rels":
  582. return self.schemas_dir / self.SCHEMA_MAPPINGS[".rels"]
  583. if "charts/" in str(xml_file) and xml_file.name.startswith("chart"):
  584. return self.schemas_dir / self.SCHEMA_MAPPINGS["chart"]
  585. if "theme/" in str(xml_file) and xml_file.name.startswith("theme"):
  586. return self.schemas_dir / self.SCHEMA_MAPPINGS["theme"]
  587. if xml_file.parent.name in self.MAIN_CONTENT_FOLDERS:
  588. return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.parent.name]
  589. return None
  590. def _clean_ignorable_namespaces(self, xml_doc):
  591. xml_string = lxml.etree.tostring(xml_doc, encoding="unicode")
  592. xml_copy = lxml.etree.fromstring(xml_string)
  593. for elem in xml_copy.iter():
  594. attrs_to_remove = []
  595. for attr in elem.attrib:
  596. if "{" in attr:
  597. ns = attr.split("}")[0][1:]
  598. if ns not in self.OOXML_NAMESPACES:
  599. attrs_to_remove.append(attr)
  600. for attr in attrs_to_remove:
  601. del elem.attrib[attr]
  602. self._remove_ignorable_elements(xml_copy)
  603. return lxml.etree.ElementTree(xml_copy)
  604. def _remove_ignorable_elements(self, root):
  605. elements_to_remove = []
  606. for elem in list(root):
  607. if not hasattr(elem, "tag") or callable(elem.tag):
  608. continue
  609. tag_str = str(elem.tag)
  610. if tag_str.startswith("{"):
  611. ns = tag_str.split("}")[0][1:]
  612. if ns not in self.OOXML_NAMESPACES:
  613. elements_to_remove.append(elem)
  614. continue
  615. self._remove_ignorable_elements(elem)
  616. for elem in elements_to_remove:
  617. root.remove(elem)
  618. def _preprocess_for_mc_ignorable(self, xml_doc):
  619. root = xml_doc.getroot()
  620. if f"{{{self.MC_NAMESPACE}}}Ignorable" in root.attrib:
  621. del root.attrib[f"{{{self.MC_NAMESPACE}}}Ignorable"]
  622. return xml_doc
  623. def _validate_single_file_xsd(self, xml_file, base_path):
  624. schema_path = self._get_schema_path(xml_file)
  625. if not schema_path:
  626. return None, None
  627. try:
  628. with open(schema_path, "rb") as xsd_file:
  629. parser = lxml.etree.XMLParser()
  630. xsd_doc = lxml.etree.parse(
  631. xsd_file, parser=parser, base_url=str(schema_path)
  632. )
  633. schema = lxml.etree.XMLSchema(xsd_doc)
  634. with open(xml_file, "r") as f:
  635. xml_doc = lxml.etree.parse(f)
  636. xml_doc, _ = self._remove_template_tags_from_text_nodes(xml_doc)
  637. xml_doc = self._preprocess_for_mc_ignorable(xml_doc)
  638. relative_path = xml_file.relative_to(base_path)
  639. if (
  640. relative_path.parts
  641. and relative_path.parts[0] in self.MAIN_CONTENT_FOLDERS
  642. ):
  643. xml_doc = self._clean_ignorable_namespaces(xml_doc)
  644. if schema.validate(xml_doc):
  645. return True, set()
  646. else:
  647. errors = set()
  648. for error in schema.error_log:
  649. errors.add(error.message)
  650. return False, errors
  651. except Exception as e:
  652. return False, {str(e)}
  653. def _get_original_file_errors(self, xml_file):
  654. if self.original_file is None:
  655. return set()
  656. import tempfile
  657. import zipfile
  658. xml_file = Path(xml_file).resolve()
  659. unpacked_dir = self.unpacked_dir.resolve()
  660. relative_path = xml_file.relative_to(unpacked_dir)
  661. with tempfile.TemporaryDirectory() as temp_dir:
  662. temp_path = Path(temp_dir)
  663. with zipfile.ZipFile(self.original_file, "r") as zip_ref:
  664. zip_ref.extractall(temp_path)
  665. original_xml_file = temp_path / relative_path
  666. if not original_xml_file.exists():
  667. return set()
  668. is_valid, errors = self._validate_single_file_xsd(
  669. original_xml_file, temp_path
  670. )
  671. return errors if errors else set()
  672. def _remove_template_tags_from_text_nodes(self, xml_doc):
  673. warnings = []
  674. template_pattern = re.compile(r"\{\{[^}]*\}\}")
  675. xml_string = lxml.etree.tostring(xml_doc, encoding="unicode")
  676. xml_copy = lxml.etree.fromstring(xml_string)
  677. def process_text_content(text, content_type):
  678. if not text:
  679. return text
  680. matches = list(template_pattern.finditer(text))
  681. if matches:
  682. for match in matches:
  683. warnings.append(
  684. f"Found template tag in {content_type}: {match.group()}"
  685. )
  686. return template_pattern.sub("", text)
  687. return text
  688. for elem in xml_copy.iter():
  689. if not hasattr(elem, "tag") or callable(elem.tag):
  690. continue
  691. tag_str = str(elem.tag)
  692. if tag_str.endswith("}t") or tag_str == "t":
  693. continue
  694. elem.text = process_text_content(elem.text, "text content")
  695. elem.tail = process_text_content(elem.tail, "tail content")
  696. return lxml.etree.ElementTree(xml_copy), warnings
  697. if __name__ == "__main__":
  698. raise RuntimeError("This module should not be run directly.")