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

LibreSign / libresign / 21804829862

08 Feb 2026 08:27PM UTC coverage: 47.842%. First build
21804829862

Pull #6784

github

web-flow
Merge b32e4e5e7 into 87b6b7bcf
Pull Request #6784: fix: docmdp certification level and visibility

45 of 61 new or added lines in 3 files covered. (73.77%)

8325 of 17401 relevant lines covered (47.84%)

5.38 hits per line

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

12.17
/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
                return $this->jSignParam;
3✔
102
        }
103

104
        private function getEnvironments(): string {
105
                return 'JSIGNPDF_HOME=' . escapeshellarg($this->getHome()) . ' ';
2✔
106
        }
107

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

120
                $tempFolder = $this->createJSignPdfTempFolder();
×
121
                $this->initializeJSignPdfConfigurationFiles($tempFolder);
×
122
                return $tempFolder;
×
123
        }
124

125
        private function getConfiguredHome(): ?string {
126
                $jSignPdfHome = $this->appConfig->getValueString(Application::APP_ID, 'jsignpdf_home', '');
2✔
127
                if ($jSignPdfHome && is_dir($jSignPdfHome)) {
2✔
128
                        return $jSignPdfHome;
2✔
129
                }
130
                return null;
×
131
        }
132

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

145
        private function initializeJSignPdfConfigurationFiles(string $folder): void {
146
                $this->createEmptyFile($folder . '/conf/conf.properties');
×
147
                $this->createEmptyFile($folder . '/.JSignPdf');
×
148
        }
149

150
        private function createEmptyFile(string $path): void {
151
                $file = fopen($path, 'w');
×
152
                fclose($file);
×
153
        }
154

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

163
                if ($pdfVersion === null) {
×
164
                        return $this->validateHashAlgorithm($configuredAlgorithm);
×
165
                }
166

167
                return $this->getHashAlgorithmForPdfVersion($pdfVersion, $configuredAlgorithm);
×
168
        }
169

170
        private function extractPdfVersion(string $content): ?float {
171
                if (!preg_match('/^%PDF-(?<version>\d+(\.\d+)?)/', $content, $match)) {
×
172
                        return null;
×
173
                }
174
                return (float)$match['version'];
×
175
        }
176

177
        private function getHashAlgorithmForPdfVersion(float $pdfVersion, string $configuredAlgorithm): string {
178
                if ($pdfVersion < 1.6) {
×
179
                        return 'SHA1';
×
180
                }
181
                if ($pdfVersion < self::MIN_PDF_VERSION_SHA1_REJECT) {
×
182
                        return 'SHA256';
×
183
                }
184
                if ($pdfVersion >= self::MIN_PDF_VERSION_SHA1_REJECT && $configuredAlgorithm === 'SHA1') {
×
185
                        return 'SHA256';
×
186
                }
187
                return $this->validateHashAlgorithm($configuredAlgorithm);
×
188
        }
189

190
        private function validateHashAlgorithm(string $algorithm): string {
191
                $supportedAlgorithms = ['SHA1', 'SHA256', 'SHA384', 'SHA512', 'RIPEMD160'];
×
192
                return in_array($algorithm, $supportedAlgorithms) ? $algorithm : 'SHA256';
×
193
        }
194

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

207
                // Convert very old PDFs (< 1.2) to 1.3 to avoid JSignPDF NullPointerException
208
                if ($this->isVeryOldPdfVersion($version)) {
×
209
                        return $this->replacePdfVersion($content, self::TARGET_OLD_PDF_VERSION);
×
210
                }
211

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

218
                return $content;
×
219
        }
220

221
        private function isVeryOldPdfVersion(float $version): bool {
222
                return $version > 0 && $version < self::MIN_PDF_VERSION;
×
223
        }
224

225
        private function requiresPdfVersionUpgradeForSha256(float $version): bool {
226
                if ($version >= self::MIN_PDF_VERSION_SHA256) {
×
227
                        return false;
×
228
                }
229
                $hashAlgorithm = $this->appConfig->getValueString(Application::APP_ID, 'signature_hash_algorithm', 'SHA256');
×
230
                return $hashAlgorithm === 'SHA256';
×
231
        }
232

233
        private function replacePdfVersion(string $content, string $newVersion): string {
234
                return (string)preg_replace('/^%PDF-\d+(\.\d+)?/', '%PDF-' . $newVersion, $content, 1);
×
235
        }
236

237
        private function getCertificationLevel(): ?string {
238
                if (!$this->docMdpConfigService->isEnabled()) {
×
239
                        return null;
×
240
                }
241

242
                return $this->docMdpConfigService->getLevel()->name;
×
243
        }
244

245
        #[\Override]
246
        public function sign(): File {
247
                $this->beforeSign();
×
248

249
                $signedContent = $this->getSignedContent();
×
250
                $this->getInputFile()->putContent($signedContent);
×
251
                return $this->getInputFile();
×
252
        }
253

254
        #[\Override]
255
        public function getSignedContent(): string {
256
                $normalizedPdf = $this->normalizePdfVersion($this->getInputFile()->getContent());
×
257
                $hashAlgorithm = $this->getHashAlgorithm($normalizedPdf);
×
258
                $param = $this->getJSignParam();
×
259

NEW
260
                $tsaParams = $this->listParamsToString($this->getTsaParameters());
×
261

NEW
262
                $visibleElements = $this->getVisibleElements();
×
NEW
263
                $certParams = '';
×
NEW
264
                $certificationLevel = $this->getCertificationLevel();
×
NEW
265
                if ($certificationLevel !== null && !$visibleElements && !$this->hasExistingSignatures($normalizedPdf)) {
×
NEW
266
                        $certParams = ' -cl ' . $certificationLevel;
×
267
                }
268

269
                $param->setJSignParameters(
×
270
                        $param->getJSignParameters()
×
NEW
271
                        . $certParams
×
NEW
272
                        . $tsaParams
×
273
                );
×
274
                $param->setCertificate($this->getCertificate())
×
275
                        ->setPdf($normalizedPdf)
×
276
                        ->setPassword($this->getPassword());
×
277

278
                $signed = $this->signUsingVisibleElements($normalizedPdf, $hashAlgorithm);
×
279
                if ($signed) {
×
280
                        return $signed;
×
281
                }
282

283
                $param->setJSignParameters(
×
284
                        $param->getJSignParameters()
×
285
                        . $this->listParamsToString([
×
286
                                '--hash-algorithm' => $hashAlgorithm,
×
287
                        ])
×
288
                );
×
289
                $jSignPdf = $this->getJSignPdf();
×
290
                $jSignPdf->setParam($param);
×
291
                return $this->signWrapper($jSignPdf);
×
292
        }
293

294
        private function signUsingVisibleElements(string $normalizedPdf, string $hashAlgorithm): string {
295
                $visibleElements = $this->getVisibleElements();
×
296
                if ($visibleElements) {
×
297
                        $jSignPdf = $this->getJSignPdf();
×
298

299
                        $renderMode = $this->signatureTextService->getRenderMode();
×
300

301
                        $params = [
×
302
                                '--l2-text' => $this->getSignatureText(),
×
303
                                '-V' => null,
×
304
                        ];
×
305

306
                        // When l2-text is empty, add hash-algorithm at the beginning
307
                        if ($params['--l2-text'] === '""') {
×
308
                                $params = [
×
309
                                        '--hash-algorithm' => $hashAlgorithm,
×
310
                                        '--l2-text' => $params['--l2-text'],
×
311
                                        '-V' => null,
×
312
                                ];
×
313
                        }
314

315
                        $fontSize = $this->parseSignatureText()['templateFontSize'];
×
316
                        if ($fontSize === self::SIGNATURE_DEFAULT_FONT_SIZE || !$fontSize || $params['--l2-text'] === '""') {
×
317
                                $fontSize = 0;
×
318
                        }
319

320
                        $backgroundType = $this->signatureBackgroundService->getSignatureBackgroundType();
×
321
                        if ($backgroundType !== 'deleted') {
×
322
                                $backgroundPath = $this->signatureBackgroundService->getImagePath();
×
323
                        } else {
324
                                $backgroundPath = '';
×
325
                        }
326

NEW
327
                        $certificationLevel = $this->getCertificationLevel();
×
NEW
328
                        $applyCertification = $certificationLevel !== null && !$this->hasExistingSignatures($normalizedPdf);
×
NEW
329
                        $certParams = $applyCertification ? ' -cl ' . $certificationLevel : '';
×
NEW
330
                        $elementIndex = 0;
×
331

332
                        $param = $this->getJSignParam();
×
333
                        $originalParam = clone $param;
×
334

335
                        foreach ($visibleElements as $element) {
×
NEW
336
                                $elementIndex++;
×
337
                                $params['-pg'] = $element->getFileElement()->getPage();
×
338
                                if ($params['-pg'] <= self::PAGE_FIRST) {
×
339
                                        unset($params['-pg']);
×
340
                                }
341
                                $params['-llx'] = $element->getFileElement()->getLlx();
×
342
                                $params['-lly'] = $element->getFileElement()->getLly();
×
343
                                $params['-urx'] = $element->getFileElement()->getUrx();
×
344
                                $params['-ury'] = $element->getFileElement()->getUry();
×
345

346
                                $scaleFactor = $this->getScaleFactor($params['-urx'] - $params['-llx']);
×
347
                                if ($fontSize) {
×
348
                                        $params['--font-size'] = $fontSize * $scaleFactor;
×
349
                                }
350

351
                                $backgroundPathForElement = $backgroundPath
×
352
                                        ? $this->prepareBackgroundForPdf($backgroundPath, $this->normalizeScaleFactor($scaleFactor))
×
353
                                        : '';
×
354

355
                                $signatureImagePath = $element->getTempFile();
×
356
                                if ($backgroundType === 'deleted') {
×
357
                                        if ($renderMode === SignerElementsService::RENDER_MODE_SIGNAME_AND_DESCRIPTION) {
×
358
                                                $params['--render-mode'] = SignerElementsService::RENDER_MODE_GRAPHIC_AND_DESCRIPTION;
×
359
                                                $params['--img-path'] = $this->createTextImage(
×
360
                                                        width: ($params['-urx'] - $params['-llx']),
×
361
                                                        height: ($params['-ury'] - $params['-lly']),
×
362
                                                        fontSize: $this->signatureTextService->getSignatureFontSize() * $scaleFactor,
×
363
                                                        scaleFactor: $this->normalizeScaleFactor($scaleFactor),
×
364
                                                );
×
365
                                        } elseif ($signatureImagePath) {
×
366
                                                $params['--bg-path'] = $signatureImagePath;
×
367
                                        }
368
                                } elseif ($params['--l2-text'] === '""') {
×
369
                                        if ($backgroundPathForElement) {
×
370
                                                $params['--bg-path'] = $this->mergeBackgroundWithSignature(
×
371
                                                        $backgroundPathForElement,
×
372
                                                        $signatureImagePath,
×
373
                                                        $this->normalizeScaleFactor($scaleFactor),
×
374
                                                );
×
375
                                        } else {
376
                                                $params['--bg-path'] = $signatureImagePath;
×
377
                                        }
378
                                } else {
379
                                        if ($renderMode === SignerElementsService::RENDER_MODE_GRAPHIC_AND_DESCRIPTION) {
×
380
                                                $params['--render-mode'] = SignerElementsService::RENDER_MODE_GRAPHIC_AND_DESCRIPTION;
×
381
                                                $params['--bg-path'] = $backgroundPathForElement;
×
382
                                                $params['--img-path'] = $signatureImagePath;
×
383
                                        } elseif ($renderMode === SignerElementsService::RENDER_MODE_SIGNAME_AND_DESCRIPTION) {
×
384
                                                $params['--render-mode'] = SignerElementsService::RENDER_MODE_GRAPHIC_AND_DESCRIPTION;
×
385
                                                $params['--bg-path'] = $backgroundPathForElement;
×
386
                                                $params['--img-path'] = $this->createTextImage(
×
387
                                                        width: (int)(($params['-urx'] - $params['-llx']) / 2),
×
388
                                                        height: $params['-ury'] - $params['-lly'],
×
389
                                                        fontSize: $this->signatureTextService->getSignatureFontSize() * $scaleFactor,
×
390
                                                        scaleFactor: $this->normalizeScaleFactor($scaleFactor),
×
391
                                                );
×
392

393
                                        } else {
394
                                                $params['--bg-path'] = $backgroundPathForElement;
×
395
                                        }
396
                                }
397

398
                                // Only add hash-algorithm at the end if l2-text is not empty
399
                                if ($params['--l2-text'] !== '""') {
×
400
                                        $params['--hash-algorithm'] = $hashAlgorithm;
×
401
                                }
402

NEW
403
                                $elementCertParams = ($applyCertification && $elementIndex === 1) ? $certParams : '';
×
404
                                $param->setJSignParameters(
×
405
                                        $originalParam->getJSignParameters()
×
NEW
406
                                        . $elementCertParams
×
407
                                        . $this->listParamsToString($params)
×
408
                                );
×
409
                                $param->setPdf($normalizedPdf);
×
410
                                $jSignPdf->setParam($param);
×
411
                                $signed = $this->signWrapper($jSignPdf);
×
412
                                $normalizedPdf = $signed;
×
413
                        }
414
                        return $signed;
×
415
                }
416
                return '';
×
417
        }
418

419
        private function hasExistingSignatures(string $pdfContent): bool {
NEW
420
                return (bool)preg_match('/\/ByteRange\s*\[|\/Type\s*\/Sig\b|\/DocMDP\b|\/Perms\b/', $pdfContent);
×
421
        }
422

423
        private function getScaleFactor(float $width): float {
424
                $systemWidth = $this->signatureTextService->getFullSignatureWidth();
×
425
                if (!$systemWidth) {
×
426
                        return 1;
×
427
                }
428
                return $width / $systemWidth;
×
429
        }
430

431
        private function normalizeScaleFactor(float $scaleFactor): float {
432
                return max($scaleFactor, self::SCALE_FACTOR_MIN);
×
433
        }
434

435

436
        #[\Override]
437
        public function readCertificate(): array {
438
                $result = $this->certificateEngineFactory
×
439
                        ->getEngine()
×
440
                        ->readCertificate(
×
441
                                $this->getCertificate(),
×
442
                                $this->getPassword()
×
443
                        );
×
444

445
                if (!is_array($result)) {
×
446
                        throw new \RuntimeException('Failed to read certificate data');
×
447
                }
448

449
                return $result;
×
450
        }
451

452
        private function createTextImage(int $width, int $height, float $fontSize, float $scaleFactor): string {
453
                $params = $this->getSignatureParams();
×
454
                if (!empty($params['SignerCommonName'])) {
×
455
                        $commonName = $params['SignerCommonName'];
×
456
                } else {
457
                        $certificateData = $this->readCertificate();
×
458
                        $commonName = $certificateData['subject']['CN'] ?? throw new \RuntimeException('Certificate must have a Common Name (CN) in subject field');
×
459
                }
460
                $content = $this->signatureTextService->signerNameImage(
×
461
                        width: $width,
×
462
                        height: $height,
×
463
                        text: $commonName,
×
464
                        fontSize: $fontSize,
×
465
                        scale: $scaleFactor,
×
466
                );
×
467

468
                $tmpPath = $this->tempManager->getTemporaryFile('_text_image.png');
×
469
                if (!$tmpPath) {
×
470
                        throw new \Exception('Temporary file not accessible');
×
471
                }
472
                file_put_contents($tmpPath, $content);
×
473
                return $tmpPath;
×
474
        }
475

476
        private function mergeBackgroundWithSignature(string $backgroundPath, string $signaturePath, float $scaleFactor): string {
477
                if (!extension_loaded('imagick')) {
×
478
                        throw new \Exception('Extension imagick is not loaded.');
×
479
                }
480
                $baseWidth = $this->signatureTextService->getFullSignatureWidth();
×
481
                $baseHeight = $this->signatureTextService->getFullSignatureHeight();
×
482

483
                $canvasWidth = round($baseWidth * $scaleFactor);
×
484
                $canvasHeight = round($baseHeight * $scaleFactor);
×
485

486
                $background = new Imagick($backgroundPath);
×
487
                $signature = new Imagick($signaturePath);
×
488

489
                $background->setImageFormat('png');
×
490
                $signature->setImageFormat('png');
×
491

492
                $background->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
493
                $signature->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
494

495
                $background->resizeImage(
×
496
                        (int)$canvasWidth,
×
497
                        (int)$canvasHeight,
×
498
                        Imagick::FILTER_LANCZOS,
×
499
                        1,
×
500
                        true
×
501
                );
×
502

503
                $signature->resizeImage(
×
504
                        (int)round($signature->getImageWidth() * $scaleFactor),
×
505
                        (int)round($signature->getImageHeight() * $scaleFactor),
×
506
                        Imagick::FILTER_LANCZOS,
×
507
                        1
×
508
                );
×
509

510
                $canvas = new Imagick();
×
511
                $canvas->newImage((int)$canvasWidth, (int)$canvasHeight, new ImagickPixel('transparent'));
×
512
                $canvas->setImageFormat('png32');
×
513
                $canvas->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
514

515
                $bgX = (int)(($canvasWidth - $background->getImageWidth()) / 2);
×
516
                $bgY = (int)(($canvasHeight - $background->getImageHeight()) / 2);
×
517
                $canvas->compositeImage($background, Imagick::COMPOSITE_OVER, $bgX, $bgY);
×
518

519
                $sigX = (int)(($canvasWidth - $signature->getImageWidth()) / 2);
×
520
                $sigY = (int)(($canvasHeight - $signature->getImageHeight()) / 2);
×
521
                $canvas->compositeImage($signature, Imagick::COMPOSITE_OVER, $sigX, $sigY);
×
522

523
                $tmpPath = $this->tempManager->getTemporaryFile('_merged.png');
×
524
                if (!$tmpPath) {
×
525
                        throw new \Exception('Temporary file not accessible');
×
526
                }
527
                $canvas->writeImage($tmpPath);
×
528

529
                $canvas->clear();
×
530
                $background->clear();
×
531
                $signature->clear();
×
532

533
                return $tmpPath;
×
534
        }
535

536
        private function prepareBackgroundForPdf(string $backgroundPath, float $scaleFactor): string {
537
                if (!extension_loaded('imagick')) {
×
538
                        throw new \Exception('Extension imagick is not loaded.');
×
539
                }
540
                $baseWidth = $this->signatureTextService->getFullSignatureWidth();
×
541
                $baseHeight = $this->signatureTextService->getFullSignatureHeight();
×
542

543
                $canvasWidth = (int)round($baseWidth * $scaleFactor);
×
544
                $canvasHeight = (int)round($baseHeight * $scaleFactor);
×
545

546
                $background = new Imagick($backgroundPath);
×
547
                $background->setImageFormat('png');
×
548
                $background->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
549
                $background->resizeImage(
×
550
                        $canvasWidth,
×
551
                        $canvasHeight,
×
552
                        Imagick::FILTER_LANCZOS,
×
553
                        1,
×
554
                        true
×
555
                );
×
556

557
                $canvas = new Imagick();
×
558
                $canvas->newImage($canvasWidth, $canvasHeight, new ImagickPixel('transparent'));
×
559
                $canvas->setImageFormat('png32');
×
560
                $canvas->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
×
561

562
                $bgX = (int)(($canvasWidth - $background->getImageWidth()) / 2);
×
563
                $bgY = (int)(($canvasHeight - $background->getImageHeight()) / 2);
×
564
                $canvas->compositeImage($background, Imagick::COMPOSITE_OVER, $bgX, $bgY);
×
565

566
                $tmpPath = $this->tempManager->getTemporaryFile('_background.png');
×
567
                if (!$tmpPath) {
×
568
                        throw new \Exception('Temporary file not accessible');
×
569
                }
570
                $canvas->writeImage($tmpPath);
×
571

572
                $canvas->clear();
×
573
                $background->clear();
×
574

575
                return $tmpPath;
×
576
        }
577

578
        private function parseSignatureText(): array {
579
                if (!$this->parsedSignatureText) {
5✔
580
                        $params = $this->getSignatureParams();
5✔
581
                        $params['ServerSignatureDate'] = '${timestamp}';
5✔
582
                        $this->parsedSignatureText = $this->signatureTextService->parse(context: $params);
5✔
583
                }
584
                return $this->parsedSignatureText;
5✔
585
        }
586

587
        public function getSignatureText(): string {
588
                $renderMode = $this->signatureTextService->getRenderMode();
10✔
589
                if ($renderMode !== 'GRAPHIC_ONLY') {
10✔
590
                        $data = $this->parseSignatureText();
5✔
591
                        $signatureText = '"' . str_replace(
5✔
592
                                ['"', '$'],
5✔
593
                                ['\"', '\$'],
5✔
594
                                $data['parsed']
5✔
595
                        ) . '"';
5✔
596
                } else {
597
                        $signatureText = '""';
5✔
598
                }
599

600
                return $signatureText;
10✔
601
        }
602

603
        private function listParamsToString(array $params): string {
604
                $paramString = '';
×
605
                foreach ($params as $flag => $value) {
×
606
                        $paramString .= ' ' . $flag;
×
607
                        if ($value !== null && $value !== '') {
×
608
                                $paramString .= ' ' . $value;
×
609
                        }
610
                }
611
                return $paramString;
×
612
        }
613

614
        private function getTsaParameters(): array {
615
                $tsaUrl = $this->appConfig->getValueString(Application::APP_ID, 'tsa_url', '');
×
616
                if (empty($tsaUrl)) {
×
617
                        return [];
×
618
                }
619

620
                $params = [
×
621
                        '--tsa-server-url' => $tsaUrl,
×
622
                        '--tsa-policy-oid' => $this->appConfig->getValueString(Application::APP_ID, 'tsa_policy_oid', ''),
×
623
                ];
×
624

625
                if (!$params['--tsa-policy-oid']) {
×
626
                        unset($params['--tsa-policy-oid']);
×
627
                }
628

629
                $tsaAuthType = $this->appConfig->getValueString(Application::APP_ID, 'tsa_auth_type', 'none');
×
630
                if ($tsaAuthType === 'basic') {
×
631
                        $tsaUsername = $this->appConfig->getValueString(Application::APP_ID, 'tsa_username', '');
×
632
                        $tsaPassword = $this->appConfig->getValueString(Application::APP_ID, 'tsa_password', '');
×
633

634
                        if (!empty($tsaUsername) && !empty($tsaPassword)) {
×
635
                                $params['--tsa-authentication'] = 'PASSWORD';
×
636
                                $params['--tsa-user'] = $tsaUsername;
×
637
                                $params['--tsa-password'] = $tsaPassword;
×
638
                        }
639
                }
640

641
                return $params;
×
642
        }
643

644
        private function signWrapper(JSignPDF $jSignPDF): string {
645
                try {
646
                        return $jSignPDF->sign();
×
647
                } catch (\Throwable $th) {
×
648
                        $errorMessage = $th->getMessage();
×
649

650
                        $this->checkTsaError($errorMessage);
×
651
                        $this->checkHashAlgorithmError($errorMessage);
×
652

653
                        $this->logger->error('Error at JSignPdf side. LibreSign can not do nothing. Follow the error message: ' . $errorMessage);
×
654
                        throw new \Exception($errorMessage);
×
655
                }
656
        }
657

658
        private function checkTsaError(string $errorMessage): void {
659
                $tsaErrors = ['TSAClientBouncyCastle', 'UnknownHostException', 'Invalid TSA'];
×
660
                $isTsaError = false;
×
661
                foreach ($tsaErrors as $error) {
×
662
                        if (str_contains($errorMessage, $error)) {
×
663
                                $isTsaError = true;
×
664
                                break;
×
665
                        }
666
                }
667

668
                if ($isTsaError) {
×
669
                        if (str_contains($errorMessage, 'Invalid TSA') && preg_match("/Invalid TSA '([^']+)'/", $errorMessage, $matches)) {
×
670
                                $friendlyMessage = 'Timestamp Authority (TSA) service is unavailable or misconfigured: ' . $matches[1];
×
671
                        } else {
672
                                $friendlyMessage = 'Timestamp Authority (TSA) service error.' . "\n"
×
673
                                        . 'Please check the TSA configuration.';
×
674
                        }
675
                        throw new LibresignException($friendlyMessage);
×
676
                }
677
        }
678

679
        private function checkHashAlgorithmError(string $errorMessage): void {
680
                $rows = str_getcsv($errorMessage);
×
681
                $hashAlgorithm = array_filter($rows, fn ($r) => str_contains((string)$r, 'The chosen hash algorithm'));
×
682

683
                if (!empty($hashAlgorithm)) {
×
684
                        $hashAlgorithm = current($hashAlgorithm);
×
685
                        $hashAlgorithm = trim((string)$hashAlgorithm, 'INFO ');
×
686
                        $hashAlgorithm = str_replace('\"', '"', $hashAlgorithm);
×
687
                        $hashAlgorithm = preg_replace('/\.( )/', ".\n", $hashAlgorithm);
×
688
                        throw new LibresignException($hashAlgorithm);
×
689
                }
690
        }
691
}
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