Skip to content

Commit

Permalink
Test: Fix Pictures in HTML Export
Browse files Browse the repository at this point in the history
  • Loading branch information
kergomard committed Nov 10, 2023
1 parent 99339f7 commit 5677a09
Showing 1 changed file with 34 additions and 15 deletions.
49 changes: 34 additions & 15 deletions components/ILIAS/Test/classes/class.ilTestHTMLGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,39 +78,58 @@ private function makeHtmlDocument($content_html, $style_html): string

$dom->encoding = 'UTF-8';

$content_to_replace = $this->generateImageDataSrces($dom);

$cleaned_html = $dom->saveHTML();

if (!$cleaned_html) {
return $html;
}

if ($content_to_replace === null) {
return $cleaned_html;
}

return str_replace(array_keys($content_to_replace), array_values($content_to_replace), $cleaned_html);
}

private function generateImageDataSrces(DOMDocument $dom): ?array
{
$content_to_replace = null;
$sources = [];
$image_file_names = [];
foreach ($dom->getElementsByTagName('img') as $elm) {
/** @var $elm DOMElement $uid */
$src = $elm->getAttribute('src');
$original_content = $dom->saveHTML($elm);

$src_uri = new ILIAS\Data\URI($src);
$path_to_file = $_SERVER['DOCUMENT_ROOT'] . $src_uri->getPath();
if (array_key_exists($src, $sources)) {
$replacement_content = preg_replace('/src=[^\s]*/', "src='{$sources[$src]}'", $original_content);
$content_to_replace[$original_content] = $replacement_content;
continue;
}

try {
$image_content = base64_encode(file_get_contents($path_to_file));
$image_raw_content = file_get_contents($src);
$image_file_names[$src] = ilFileUtils::ilTempnam();
file_put_contents($image_file_names[$src], $image_raw_content);
$image_content = base64_encode($image_raw_content);
$file_info = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($file_info, $path_to_file);
$mime_type = finfo_file($file_info, $image_file_names[$src]);
$image_data = "data:{$mime_type};base64,{$image_content}";

$original_content = $dom->saveHTML($elm);
$sources[$src] = $image_data;
$replacement_content = preg_replace('/src=[^\s]*/', "src='{$image_data}'", $original_content);
$content_to_replace[$original_content] = $replacement_content;
} catch (Exception $e) {

}
}

$cleaned_html = $dom->saveHTML();

if (!$cleaned_html) {
return $html;
}

if ($content_to_replace === null) {
return $cleaned_html;
foreach ($image_file_names as $image_file_name) {
unlink($image_file_name);
}

return str_replace(array_keys($content_to_replace), array_values($content_to_replace), $cleaned_html);
return $content_to_replace;
}

public function generateHTML(string $content, string $filename)
Expand Down

0 comments on commit 5677a09

Please sign in to comment.