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