• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

LibreSign / libresign / 21337786628

25 Jan 2026 06:54PM UTC coverage: 45.319%. First build
21337786628

Pull #6573

github

web-flow
Merge e9318e369 into 14d0dcc48
Pull Request #6573: fix: resize background

0 of 42 new or added lines in 1 file covered. (0.0%)

7469 of 16481 relevant lines covered (45.32%)

4.95 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

13.66
/lib/Handler/SignEngine/JSignPdfHandler.php
1
<?php
2

3
declare(strict_types=1);
4
/**
5
 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6
 * SPDX-License-Identifier: AGPL-3.0-or-later
7
 */
8

9
namespace OCA\Libresign\Handler\SignEngine;
10

11
use Imagick;
12
use ImagickPixel;
13
use OCA\Libresign\AppInfo\Application;
14
use OCA\Libresign\Exception\LibresignException;
15
use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory;
16
use OCA\Libresign\Helper\JavaHelper;
17
use OCA\Libresign\Service\DocMdpConfigService;
18
use OCA\Libresign\Service\Install\InstallService;
19
use OCA\Libresign\Service\SignatureBackgroundService;
20
use OCA\Libresign\Service\SignatureTextService;
21
use OCA\Libresign\Service\SignerElementsService;
22
use OCA\Libresign\Vendor\Jeidison\JSignPDF\JSignPDF;
23
use OCA\Libresign\Vendor\Jeidison\JSignPDF\Sign\JSignParam;
24
use OCP\Files\File;
25
use OCP\IAppConfig;
26
use OCP\ITempManager;
27
use Psr\Log\LoggerInterface;
28

29
class JSignPdfHandler extends Pkcs12Handler {
30
        private const MIN_PDF_VERSION = 1.2;
31
        private const TARGET_OLD_PDF_VERSION = '1.3';
32
        private const MIN_PDF_VERSION_SHA256 = 1.6;
33
        private const TARGET_PDF_VERSION_SHA256 = '1.6';
34
        private const MIN_PDF_VERSION_SHA1_REJECT = 1.7;
35
        private const SIGNATURE_DEFAULT_FONT_SIZE = 10.0;
36
        private const PAGE_FIRST = 1;
37
        private const SCALE_FACTOR_MIN = 5;
38

39
        /** @var JSignPDF */
40
        private $jSignPdf;
41
        /** @var JSignParam */
42
        private $jSignParam;
43
        private array $parsedSignatureText = [];
44

45
        public function __construct(
46
                private IAppConfig $appConfig,
47
                private LoggerInterface $logger,
48
                private SignatureTextService $signatureTextService,
49
                private ITempManager $tempManager,
50
                private SignatureBackgroundService $signatureBackgroundService,
51
                protected CertificateEngineFactory $certificateEngineFactory,
52
                protected JavaHelper $javaHelper,
53
                private DocMdpConfigService $docMdpConfigService,
54
        ) {
55
        }
24✔
56

57
        public function setJSignPdf(JSignPDF $jSignPdf): void {
58
                $this->jSignPdf = $jSignPdf;
×
59
        }
60

61
        public function getJSignPdf(): JSignPDF {
62
                if (!$this->jSignPdf) {
×
63
                        // @codeCoverageIgnoreStart
64
                        $this->setJSignPdf(new JSignPDF());
65
                        // @codeCoverageIgnoreEnd
66
                }
67
                return $this->jSignPdf;
×
68
        }
69

70
        /**
71
         * @psalm-suppress MixedReturnStatement
72
         */
73
        public function getJSignParam(): JSignParam {
74
                if (!$this->jSignParam) {
8✔
75
                        $javaPath = $this->javaHelper->getJavaPath();
8✔
76
                        $tempPath = $this->appConfig->getValueString(Application::APP_ID, 'jsignpdf_temp_path', sys_get_temp_dir() . DIRECTORY_SEPARATOR);
8✔
77
                        if (!is_writable($tempPath)) {
8✔
78
                                throw new \Exception('The path ' . $tempPath . ' is not writtable. Fix this or change the LibreSign app setting jsignpdf_temp_path to a writtable path');
2✔
79
                        }
80
                        $jSignPdfJarPath = $this->appConfig->getValueString(Application::APP_ID, 'jsignpdf_jar_path', '/opt/jsignpdf-' . InstallService::JSIGNPDF_VERSION . '/JSignPdf.jar');
6✔
81
                        if (!file_exists($jSignPdfJarPath)) {
6✔
82
                                throw new \Exception('Invalid JSignPdf jar path. Run occ libresign:install --jsignpdf');
1✔
83
                        }
84
                        $this->jSignParam = (new JSignParam())
5✔
85
                                ->setTempPath($tempPath)
5✔
86
                                ->setIsUseJavaInstalled(empty($javaPath))
5✔
87
                                ->setJavaDownloadUrl('')
5✔
88
                                ->setJSignPdfDownloadUrl('')
5✔
89
                                ->setjSignPdfJarPath($jSignPdfJarPath);
5✔
90
                        if (!empty($javaPath)) {
5✔
91
                                if (!file_exists($javaPath)) {
4✔
92
                                        throw new \Exception('Invalid Java binary. Run occ libresign:install --java');
2✔
93
                                }
94
                                $this->jSignParam->setJavaPath(
2✔
95
                                        $this->getEnvironments()
2✔
96
                                        . $javaPath
2✔
97
                                        . ' -Duser.home=' . escapeshellarg($this->getHome()) . ' '
2✔
98
                                );
2✔
99
                        }
100

101
                        $certificationLevel = $this->getCertificationLevel();
3✔
102
                        if ($certificationLevel !== null) {
3✔
103
                                $this->jSignParam->setJSignParameters(' -cl ' . $certificationLevel);
×
104
                        }
105
                }
106
                return $this->jSignParam;
3✔
107
        }
108

109
        private function getEnvironments(): string {
110
                return 'JSIGNPDF_HOME=' . escapeshellarg($this->getHome()) . ' ';
2✔
111
        }
112

113
        /**
114
         * It's a workaround to create the folder structure that JSignPdf needs. Without
115
         * this, the JSignPdf will return the follow message to all commands:
116
         * > FINE Config file conf/conf.properties doesn't exists.
117
         * > FINE Default property file /root/.JSignPdf doesn't exists.
118
         */
119
        private function getHome(): string {
120
                $configuredHome = $this->getConfiguredHome();
2✔
121
                if ($configuredHome !== null) {
2✔
122
                        return $configuredHome;
2✔
123
                }
124

125
                $tempFolder = $this->createJSignPdfTempFolder();
×
126
                $this->initializeJSignPdfConfigurationFiles($tempFolder);
×
127
                return $tempFolder;
×
128
        }
129

130
        private function getConfiguredHome(): ?string {
131
                $jSignPdfHome = $this->appConfig->getValueString(Application::APP_ID, 'jsignpdf_home', '');
2✔
132
                if ($jSignPdfHome && is_dir($jSignPdfHome)) {
2✔
133
                        return $jSignPdfHome;
2✔
134
                }
135
                return null;
×
136
        }
137

138
        private function createJSignPdfTempFolder(): string {
139
                $jsignpdfTempFolder = $this->tempManager->getTemporaryFolder('jsignpdf');
×
140
                if (!$jsignpdfTempFolder) {
×
141
                        throw new \Exception('Temporary file not accessible');
×
142
                }
143
                mkdir(
×
144
                        directory: $jsignpdfTempFolder . '/conf',
×
145
                        recursive: true
×
146
                );
×
147
                return $jsignpdfTempFolder;
×
148
        }
149

150
        private function initializeJSignPdfConfigurationFiles(string $folder): void {
151
                $this->createEmptyFile($folder . '/conf/conf.properties');
×
152
                $this->createEmptyFile($folder . '/.JSignPdf');
×
153
        }
154

155
        private function createEmptyFile(string $path): void {
156
                $file = fopen($path, 'w');
×
157
                fclose($file);
×
158
        }
159

160
        private function getHashAlgorithm(string $pdfContent): string {
161
                $configuredAlgorithm = $this->appConfig->getValueString(Application::APP_ID, 'signature_hash_algorithm', 'SHA256');
×
162
                /**
163
                 * Need to respect the follow code:
164
                 * https://github.com/intoolswetrust/jsignpdf/blob/JSignPdf_2_2_2/jsignpdf/src/main/java/net/sf/jsignpdf/types/HashAlgorithm.java#L46-L47
165
                 */
166
                $pdfVersion = $this->extractPdfVersion($pdfContent);
×
167

168
                if ($pdfVersion === null) {
×
169
                        return $this->validateHashAlgorithm($configuredAlgorithm);
×
170
                }
171

172
                return $this->getHashAlgorithmForPdfVersion($pdfVersion, $configuredAlgorithm);
×
173
        }
174

175
        private function extractPdfVersion(string $content): ?float {
176
                if (!preg_match('/^%PDF-(?<version>\d+(\.\d+)?)/', $content, $match)) {
×
177
                        return null;
×
178
                }
179
                return (float)$match['version'];
×
180
        }
181

182
        private function getHashAlgorithmForPdfVersion(float $pdfVersion, string $configuredAlgorithm): string {
183
                if ($pdfVersion < 1.6) {
×
184
                        return 'SHA1';
×
185
                }
186
                if ($pdfVersion < self::MIN_PDF_VERSION_SHA1_REJECT) {
×
187
                        return 'SHA256';
×
188
                }
189
                if ($pdfVersion >= self::MIN_PDF_VERSION_SHA1_REJECT && $configuredAlgorithm === 'SHA1') {
×
190
                        return 'SHA256';
×
191
                }
192
                return $this->validateHashAlgorithm($configuredAlgorithm);
×
193
        }
194

195
        private function validateHashAlgorithm(string $algorithm): string {
196
                $supportedAlgorithms = ['SHA1', 'SHA256', 'SHA384', 'SHA512', 'RIPEMD160'];
×
197
                return in_array($algorithm, $supportedAlgorithms) ? $algorithm : 'SHA256';
×
198
        }
199

200
        /**
201
         * Normalizes very old PDFs (1.0/1.1) to 1.3.
202
         * Rationale: JSignPDF enum PdfVersion only defines 1.2+; for 1.0/1.1,
203
         * PdfVersion.fromCharVersion(...) returns null and SignerLogic.signFile() NPEs.
204
         * See JSignPDF 2.3.0 sources: types/PdfVersion.java and SignerLogic.signFile().
205
         */
206
        private function normalizePdfVersion(string $content): string {
207
                $version = $this->extractPdfVersion($content);
×
208
                if ($version === null) {
×
209
                        return $content;
×
210
                }
211

212
                // Convert very old PDFs (< 1.2) to 1.3 to avoid JSignPDF NullPointerException
213
                if ($this->isVeryOldPdfVersion($version)) {
×
214
                        return $this->replacePdfVersion($content, self::TARGET_OLD_PDF_VERSION);
×
215
                }
216

217
                // Convert PDFs < 1.6 to 1.6 if using SHA-256 (the default hash algorithm)
218
                // This prevents "The chosen hash algorithm (SHA-256) requires a newer PDF version" error
219
                if ($this->requiresPdfVersionUpgradeForSha256($version)) {
×
220
                        return $this->replacePdfVersion($content, self::TARGET_PDF_VERSION_SHA256);
×
221
                }
222

223
                return $content;
×
224
        }
225

226
        private function isVeryOldPdfVersion(float $version): bool {
227
                return $version > 0 && $version < self::MIN_PDF_VERSION;
×
228
        }
229

230
        private function requiresPdfVersionUpgradeForSha256(float $version): bool {
231
                if ($version >= self::MIN_PDF_VERSION_SHA256) {
×
232
                        return false;
×
233
                }
234
                $hashAlgorithm = $this->appConfig->getValueString(Application::APP_ID, 'signature_hash_algorithm', 'SHA256');
×
235
                return $hashAlgorithm === 'SHA256';
×
236
        }
237

238
        private function replacePdfVersion(string $content, string $newVersion): string {
239
                return (string)preg_replace('/^%PDF-\d+(\.\d+)?/', '%PDF-' . $newVersion, $content, 1);
×
240
        }
241

242
        private function getCertificationLevel(): ?string {
243
                if (!$this->docMdpConfigService->isEnabled()) {
3✔
244
                        return null;
3✔
245
                }
246

247
                return $this->docMdpConfigService->getLevel()->name;
×
248
        }
249

250
        #[\Override]
251
        public function sign(): File {
252
                $this->beforeSign();
×
253

254
                $signedContent = $this->getSignedContent();
×
255
                $this->getInputFile()->putContent($signedContent);
×
256
                return $this->getInputFile();
×
257
        }
258

259
        #[\Override]
260
        public function getSignedContent(): string {
261
                $normalizedPdf = $this->normalizePdfVersion($this->getInputFile()->getContent());
×
262
                $hashAlgorithm = $this->getHashAlgorithm($normalizedPdf);
×
263
                $param = $this->getJSignParam();
×
264
                $param->setJSignParameters(
×
265
                        $param->getJSignParameters()
×
266
                        . $this->listParamsToString($this->getTsaParameters())
×
267
                );
×
268
                $param->setCertificate($this->getCertificate())
×
269
                        ->setPdf($normalizedPdf)
×
270
                        ->setPassword($this->getPassword());
×
271

272
                $signed = $this->signUsingVisibleElements($normalizedPdf, $hashAlgorithm);
×
273
                if ($signed) {
×
274
                        return $signed;
×
275
                }
276

277
                $param->setJSignParameters(
×
278
                        $param->getJSignParameters()
×
279
                        . $this->listParamsToString([
×
280
                                '--hash-algorithm' => $hashAlgorithm,
×
281
                        ])
×
282
                );
×
283
                $jSignPdf = $this->getJSignPdf();
×
284
                $jSignPdf->setParam($param);
×
285
                return $this->signWrapper($jSignPdf);
×
286
        }
287

288
        private function signUsingVisibleElements(string $normalizedPdf, string $hashAlgorithm): string {
289
                $visibleElements = $this->getVisibleElements();
×
290
                if ($visibleElements) {
×
291
                        $jSignPdf = $this->getJSignPdf();
×
292

293
                        $renderMode = $this->signatureTextService->getRenderMode();
×
294

295
                        $params = [
×
296
                                '--l2-text' => $this->getSignatureText(),
×
297
                                '-V' => null,
×
298
                        ];
×
299

300
                        // When l2-text is empty, add hash-algorithm at the beginning
301
                        if ($params['--l2-text'] === '""') {
×
302
                                $params = [
×
303
                                        '--hash-algorithm' => $hashAlgorithm,
×
304
                                        '--l2-text' => $params['--l2-text'],
×
305
                                        '-V' => null,
×
306
                                ];
×
307
                        }
308

309
                        $fontSize = $this->parseSignatureText()['templateFontSize'];
×
310
                        if ($fontSize === self::SIGNATURE_DEFAULT_FONT_SIZE || !$fontSize || $params['--l2-text'] === '""') {
×
311
                                $fontSize = 0;
×
312
                        }
313

314
                        $backgroundType = $this->signatureBackgroundService->getSignatureBackgroundType();
×
315
                        if ($backgroundType !== 'deleted') {
×
316
                                $backgroundPath = $this->signatureBackgroundService->getImagePath();
×
317
                        } else {
318
                                $backgroundPath = '';
×
319
                        }
320

321
                        $param = $this->getJSignParam();
×
322
                        $originalParam = clone $param;
×
323

324
                        foreach ($visibleElements as $element) {
×
325
                                $params['-pg'] = $element->getFileElement()->getPage();
×
326
                                if ($params['-pg'] <= self::PAGE_FIRST) {
×
327
                                        unset($params['-pg']);
×
328
                                }
329
                                $params['-llx'] = $element->getFileElement()->getLlx();
×
330
                                $params['-lly'] = $element->getFileElement()->getLly();
×
331
                                $params['-urx'] = $element->getFileElement()->getUrx();
×
332
                                $params['-ury'] = $element->getFileElement()->getUry();
×
333

334
                                $scaleFactor = $this->getScaleFactor($params['-urx'] - $params['-llx']);
×
335
                                if ($fontSize) {
×
336
                                        $params['--font-size'] = $fontSize * $scaleFactor;
×
337
                                }
338

NEW
339
                                $backgroundPathForElement = $backgroundPath
×
NEW
340
                                        ? $this->prepareBackgroundForPdf($backgroundPath, $this->normalizeScaleFactor($scaleFactor))
×
NEW
341
                                        : '';
×
342

343
                                $signatureImagePath = $element->getTempFile();
×
344
                                if ($backgroundType === 'deleted') {
×
345
                                        if ($renderMode === SignerElementsService::RENDER_MODE_SIGNAME_AND_DESCRIPTION) {
×
346
                                                $params['--render-mode'] = SignerElementsService::RENDER_MODE_GRAPHIC_AND_DESCRIPTION;
×
347
                                                $params['--img-path'] = $this->createTextImage(
×
348
                                                        width: ($params['-urx'] - $params['-llx']),
×
349
                                                        height: ($params['-ury'] - $params['-lly']),
×
350
                                                        fontSize: $this->signatureTextService->getSignatureFontSize() * $scaleFactor,
×
351
                                                        scaleFactor: $this->normalizeScaleFactor($scaleFactor),
×
352
                                                );
×
353
                                        } elseif ($signatureImagePath) {
×
354
                                                $params['--bg-path'] = $signatureImagePath;
×
355
                                        }
356
                                } elseif ($params['--l2-text'] === '""') {
×
NEW
357
                                        if ($backgroundPathForElement) {
×
358
                                                $params['--bg-path'] = $this->mergeBackgroundWithSignature(
×
NEW
359
                                                        $backgroundPathForElement,
×
360
                                                        $signatureImagePath,
×
361
                                                        $this->normalizeScaleFactor($scaleFactor),
×
362
                                                );
×
363
                                        } else {
364
                                                $params['--bg-path'] = $signatureImagePath;
×
365
                                        }
366
                                } else {
367
                                        if ($renderMode === SignerElementsService::RENDER_MODE_GRAPHIC_AND_DESCRIPTION) {
×
368
                                                $params['--render-mode'] = SignerElementsService::RENDER_MODE_GRAPHIC_AND_DESCRIPTION;
×
NEW
369
                                                $params['--bg-path'] = $backgroundPathForElement;
×
370
                                                $params['--img-path'] = $signatureImagePath;
×
371
                                        } elseif ($renderMode === SignerElementsService::RENDER_MODE_SIGNAME_AND_DESCRIPTION) {
×
372
                                                $params['--render-mode'] = SignerElementsService::RENDER_MODE_GRAPHIC_AND_DESCRIPTION;
×
NEW
373
                                                $params['--bg-path'] = $backgroundPathForElement;
×
374
                                                $params['--img-path'] = $this->createTextImage(
×
375
                                                        width: (int)(($params['-urx'] - $params['-llx']) / 2),
×
376
                                                        height: $params['-ury'] - $params['-lly'],
×
377
                                                        fontSize: $this->signatureTextService->getSignatureFontSize() * $scaleFactor,
×
378
                                                        scaleFactor: $this->normalizeScaleFactor($scaleFactor),
×
379
                                                );
×
380

381
                                        } else {
NEW
382
                                                $params['--bg-path'] = $backgroundPathForElement;
×
383
                                        }
384
                                }
385

386
                                // Only add hash-algorithm at the end if l2-text is not empty
387
                                if ($params['--l2-text'] !== '""') {
×
388
                                        $params['--hash-algorithm'] = $hashAlgorithm;
×
389
                                }
390

391
                                $param->setJSignParameters(
×
392
                                        $originalParam->getJSignParameters()
×
393
                                        . $this->listParamsToString($params)
×
394
                                );
×
395
                                $param->setPdf($normalizedPdf);
×
396
                                $jSignPdf->setParam($param);
×
397
                                $signed = $this->signWrapper($jSignPdf);
×
398
                                $normalizedPdf = $signed;
×
399
                        }
400
                        return $signed;
×
401
                }
402
                return '';
×
403
        }
404

405
        private function getScaleFactor(float $width): float {
406
                $systemWidth = $this->signatureTextService->getFullSignatureWidth();
×
407
                if (!$systemWidth) {
×
408
                        return 1;
×
409
                }
410
                return $width / $systemWidth;
×
411
        }
412

413
        private function normalizeScaleFactor(float $scaleFactor): float {
414
                return max($scaleFactor, self::SCALE_FACTOR_MIN);
×
415
        }
416

417

418
        #[\Override]
419
        public function readCertificate(): array {
420
                $result = $this->certificateEngineFactory
×
421
                        ->getEngine()
×
422
                        ->readCertificate(
×
423
                                $this->getCertificate(),
×
424
                                $this->getPassword()
×
425
                        );
×
426

427
                if (!is_array($result)) {
×
428
                        throw new \RuntimeException('Failed to read certificate data');
×
429
                }
430

431
                return $result;
×
432
        }
433

434
        private function createTextImage(int $width, int $height, float $fontSize, float $scaleFactor): string {
435
                $params = $this->getSignatureParams();
×
436
                if (!empty($params['SignerCommonName'])) {
×
437
                        $commonName = $params['SignerCommonName'];
×
438
                } else {
439
                        $certificateData = $this->readCertificate();
×
440
                        $commonName = $certificateData['subject']['CN'] ?? throw new \RuntimeException('Certificate must have a Common Name (CN) in subject field');
×
441
                }
442
                $content = $this->signatureTextService->signerNameImage(
×
443
                        width: $width,
×
444
                        height: $height,
×
445
                        text: $commonName,
×
446
                        fontSize: $fontSize,
×
447
                        scale: $scaleFactor,
×
448
                );
×
449

450
                $tmpPath = $this->tempManager->getTemporaryFile('_text_image.png');
×
451
                if (!$tmpPath) {
×
452
                        throw new \Exception('Temporary file not accessible');
×
453
                }
454
                file_put_contents($tmpPath, $content);
×
455
                return $tmpPath;
×
456
        }
457

458
        private function mergeBackgroundWithSignature(string $backgroundPath, string $signaturePath, float $scaleFactor): string {
459
                if (!extension_loaded('imagick')) {
×
460
                        throw new \Exception('Extension imagick is not loaded.');
×
461
                }
462
                $baseWidth = $this->signatureTextService->getFullSignatureWidth();
×
463
                $baseHeight = $this->signatureTextService->getFullSignatureHeight();
×
464

465
                $canvasWidth = round($baseWidth * $scaleFactor);
×
466
                $canvasHeight = round($baseHeight * $scaleFactor);
×
467

468
                $background = new Imagick($backgroundPath);
×
469
                $signature = new Imagick($signaturePath);
×
470

471
                $background->setImageFormat('png');
×
472
                $signature->setImageFormat('png');
×
473

474
                $background->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
475
                $signature->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
476

477
                $background->resizeImage(
×
NEW
478
                        (int)$canvasWidth,
×
NEW
479
                        (int)$canvasHeight,
×
480
                        Imagick::FILTER_LANCZOS,
×
NEW
481
                        1,
×
NEW
482
                        true
×
483
                );
×
484

485
                $signature->resizeImage(
×
486
                        (int)round($signature->getImageWidth() * $scaleFactor),
×
487
                        (int)round($signature->getImageHeight() * $scaleFactor),
×
488
                        Imagick::FILTER_LANCZOS,
×
489
                        1
×
490
                );
×
491

492
                $canvas = new Imagick();
×
493
                $canvas->newImage((int)$canvasWidth, (int)$canvasHeight, new ImagickPixel('transparent'));
×
494
                $canvas->setImageFormat('png32');
×
495
                $canvas->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
496

497
                $bgX = (int)(($canvasWidth - $background->getImageWidth()) / 2);
×
498
                $bgY = (int)(($canvasHeight - $background->getImageHeight()) / 2);
×
499
                $canvas->compositeImage($background, Imagick::COMPOSITE_OVER, $bgX, $bgY);
×
500

501
                $sigX = (int)(($canvasWidth - $signature->getImageWidth()) / 2);
×
502
                $sigY = (int)(($canvasHeight - $signature->getImageHeight()) / 2);
×
503
                $canvas->compositeImage($signature, Imagick::COMPOSITE_OVER, $sigX, $sigY);
×
504

505
                $tmpPath = $this->tempManager->getTemporaryFile('_merged.png');
×
506
                if (!$tmpPath) {
×
507
                        throw new \Exception('Temporary file not accessible');
×
508
                }
509
                $canvas->writeImage($tmpPath);
×
510

511
                $canvas->clear();
×
512
                $background->clear();
×
513
                $signature->clear();
×
514

515
                return $tmpPath;
×
516
        }
517

518
        private function prepareBackgroundForPdf(string $backgroundPath, float $scaleFactor): string {
NEW
519
                if (!extension_loaded('imagick')) {
×
NEW
520
                        throw new \Exception('Extension imagick is not loaded.');
×
521
                }
NEW
522
                $baseWidth = $this->signatureTextService->getFullSignatureWidth();
×
NEW
523
                $baseHeight = $this->signatureTextService->getFullSignatureHeight();
×
524

NEW
525
                $canvasWidth = (int)round($baseWidth * $scaleFactor);
×
NEW
526
                $canvasHeight = (int)round($baseHeight * $scaleFactor);
×
527

NEW
528
                $background = new Imagick($backgroundPath);
×
NEW
529
                $background->setImageFormat('png');
×
NEW
530
                $background->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
NEW
531
                $background->resizeImage(
×
NEW
532
                        $canvasWidth,
×
NEW
533
                        $canvasHeight,
×
NEW
534
                        Imagick::FILTER_LANCZOS,
×
NEW
535
                        1,
×
NEW
536
                        true
×
NEW
537
                );
×
538

NEW
539
                $canvas = new Imagick();
×
NEW
540
                $canvas->newImage($canvasWidth, $canvasHeight, new ImagickPixel('transparent'));
×
NEW
541
                $canvas->setImageFormat('png32');
×
NEW
542
                $canvas->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
543

NEW
544
                $bgX = (int)(($canvasWidth - $background->getImageWidth()) / 2);
×
NEW
545
                $bgY = (int)(($canvasHeight - $background->getImageHeight()) / 2);
×
NEW
546
                $canvas->compositeImage($background, Imagick::COMPOSITE_OVER, $bgX, $bgY);
×
547

NEW
548
                $tmpPath = $this->tempManager->getTemporaryFile('_background.png');
×
NEW
549
                if (!$tmpPath) {
×
NEW
550
                        throw new \Exception('Temporary file not accessible');
×
551
                }
NEW
552
                $canvas->writeImage($tmpPath);
×
553

NEW
554
                $canvas->clear();
×
NEW
555
                $background->clear();
×
556

NEW
557
                return $tmpPath;
×
558
        }
559

560
        private function parseSignatureText(): array {
561
                if (!$this->parsedSignatureText) {
5✔
562
                        $params = $this->getSignatureParams();
5✔
563
                        $params['ServerSignatureDate'] = '${timestamp}';
5✔
564
                        $this->parsedSignatureText = $this->signatureTextService->parse(context: $params);
5✔
565
                }
566
                return $this->parsedSignatureText;
5✔
567
        }
568

569
        public function getSignatureText(): string {
570
                $renderMode = $this->signatureTextService->getRenderMode();
10✔
571
                if ($renderMode !== 'GRAPHIC_ONLY') {
10✔
572
                        $data = $this->parseSignatureText();
5✔
573
                        $signatureText = '"' . str_replace(
5✔
574
                                ['"', '$'],
5✔
575
                                ['\"', '\$'],
5✔
576
                                $data['parsed']
5✔
577
                        ) . '"';
5✔
578
                } else {
579
                        $signatureText = '""';
5✔
580
                }
581

582
                return $signatureText;
10✔
583
        }
584

585
        private function listParamsToString(array $params): string {
586
                $paramString = '';
×
587
                foreach ($params as $flag => $value) {
×
588
                        $paramString .= ' ' . $flag;
×
589
                        if ($value !== null && $value !== '') {
×
590
                                $paramString .= ' ' . $value;
×
591
                        }
592
                }
593
                return $paramString;
×
594
        }
595

596
        private function getTsaParameters(): array {
597
                $tsaUrl = $this->appConfig->getValueString(Application::APP_ID, 'tsa_url', '');
×
598
                if (empty($tsaUrl)) {
×
599
                        return [];
×
600
                }
601

602
                $params = [
×
603
                        '--tsa-server-url' => $tsaUrl,
×
604
                        '--tsa-policy-oid' => $this->appConfig->getValueString(Application::APP_ID, 'tsa_policy_oid', ''),
×
605
                ];
×
606

607
                if (!$params['--tsa-policy-oid']) {
×
608
                        unset($params['--tsa-policy-oid']);
×
609
                }
610

611
                $tsaAuthType = $this->appConfig->getValueString(Application::APP_ID, 'tsa_auth_type', 'none');
×
612
                if ($tsaAuthType === 'basic') {
×
613
                        $tsaUsername = $this->appConfig->getValueString(Application::APP_ID, 'tsa_username', '');
×
614
                        $tsaPassword = $this->appConfig->getValueString(Application::APP_ID, 'tsa_password', '');
×
615

616
                        if (!empty($tsaUsername) && !empty($tsaPassword)) {
×
617
                                $params['--tsa-authentication'] = 'PASSWORD';
×
618
                                $params['--tsa-user'] = $tsaUsername;
×
619
                                $params['--tsa-password'] = $tsaPassword;
×
620
                        }
621
                }
622

623
                return $params;
×
624
        }
625

626
        private function signWrapper(JSignPDF $jSignPDF): string {
627
                try {
628
                        return $jSignPDF->sign();
×
629
                } catch (\Throwable $th) {
×
630
                        $errorMessage = $th->getMessage();
×
631

632
                        $this->checkTsaError($errorMessage);
×
633
                        $this->checkHashAlgorithmError($errorMessage);
×
634

635
                        $this->logger->error('Error at JSignPdf side. LibreSign can not do nothing. Follow the error message: ' . $errorMessage);
×
636
                        throw new \Exception($errorMessage);
×
637
                }
638
        }
639

640
        private function checkTsaError(string $errorMessage): void {
641
                $tsaErrors = ['TSAClientBouncyCastle', 'UnknownHostException', 'Invalid TSA'];
×
642
                $isTsaError = false;
×
643
                foreach ($tsaErrors as $error) {
×
644
                        if (str_contains($errorMessage, $error)) {
×
645
                                $isTsaError = true;
×
646
                                break;
×
647
                        }
648
                }
649

650
                if ($isTsaError) {
×
651
                        if (str_contains($errorMessage, 'Invalid TSA') && preg_match("/Invalid TSA '([^']+)'/", $errorMessage, $matches)) {
×
652
                                $friendlyMessage = 'Timestamp Authority (TSA) service is unavailable or misconfigured: ' . $matches[1];
×
653
                        } else {
654
                                $friendlyMessage = 'Timestamp Authority (TSA) service error.' . "\n"
×
655
                                        . 'Please check the TSA configuration.';
×
656
                        }
657
                        throw new LibresignException($friendlyMessage);
×
658
                }
659
        }
660

661
        private function checkHashAlgorithmError(string $errorMessage): void {
662
                $rows = str_getcsv($errorMessage);
×
663
                $hashAlgorithm = array_filter($rows, fn ($r) => str_contains((string)$r, 'The chosen hash algorithm'));
×
664

665
                if (!empty($hashAlgorithm)) {
×
666
                        $hashAlgorithm = current($hashAlgorithm);
×
667
                        $hashAlgorithm = trim((string)$hashAlgorithm, 'INFO ');
×
668
                        $hashAlgorithm = str_replace('\"', '"', $hashAlgorithm);
×
669
                        $hashAlgorithm = preg_replace('/\.( )/', ".\n", $hashAlgorithm);
×
670
                        throw new LibresignException($hashAlgorithm);
×
671
                }
672
        }
673
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc