'Jsx', 'links' => 'Links', 'template' => 'Template', 'xml' => 'Xml' ]; /** @var array */ private array $files = [ 'xml' => 'generate.xml' ]; /** @var array */ private array $fileTypes = [ 'indesignTemplate' => 'indt', 'indesignJavascript' => 'jsx' ]; /** @var string */ private string $defaultJsxFilePath = "/Users/administrateur/ids/ids.jsx"; /** @var string */ private string $defaultGenerationImage; public function __construct(DirectoryInterface $directory, ParameterBagInterface $params, ClearInterface $clearService, LogService $logService) { $this->directory = $directory; $this->params = $params; $this->clearService = $clearService; $this->logService = $logService; $this->defaultGenerationImage = $this->getDefaultGenerationImage(); } /** * Used in generation in case link send wrong response * * @return string */ private function getDefaultGenerationImage(): string { $path = $this->params->get('arborescence_base') . DIRECTORY_SEPARATOR . 'public/default/default.png'; $exist = $this->directory->findPath($path); if (!$exist) { throw new UnprocessableEntityMaestroException("Ressource not found on path '$path'"); } $content = file_get_contents($path); if (false === $content) { throw new UnprocessableEntityMaestroException("Content not found on path '$path'"); } return $content; } /** * {@inheritdoc} */ public function generate(PageGenerateView $view) { $this->logService->setLog('GenerationService : Entry-point.'); $time = time(); $generationId = $view->project . '_' . $view->export . '_' . $view->id . '_' . $view->folio; // ProjectID_ExportID_PageID_Folio_Time if (!empty($view->versionId) && !empty($view->duplicateId)) { $generationId .= '_' . $view->versionId . '_' . $view->duplicateId; } $xmlPathId = $this->params->get('arborescence_generation_xml') . DIRECTORY_SEPARATOR . $generationId . ".xml"; $generationId .= '_' . $time; $inPath = $this->params->get('arborescence_generation_in'); $absoluteInPath = $this->directory->getAbsolutePath($inPath, 'directory'); $this->logService->setLog('Absolute in path returned.'); if (!$absoluteInPath instanceof Exception) { $absoluteOutPath = $this->directory->getAbsolutePath($this->params->get('arborescence_generation_out'), 'directory'); $this->logService->setLog('Absolute out path returned.'); if (!$absoluteOutPath instanceof Exception) { $inDirectory = $inPath . DIRECTORY_SEPARATOR . $generationId; $generationDirectory = $this->directory->getAbsolutePath($inDirectory, 'directory'); $this->logService->setLog('Generation directory created.'); if (!$generationDirectory instanceof Exception) { $generationSubDirectories = $this->createSubDirectories($inDirectory); // Generation sub directories $this->logService->setLog('Generation sub-directories created.'); if (!$generationSubDirectories instanceof Exception) { $scripArgsContent = $this->createScriptArgs($view, $generationId); $this->logService->setLog('Scriptargs created.'); if (!$scripArgsContent instanceof Exception) { $addedFiles = $this->addAllFilesContentInDirectories($inDirectory, $view, $xmlPathId); $this->logService->setLog('Files created.'); if (!$addedFiles instanceof Exception) { $absoluteOutPath .= $generationId . DIRECTORY_SEPARATOR; $arrayData = [ "generationType" => $view->generationType, "inPath" => $generationDirectory, "outPath" => $absoluteOutPath, "scriptArgs" => $scripArgsContent, "dirName" => $generationId ]; $result = $arrayData; } else { $result = $this->getMergeErrorOnRemovePath($addedFiles->getMessage(), $generationDirectory); } } else { $result = $this->getMergeErrorOnRemovePath($scripArgsContent->getMessage(), $generationDirectory); } } else { $result = $this->getMergeErrorOnRemovePath($generationSubDirectories->getMessage(), $generationDirectory); } } else { $result = $generationDirectory; } } else { $result = $absoluteOutPath; } } else { $result = $absoluteInPath; } return $result; } /** * @param string $inDirectory * * @return bool|Exception */ private function createSubDirectories(string $inDirectory) { $result = true; foreach ($this->generationDirectories as $generationSubDirectory) { $path = $inDirectory . DIRECTORY_SEPARATOR . $generationSubDirectory; $subDirectory = $this->directory->getAbsolutePath($path, 'directory'); if (!$subDirectory instanceof Exception) { continue; } $result = $subDirectory; break; } return $result; } /** * @param PageGenerateView $view * @param string $generationId * * @return string|Exception */ private function createScriptArgs(PageGenerateView $view, string $generationId) { try { if (isset($view->templateFiles['defaultJsx']) && $view->templateFiles['defaultJsx']->originalName) { $jsxDefaultPath = $this->params->get('indesign_jsx') . $view->templateFiles['defaultJsx']->originalName; } else { $jsxDefaultPath = $this->defaultJsxFilePath; } if (isset($view->templateFiles['jsx']) && $view->templateFiles['jsx']->originalName) { $jsxPath = $this->params->get('indesign_in') . $generationId . DIRECTORY_SEPARATOR . $this->generationDirectories['jsx'] . DIRECTORY_SEPARATOR . $view->templateFiles['jsx']->originalName; } else { $jsxPath = $this->defaultJsxFilePath; } $data = [ "runScriptParameters" => [ "scriptText" => null, "scriptFile" => $jsxDefaultPath, "scriptLanguage" => 'javascript', "scriptArgs" => [] ] ]; $templateIndt = str_replace('.indt', '', $view->templateFiles['indt']->originalName); $isColor = false; $stringProtocoleColor = NULL; $options = $view->optionsGabValues; $arrayColorMerge = array(); foreach ($options as $option) { if ($option->type === 'color' && property_exists($option, "value")) { $isColor = true; $oneProtocol = $option->twigVar; $stringProtocoleColor .= ($stringProtocoleColor) ? ',' : NULL; $stringProtocoleColor .= $oneProtocol; $arrayValue = json_decode($option->value, true); $arrayColorMerge[$oneProtocol . '_C'] = $arrayValue['c'] * 100; $arrayColorMerge[$oneProtocol . '_M'] = $arrayValue['m'] * 100; $arrayColorMerge[$oneProtocol . '_Y'] = $arrayValue['y'] * 100; $arrayColorMerge[$oneProtocol . '_K'] = $arrayValue['k'] * 100; } } if ($isColor) { $arrayColorMerge['PROTOCOLE_COULEUR'] = $stringProtocoleColor; } $variables = [ 'path_gabarit' => $this->params->get('indesign_in') . $generationId . DIRECTORY_SEPARATOR . $this->generationDirectories['template'] . DIRECTORY_SEPARATOR, // 'path_package' => "", // 'path_package_filename' => "", 'path_xml' => $this->params->get('indesign_in') . $generationId . DIRECTORY_SEPARATOR . $this->generationDirectories['xml'] . DIRECTORY_SEPARATOR, 'path_syspad' => $this->params->get('indesign_out'), // 'path_export' => "", 'gabarit_name' => $templateIndt, 'gabarit_add_suffixe' => 0, // Page generation case 'build_indd' => $view->generationType, // 0 pdf base def, 1 indesign, 2 package, etc ... 'folio' => $view->folio, 'nb_page' => $view->nbPage, 'nb_product' => $view->nbProduct, 'id_file' => $generationId, 'nom_fichier' => $generationId . '.indd', // Indesign generation case 'langue_protocole' => 'FR', // TODO : Add template options as var for script_args 'path_jsx' => "/Users/administrateur/ids/", // Temporary for debug indesign jsx 'path_jsx_supp' => $jsxPath, // Temporary for debug indesign jsx 'path_font' => $view->fontPath, 'string_args' => '', 'path_package' => $this->params->get('indesign_out') . "/" . $generationId, 'path_package_filename' => $generationId ]; if ($isColor) { $variables = array_merge($variables, $arrayColorMerge); } $args = []; $stringArgs = ""; foreach ($variables as $key => $value) { $arr = ["name" => $key]; if ('string_args' !== $key) { $stringArgs .= $key . ','; $arr["value"] = $value; } else { //$stringArgs = rtrim($stringArgs, ','); $arr["value"] = $stringArgs; } $args[] = $arr; } // Reparse sur string_args car toutes les vaiables ne se mettent pas dedans // Marchait avant car string_args était la derniere clé du tableau. $arrayStringArgs = array(); $savKey = -1; foreach ($args as $key => $oneArg) { if ($oneArg["name"] === 'string_args') { $savKey = $key; $stringArgs = rtrim($stringArgs, ','); $oneArg["value"] = $stringArgs; $arrayStringArgs = $oneArg; } } if ($savKey >= 0) { $args[$savKey] = $arrayStringArgs; } $data["runScriptParameters"]["scriptArgs"] = $args; $result = json_encode($data); } catch (Exception $e) { $result = $e; } return $result; } /** * @param string $inDirectory * @param PageGenerateView $view * * @return bool|Exception */ private function addAllFilesContentInDirectories(string $inDirectory, PageGenerateView $view, $xmlPath) { $xmlFile = $this->addXmlFile($inDirectory, $view->xmlContent, $xmlPath); if (!$xmlFile instanceof Exception) { // $croppedMedias = $this->getAllCropFromGabValue($view->elementsGabValues); // Currently unused // $this->addMediaFiles($inDirectory, $view->mediaFiles, /*$croppedMedias,*/ $view->generationType); // $this->addMediaLinks($inDirectory, $view->mediaLinks); $templateFiles = $this->addTemplateFiles($inDirectory, $view->templateFiles); if (!$templateFiles instanceof Exception) { $result = true; } else { $result = $templateFiles; } } else { $result = $xmlFile; } return $result; } /** * @param string $inDirectory * @param string $xmlContent * * @return bool|Exception */ private function addXmlFile(string $inDirectory, string $xmlContent, $xmlGenerationlPath) { $xmlPath = $inDirectory . DIRECTORY_SEPARATOR . $this->generationDirectories['xml'] . DIRECTORY_SEPARATOR . $this->files['xml']; $filePath = $this->directory->getAbsolutePath($xmlPath, "file", $xmlContent); $this->directory->getAbsolutePath($xmlGenerationlPath, "file", $xmlContent, true); if (!$filePath instanceof Exception) { $result = true; } else { $result = $filePath; } return $result; } /** * @param string $inDirectory * @param array $mediaFiles * @param array $croppedMedias * @param int $generationType * * @return void * * @throws InternalServerErrorMaestroException|UnprocessableEntityMaestroException|Exception */ private function addMediaFiles(string $inDirectory, array $mediaFiles, /*array $croppedMedias,*/ int $generationType): void { foreach ($mediaFiles as $mediaFile) { $this->logService->setLog("Start add file : " . $mediaFile['originalName']); $mediaPath = $inDirectory . DIRECTORY_SEPARATOR . $this->generationDirectories['links'] . DIRECTORY_SEPARATOR . $mediaFile['originalName']; if ($mediaFile['filePath'] || $mediaFile['fileBdPath']) { if (($generationType && $mediaFile['filePath']) || strrpos($mediaFile["originalName"], '.ai', -3)) { $content = $this->getContentFromPath($mediaFile['filePath']); } else { $content = $this->getContentFromPath($mediaFile['fileBdPath']); } } else if ($mediaFile['file'] || $mediaFile['fileBd']) { if (($generationType && $mediaFile['file']) || strrpos($mediaFile["originalName"], '.ai', -3)) { $content = $this->decodeFileContent($mediaFile['file']); } else { $content = $this->decodeFileContent($mediaFile['fileBd']); } } else { throw new UnprocessableEntityMaestroException("No file path or file was found for media : " . $mediaFile['originalName']); } $filePath = $this->directory->getAbsolutePath($mediaPath, "file", $content); if (!$filePath instanceof Exception) { $this->logService->setLog("End add file : " . $mediaFile['originalName']); continue; } throw $filePath; } } /** * @param string $inDirectory, * @param array $mediaLinks * * @return void */ private function addMediaLinks(string $inDirectory, array $mediaLinks): void { foreach ($mediaLinks as $mediaLink) { $name = strtolower($this->formatLinksFileName($mediaLink)); $this->logService->setLog("Start add link : '$mediaLink' as '$name'"); $mediaPath = $inDirectory . DIRECTORY_SEPARATOR . $this->generationDirectories['links'] . DIRECTORY_SEPARATOR . $name; $this->getLinkData($mediaLink, $mediaPath); } } /** * {@inheritDoc} */ public function formatLinksFileName(string $link): string { $name = (string) substr($link, strrpos("/" . $link, '/')); if (empty($name)) { $name = str_replace("/", "", $link); } return $name; } /** * {@inheritDoc} */ public function getLinkMetadata($media) { if (is_array($media)) { $isArray = true; $mediaLink = isset($media["link"]) ? $media["link"] : false; } else if (is_object($media)) { $isArray = false; $mediaLink = isset($media->linkData) && isset($media->linkData["link"]) ? $media->linkData["link"] : false; } else { throw new UnprocessableEntityMaestroException("Unexpected parameter given, array or object expected, given " . gettype($media)); } if ($mediaLink) { $metadata = $this->getLinkData($mediaLink); if (is_string($metadata)) { $decoded = json_decode($metadata, true); $data = isset($decoded[0]) && is_array($decoded[0]) ? $decoded[0] : $decoded; if (isset($data["image"])) { $isArray ? $media["link"] = $data["image"] : $media->linkData["link"] = $data["image"]; } else if (isset($data["thumbnailUrl"])) { $isArray ? $media["link"] = $data["thumbnailUrl"] : $media->linkData["link"] = $data["thumbnailUrl"]; } else if (isset($data["url"])) { $isArray ? $media["link"] = $data["url"] : $media->linkData["link"] = $data["url"]; } } else { throw new UnprocessableEntityMaestroException("Unexpected result, metadata is not a string, received " . gettype($metadata)); } return $media; } else { throw new UnprocessableEntityMaestroException("Media hasn't 'link' property"); } } /** * {@inheritDoc} */ public function getLinkData(string $mediaLink, string $mediaPath = null) { $response = true; if ($mediaLink && is_string($mediaLink) && preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $mediaLink)) { $try = 1; while ($try <= 3) { try { $ch = curl_init($mediaLink); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $httpContentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); if ($httpcode === 200) { if (isset($mediaPath)) { $isImage = 0 === strpos($httpContentType, "image/"); // ENSURES THAT LINK PROVIDES ONLY IMAGE TYPE => CAN BE COMMENT LATER WHEN WE WILL ADD OTHERS FILES TYPE if ($isImage) { $filePath = $this->directory->getAbsolutePath($mediaPath, "file", $output); } else { $filePath = $this->directory->getAbsolutePath($mediaPath, "file", $this->defaultGenerationImage); } if (!$filePath instanceof Exception) { $this->logService->setLog("End add file : " . $filePath); $try = 3; // STOP LOOP } else { throw $filePath; } } else { $response = $output; } } } catch (Exception $e) { if ($try === 3) { throw $e; } } $try++; } } else { throw new UnprocessableEntityMaestroException("Link provided does not fit the requirement ! Check the url."); } return $response; } /** * @throws InternalServerErrorMaestroException */ private function getContentFromPath(string $path): string { $damUrl = $this->params->get('domain_dam'); $fileStream = fopen($damUrl . $path, 'rb'); if ($fileStream) { $content = stream_get_contents($fileStream); if ($content) { fclose($fileStream); return $content; } throw new InternalServerErrorMaestroException("Unable to get content from $damUrl . $path"); } $this->logService->setLog("File error : " . $path); throw new InternalServerErrorMaestroException("Invalid file path: " . $damUrl . $path); } /** * @param string $inDirectory * @param array $templateFiles * * @return bool|Exception */ private function addTemplateFiles(string $inDirectory, array $templateFiles) { $result = true; foreach ($templateFiles as $key => $templateFile) { if($key !== "defaultJsx"){ $inPath = $inDirectory . DIRECTORY_SEPARATOR; $originalName = DIRECTORY_SEPARATOR . $templateFile->originalName; if ($this->fileTypes['indesignTemplate'] === $key) { if ($this->params->get('indt_local_file')) { $templateFilePath = $inPath . $this->generationDirectories['template'] . $originalName; } else { $templateFilePath = null; } } elseif ($this->fileTypes['indesignJavascript'] === $key) { $templateFilePath = $inPath . $this->generationDirectories['jsx'] . $originalName; } else { $result = new Exception("Unknown fileType $key, can't be added in directory."); break; } if ($templateFilePath) { $content = $this->decodeFileContent($templateFile->file); $filePath = $this->directory->getAbsolutePath($templateFilePath, "file", $content); } else { $filePath = null; } if (!$filePath instanceof Exception) { continue; } $result = $filePath; break; } } return $result; } /** * @param string $stream [base64_encode of a file's stream_get_contents] * * @return string [the decoded string] */ private function decodeFileContent(string $stream): string { return base64_decode($stream); } /** * {@inheritDoc} * @throws Exception */ public function generateHTML(array $html, array $medias, int $exportId, int $pageId, string $generationType, array $templateFiles, array $elementsGabValues) { try { $damUrl = $this->params->get('domain_dam'); $allCrop = $this->getAllCropFromGabValue($elementsGabValues); $allCrop[-1] = null; $htmlResult = ["html" => $html["content"], "preview" => $html["content"]]; if (!empty($medias)) { foreach ($medias as $media) { foreach ($allCrop as $key => $crop) { if (strpos($htmlResult['preview'], 'mediaId__' . $media['mediaId'] . '__cropId__' . $key) !== false) { if (null !== $crop) { $modif = [ "height" => $crop->height, "width" => $crop->width, "x" => $crop->x, "y" => $crop->y, "rotate" => $crop->rotate, "flipVertical" => $crop->flipVertical, "flipHorizontal" => $crop->flipHorizontal ]; } else { $modif = []; } $filePath = isset($media['filePath']) && $media['filePath'] ? $media['filePath'] : ''; $regex = '/(sendGenerateFile($pageId, $exportId, $html, $generationType, $templateFiles, $htmlResult); } catch (Exception $e) { $result = $e->getMessage(); } return $result; } private function sendGenerateFile(int $pageId, int $exportId, array $html, string $generationType, array $templateFiles, array $htmlResult) { if (!empty($templateFiles["html"])) { $htmlResult = $this->createCssAndJs($templateFiles['html'], $htmlResult); } $files['type'] = $generationType; $name = 'export_' . $exportId . '_page_' . $pageId . '.twig'; $files['files'][] = $this->createAndSendFile($name, $htmlResult["html"], "html"); $namePreview = 'export_' . $exportId . '_page_' . $pageId . '_preview.twig'; $files['files'][] = $this->createAndSendFile($namePreview, $htmlResult["preview"], "preview"); $thumbPreview = $this->createPreview($htmlResult["preview"], 'export_' . $exportId . '_page_' . $pageId); if ($thumbPreview !== null) { $files['files'][] = $thumbPreview; } $this->removefileExport(); return $files; } /** * @param array $htmlFile * @param string $htmlContent * * @return array */ private function createCssAndJs(array $htmlFile, array $htmlResult): array { $htmlContent = $htmlResult['html']; $preview = $htmlResult['preview']; foreach ($htmlFile as $file) { $data = base64_decode($file->file); $filePath = $this->params->get('arborescence_base') . '/templates/' . $file->originalName; file_put_contents($filePath, $data); switch ($file->extension) { case 'html': $htmlContent = str_replace("{% include '" . $file->originalName . "' %}", $data, $htmlContent); $preview = str_replace("{% include '" . $file->originalName . "' %}", $data, $preview); break; case 'css': $regex = "originalName . ".* ?>"; preg_match($regex, $preview, $matchesCSS, PREG_OFFSET_CAPTURE); if (!empty($matchesCSS)) { $preview = str_replace('<' . reset($matchesCSS[0]), "", $preview); } $this->sendHtml($this->params->get('arborescence_base') . '/templates/' . $file->originalName); break; case 'js': $regex = "originalName . ".* ?>"; preg_match($regex, $preview, $matchesJS, PREG_OFFSET_CAPTURE); if (!empty($matchesJS)) { $preview = str_replace("<" . reset($matchesJS[0]), "", $preview); } $this->sendHtml($this->params->get('arborescence_base') . '/templates/' . $file->originalName); break; } } return ['html' => $htmlContent, 'preview' => $preview]; } /** * @param $name * @param $content * @param string $type * * @return array */ private function createAndSendFile($name, $content, string $type): array { $absolutePath = $this->directory->getAbsolutePath('templates/' . $name . '.html', 'file'); $fileHTML = fopen($absolutePath, 'w+'); fwrite($fileHTML, $content); $file = file_get_contents($this->params->get('arborescence_base') . '/templates/' . $name . '.html'); $data = base64_encode($file); $result = [ 'name' => $name, 'extension' => 'html', 'content' => $data ]; if ($type === "html") { $this->sendHtml($this->params->get('arborescence_base') . '/templates/' . $name . '.html'); } return $result; } /** * @param string $filePath * * @return void */ private function sendHtml(string $filePath): void { $sshTarget = $this->params->get('export_html_user') . '@' . $this->params->get('export_html_host') . ':' . $this->params->get('export_html_path'); try { $process = new Process(['scp', "$filePath", "$sshTarget"]); $process->mustRun(); $process->getOutput(); } catch (ProcessFailedException $e) { // Nothing to do ? Why return and no use in calls ? } } /** * @param string $baseError * @param string $path * * @return Exception */ private function getMergeErrorOnRemovePath(string $baseError, string $path): Exception { if ($this->params->get('generation_keep_files')) { $deletedMessage = "No files were deleted cause 'generation_keep_files' environment variable is active"; } else { $deleted = $this->directory->removeFromPath($path); $deletedMessage = !$deleted instanceof Exception ? "The path '$path' has been deleted successfully." : $deleted->getMessage(); } return new Exception($baseError . " & " . $deletedMessage); } /** * @param array $mediasFiles * * @return array */ public function renameMediasFiles(array $mediasFiles): array { $searchKey = "originalName"; $filesName = array_values(array_column($mediasFiles, $searchKey)); $newFilesName = $this->clearService->cleanFilesName($filesName); $renamedMediasFiles = []; foreach ($mediasFiles as $key => $val) { $val[$searchKey] = $newFilesName[$key]; $renamedMediasFiles[] = $val; } return $renamedMediasFiles; } /** * @param array $elementsGabValues * * @return array */ private function getAllCropFromGabValue(array $elementsGabValues): array { $crop = []; foreach ($elementsGabValues as $element) { if (!empty($element->medias)) { foreach ($element->medias as $media) { if (-1 !== $media->mediaId) { $crop[$media->exportMediaId] = $media; } } } } return $crop; } /** * {@inheritdoc} * @throws Exception */ public function cropMediaImage($file, $crop, $original = null, bool $isBase64 = true): string { if (!$isBase64) { $damUrl = $this->params->get('domain_dam'); if ($fileStream = fopen($damUrl . $file, 'r')) { $imageBlob = stream_get_contents($fileStream); fclose($fileStream); } else { throw new Exception("Invalide file path: " . $damUrl . $file); } } else { $imageBlob = base64_decode($file); } $obj_imagick = new Imagick(); $obj_imagick->readImageBlob($imageBlob); if ($crop['width'] > 0 && $crop['height'] > 0) { if (!empty($original)) { if (!$isBase64) { if ($fileStream = fopen($damUrl . $original, 'r')) { $imageOriginalBlob = stream_get_contents($fileStream); fclose($fileStream); } else { throw new Exception("Invalide file path: " . $damUrl . $original); } } else { $imageOriginalBlob = base64_decode($original); } $original_imagick = new Imagick(); $original_imagick->readImageBlob($imageOriginalBlob); } else { $original_imagick = $obj_imagick; } $width = $obj_imagick->getImageWidth() * $crop['width'] / $original_imagick->getImageWidth(); $height = $obj_imagick->getImageHeight() * $crop['height'] / $original_imagick->getImageHeight(); $x = $obj_imagick->getImageWidth() * $crop['x'] / $original_imagick->getImageWidth(); $y = $obj_imagick->getImageHeight() * $crop['y'] / $original_imagick->getImageHeight(); if ($crop['rotate'] !== 0) { $obj_imagick->rotateImage(new ImagickPixel('#00000000'), $crop['rotate']); } if ($crop['flipHorizontal']) { $obj_imagick->flopImage(); } if ($crop['flipVertical']) { $obj_imagick->flipImage(); } $obj_imagick->cropImage($width, $height, $x, $y); } $img = $obj_imagick->getImageBlob(); return base64_encode($img); } /** * @param $html * @param $name * * @return array|null * @throws \ImagickException */ private function createPreview($html, $name): ?array { $pdfOptions = new Options(); $imagick = new Imagick(); $pdfOptions->set('defaultFont', 'Arial'); // Instantiate Dompdf with our options $dompdf = new Dompdf($pdfOptions); // Load HTML to Dompdf $dompdf->loadHtml($html); // (Optional) Setup the paper size and orientation 'portrait' or 'portrait' $dompdf->setPaper('A4', 'portrait'); // Render the HTML as PDF $dompdf->render(); $output = $dompdf->output(); $pdfFilepath = $this->params->get('arborescence_base') . '/templates/' . $name . '.pdf'; // Write file to the desired path file_put_contents($pdfFilepath, $output); $jpgPath = $this->params->get('arborescence_base') . '/templates/' . $name . '.jpg'; $imagick->readimage($pdfFilepath . '[0]'); $imagick->setImageFormat('jpg'); $imagick->writeImage($jpgPath); $file = file_get_contents($jpgPath); $data = base64_encode($file); return [ 'name' => $name, 'extension' => 'jpg', 'content' => $data ]; } /** * @return void */ private function removefileExport(): void { $exportFilepath = scandir($this->params->get('arborescence_base') . '/templates'); foreach ($exportFilepath as $file) { if (strpos($file, "export_") !== false) { unlink($this->params->get('arborescence_base') . '/templates/' . $file); } } } private function createCropHtml(string $img, $crop, $media, $preview) { $newImgCrop = ''; $scaleMediaWidth = $crop->positionPhotoWidth / $crop->width; $scaleMediaHeight = $crop->positionPhotoHeight / $crop->height; $mediaSize = $this->getImageSize($media); $width = $mediaSize['width'] * $scaleMediaWidth; $height = $mediaSize['height'] * $scaleMediaHeight; $x = -$crop->x * $scaleMediaWidth; $y = -$crop->y * $scaleMediaHeight; if (!$preview) { $newImgCrop .= ''; } else { if ($media['fileBdPath']) { $damUrl = $this->params->get('domain_dam'); $newImgCrop .= ''; } } return $newImgCrop; } private function getImageSize($media) { if (isset($media['fileBdPath']) && $media['fileBdPath']) { $damUrl = $this->params->get('domain_dam'); if ($fileStream = fopen($damUrl . $media['fileBdPath'], 'r')) { $imageBlob = stream_get_contents($fileStream); fclose($fileStream); } else { throw new Exception("Invalide file path: " . $damUrl . $media['fileBdPath']); } } else { $imageBlob = base64_decode($media['fileBd']); } $obj_imagick = new Imagick(); $obj_imagick->readImageBlob($imageBlob); return ['width' => $obj_imagick->getImageWidth(), "height" => $obj_imagick->getImageHeight()]; } }