generated from Nodarx/template
9a767339fe
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
46 lines
1.7 KiB
PHP
46 lines
1.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace KTXM\ServiceWopi\Preview;
|
|
|
|
use CURLStringFile;
|
|
use KTXF\Preview\PreviewGenerationException;
|
|
use KTXM\ServiceWopi\Discovery\ServerAddress;
|
|
|
|
class ConversionClient
|
|
{
|
|
public const MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
|
|
|
|
public function pdf(ServerAddress $server, string $content, string $extension, string $mimeType): string
|
|
{
|
|
$curl = curl_init($server->url . '/cool/convert-to/pdf');
|
|
$pdf = '';
|
|
curl_setopt_array($curl, [
|
|
CURLOPT_POST => true,
|
|
CURLOPT_POSTFIELDS => ['data' => new CURLStringFile($content, 'document.' . $extension, $mimeType)],
|
|
CURLOPT_CONNECTTIMEOUT => 5,
|
|
CURLOPT_TIMEOUT => 30,
|
|
CURLOPT_FOLLOWLOCATION => false,
|
|
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
|
CURLOPT_SSL_VERIFYPEER => true,
|
|
CURLOPT_SSL_VERIFYHOST => 2,
|
|
CURLOPT_HTTPHEADER => ['Accept: application/pdf'],
|
|
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$pdf): int {
|
|
if (strlen($pdf) + strlen($chunk) > self::MAX_RESPONSE_BYTES) { return 0; }
|
|
$pdf .= $chunk;
|
|
return strlen($chunk);
|
|
},
|
|
]);
|
|
try {
|
|
if (curl_exec($curl) === false) {
|
|
throw new PreviewGenerationException('WOPI conversion failed (cURL ' . curl_errno($curl) . ')');
|
|
}
|
|
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) !== 200 || !str_starts_with($pdf, '%PDF-')) {
|
|
throw new PreviewGenerationException('WOPI conversion did not return a PDF');
|
|
}
|
|
return $pdf;
|
|
} finally {
|
|
curl_close($curl);
|
|
}
|
|
}
|
|
}
|