template; $sourceAbsolutePath = Storage::disk('local')->path($template->file_path); $outputRelativePath = 'templates/generations/'.$generation->uuid.'.pptx'; $outputAbsolutePath = Storage::disk('local')->path($outputRelativePath); Storage::disk('local')->makeDirectory('templates/generations'); if (! copy($sourceAbsolutePath, $outputAbsolutePath)) { throw new RuntimeException('امکان ساخت فایل خروجی وجود ندارد.'); } $values = $generation->values ?? []; $textValues = []; $imageValues = []; foreach ($template->keys as $key) { if (! array_key_exists($key->key, $values)) { continue; } match ($key->type) { TemplateKeyType::Text => $textValues[$key->key] = (string) $values[$key->key], TemplateKeyType::Image => $imageValues[$key->shape_name] = Storage::disk('local')->path($values[$key->key]), TemplateKeyType::Chart => throw new RuntimeException('پرکردن کلید از نوع چارت هنوز پشتیبانی نمی‌شود.'), }; } $zip = new ZipArchive; if ($zip->open($outputAbsolutePath) !== true) { throw new RuntimeException('باز کردن فایل پاورپوینت با خطا مواجه شد.'); } try { $slideEntries = $this->findSlideEntries($zip); foreach ($slideEntries as $slideEntry) { $xml = $zip->getFromName($slideEntry); if ($xml === false) { continue; } if ($textValues !== []) { $newXml = $this->replaceTextInSlideXml($xml, $textValues); if ($newXml !== null) { $zip->addFromString($slideEntry, $newXml); $xml = $newXml; } } foreach ($imageValues as $shapeName => $imagePath) { $this->replaceShapeImage($zip, $slideEntry, $xml, $shapeName, $imagePath); } } } finally { $zip->close(); } return $outputRelativePath; } /** * @return array */ private function findSlideEntries(ZipArchive $zip): array { $entries = []; for ($i = 0; $i < $zip->numFiles; $i++) { $name = $zip->getNameIndex($i); if ($name !== false && preg_match('#^ppt/slides/slide\d+\.xml$#', $name)) { $entries[] = $name; } } return $entries; } /** * @param array $textValues */ private function replaceTextInSlideXml(string $xml, array $textValues): ?string { if (! str_contains($xml, '{')) { return null; } $lookup = []; foreach ($textValues as $key => $value) { $lookup[$this->normalizeKey($key)] = $value; } $dom = new DOMDocument; $previousSetting = libxml_use_internal_errors(true); $loaded = $dom->loadXML($xml); libxml_clear_errors(); libxml_use_internal_errors($previousSetting); if (! $loaded) { return null; } $xpath = new DOMXPath($dom); $xpath->registerNamespace('a', self::NS_DRAWING); $changed = false; foreach ($xpath->query('//a:p') as $paragraph) { $textNodes = iterator_to_array($xpath->query('.//a:r/a:t', $paragraph)); if ($textNodes === []) { continue; } $originalText = ''; foreach ($textNodes as $textNode) { $originalText .= $textNode->textContent; } if (! str_contains($originalText, '{')) { continue; } $newText = preg_replace_callback( '/\{\{?\s*([^{}]+?)\s*\}?\}/u', function (array $matches) use ($lookup): string { $normalizedKey = $this->normalizeKey($matches[1]); return array_key_exists($normalizedKey, $lookup) ? $lookup[$normalizedKey] : $matches[0]; }, $originalText ); if ($newText === null || $newText === $originalText) { continue; } $textNodes[0]->textContent = $newText; for ($i = 1; $i < count($textNodes); $i++) { $textNodes[$i]->textContent = ''; } $changed = true; } return $changed ? $dom->saveXML() : null; } private function normalizeKey(string $key): string { return mb_strtolower(trim($key, "{} \t\n\r\0\x0B")); } private function replaceShapeImage(ZipArchive $zip, string $slideEntry, string $slideXml, string $shapeName, string $newImagePath): void { $relationshipId = $this->findImageRelationshipId($slideXml, $shapeName); if ($relationshipId === null) { return; } $mediaPath = $this->resolveMediaPath($zip, $slideEntry, $relationshipId); if ($mediaPath === null) { return; } $zip->addFromString($mediaPath, $this->reencodeImage($mediaPath, $newImagePath)); } private function findImageRelationshipId(string $slideXml, string $shapeName): ?string { $dom = new DOMDocument; $previousSetting = libxml_use_internal_errors(true); $loaded = $dom->loadXML($slideXml); libxml_clear_errors(); libxml_use_internal_errors($previousSetting); if (! $loaded) { return null; } $xpath = new DOMXPath($dom); $xpath->registerNamespace('p', self::NS_PRESENTATION); $xpath->registerNamespace('a', self::NS_DRAWING); $xpath->registerNamespace('r', self::NS_RELATIONSHIPS); foreach ($xpath->query('//p:cNvPr') as $cNvPr) { if ($cNvPr->getAttribute('name') !== $shapeName) { continue; } $picNode = $cNvPr->parentNode; while ($picNode !== null && $picNode->nodeName !== 'p:pic') { $picNode = $picNode->parentNode; } if ($picNode === null) { continue; } $blips = $xpath->query('.//a:blip', $picNode); if ($blips->length === 0) { continue; } $embedId = $blips->item(0)->getAttributeNS(self::NS_RELATIONSHIPS, 'embed'); if ($embedId !== '') { return $embedId; } } return null; } private function resolveMediaPath(ZipArchive $zip, string $slideEntry, string $relationshipId): ?string { $relsEntry = 'ppt/slides/_rels/'.basename($slideEntry).'.rels'; $relsXml = $zip->getFromName($relsEntry); if ($relsXml === false) { return null; } $dom = new DOMDocument; $previousSetting = libxml_use_internal_errors(true); $loaded = $dom->loadXML($relsXml); libxml_clear_errors(); libxml_use_internal_errors($previousSetting); if (! $loaded) { return null; } foreach ($dom->getElementsByTagName('Relationship') as $relationship) { if ($relationship->getAttribute('Id') !== $relationshipId) { continue; } return $this->normalizeZipPath('ppt/slides/'.$relationship->getAttribute('Target')); } return null; } private function normalizeZipPath(string $path): string { $segments = []; foreach (explode('/', $path) as $segment) { if ($segment === '' || $segment === '.') { continue; } if ($segment === '..') { array_pop($segments); continue; } $segments[] = $segment; } return implode('/', $segments); } private function reencodeImage(string $mediaPath, string $newImagePath): string { $resource = imagecreatefromstring(file_get_contents($newImagePath)); if ($resource === false) { throw new RuntimeException('فایل تصویر ارسالی معتبر نیست.'); } $extension = strtolower(pathinfo($mediaPath, PATHINFO_EXTENSION)); ob_start(); match ($extension) { 'jpg', 'jpeg' => imagejpeg($resource, quality: 92), 'gif' => imagegif($resource), 'bmp' => imagebmp($resource), default => imagepng($resource), }; $bytes = ob_get_clean(); return $bytes; } }