diff --git a/app/Controllers/Ipd_discharge.php b/app/Controllers/Ipd_discharge.php index e8f7896..a7fad80 100644 --- a/app/Controllers/Ipd_discharge.php +++ b/app/Controllers/Ipd_discharge.php @@ -7047,9 +7047,113 @@ class Ipd_discharge extends BaseController $out = (string) preg_replace('/\bheader\s*:\s*html[_a-z0-9-]+\s*;?/i', '', $out); $out = (string) preg_replace('/\bfooter\s*:\s*html[_a-z0-9-]+\s*;?/i', '', $out); + if ($this->looksLikeMalformedDischargeHtml($out)) { + $out = $this->normalizeMalformedDischargeHtmlForMpdf($out); + } + return $this->forceValidUtf8($out); } + private function looksLikeMalformedDischargeHtml(string $html): bool + { + if ($html === '') { + return false; + } + + if (preg_match('/
]*>\s*<(?:div|table|h[1-6]|ul|ol|p)\b/i', $html) === 1) { + return true; + } + + if (preg_match('/<(?!\/?(?:[a-z][a-z0-9:_-]*)(?:\s|\/?>)|!--|\?xml|!doctype)/i', $html) === 1) { + return true; + } + + return preg_match('/<\/(?:p|div|span|strong|em|i|b)>\s*<\/(?:p|div)>/i', $html) === 1; + } + + private function normalizeMalformedDischargeHtmlForMpdf(string $html): string + { + if ($html === '') { + return ''; + } + + $html = $this->escapeInvalidAngleBrackets($html); + + if (! class_exists('DOMDocument')) { + return $html; + } + + $previousUseInternalErrors = libxml_use_internal_errors(true); + libxml_clear_errors(); + + try { + $dom = new \DOMDocument('1.0', 'UTF-8'); + $flags = 0; + if (defined('LIBXML_NOWARNING')) { + $flags |= LIBXML_NOWARNING; + } + if (defined('LIBXML_NOERROR')) { + $flags |= LIBXML_NOERROR; + } + if (defined('LIBXML_COMPACT')) { + $flags |= LIBXML_COMPACT; + } + + $wrappedHtml = '