-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathtcpdf.php
More file actions
8512 lines (7526 loc) · 287 KB
/
Copy pathtcpdf.php
File metadata and controls
8512 lines (7526 loc) · 287 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
//============================================================+
// File name : tcpdf.php
// Version : 7.0.2
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (https://www.gnu.org/copyleft/lesser.html)
// Copyright (C): 2002-2026 Nicola Asuni - Tecnick.com LTD
//============================================================+
/**
* @file
* [DEPRECATED] PHP class for generating PDF documents without requiring external extensions.
* Please use instead https://github.com/tecnickcom/tc-lib-pdf
* See: https://tcpdf.org
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 7.0.2
*/
// TCPDF configuration
require_once dirname(__FILE__) . '/tcpdf_autoconfig.php';
/**
* @class TCPDF
* [DEPRECATED] PHP class for generating PDF documents without requiring external extensions.
* Please use instead https://github.com/tecnickcom/tc-lib-pdf
*
* This class is a compatibility facade: it implements the legacy TCPDF public
* API as thin wrappers that delegate the actual PDF generation to the modern
* tc-lib-pdf engine (\Com\Tecnick\Pdf\Tcpdf). The legacy stateful cursor and
* page model is preserved by a small internal state layer.
* See MAPPING.md for the per-method delegation status.
*
* See: https://tcpdf.org
* @package com.tecnick.tcpdf
*
* @phpstan-import-type StyleDataOpt from \Com\Tecnick\Pdf\Graph\Style
* @phpstan-import-type TAnnotOpts from \Com\Tecnick\Pdf\Base
*/
class TCPDF
{
/**
* The tc-lib-pdf engine that renders the actual document.
*/
protected ?\Com\Tecnick\Pdf\Tcpdf $eng = null;
/** Unit of measure ('pt', 'mm', 'cm', 'in'). */
protected string $docunit = 'mm';
/** Scale factor: number of points per user unit. */
protected float $kratio = 1.0;
/** Unicode mode flag. */
protected bool $unicode = true;
/** Document encoding (only 'UTF-8' is supported by the engine). */
protected string $charencoding = 'UTF-8';
/** PDF/A mode passed to the engine ('' = disabled). */
protected string $pdfamode = '';
/** Default page orientation ('P' or 'L'). */
protected string $deforientation = 'P';
/** Default page format (format name string or [width, height] in user units). */
protected mixed $defformat = 'A4';
/** Current page orientation. */
protected string $curorientation = 'P';
/** Current page format. */
protected mixed $curformat = 'A4';
/** Document state: 0 = not started, 1 = open, 2 = has pages, 3 = closed. */
protected int $docstate = 0;
/** Cached raw PDF output (built once at close time). */
protected string $pdfraw = '';
/** Left margin in user units. */
protected float $lmargin = 10.0;
/** Top margin in user units. */
protected float $tmargin = 10.0;
/** Right margin in user units. */
protected float $rmargin = 10.0;
/** Page-break bottom margin in user units. */
protected float $bmargin = 20.0;
/** Original margins (used by header/footer rendering). */
protected float $orig_lmargin = 10.0;
/** Original right margin in user units. */
protected float $orig_rmargin = 10.0;
/** Automatic page break flag. */
protected bool $autopagebreak = true;
/** Current abscissa (user units, from left page edge). */
protected float $posx = 0.0;
/** Current ordinate (user units, from top page edge). */
protected float $posy = 0.0;
/** Height of the last printed cell (user units). */
protected float $lasth = 0.0;
/** Cell height ratio (line height = font size * ratio). */
protected float $cellheightratio = K_CELL_HEIGHT_RATIO;
/** @var array{L: float, T: float, R: float, B: float} Cell internal padding in user units. */
protected array $cellpadding = ['L' => 0.0, 'T' => 0.0, 'R' => 0.0, 'B' => 0.0];
/** @var array{L: float, T: float, R: float, B: float} Cell external margins in user units. */
protected array $cellmargin = ['L' => 0.0, 'T' => 0.0, 'R' => 0.0, 'B' => 0.0];
/** Current font family (normalized lowercase). */
protected string $fontfamily = 'helvetica';
/** Current font style letters (subset of 'B', 'I'). */
protected string $fontstyle = '';
/** @var array{U: bool, D: bool, O: bool} Current font decorations: underline, line-through, overline. */
protected array $fontdecor = ['U' => false, 'D' => false, 'O' => false];
/** Current font size in points. */
protected float $fontsizept = 12.0;
/** @var array<string, mixed> Current font metric array returned by the engine font stack. */
protected array $fontmetric = [];
/** Default font subsetting mode for setFont (legacy default: true). */
protected bool $fontsubsetting = true;
/** Extra font spacing (user units) applied via the engine font stack. */
protected float $fontspacing = 0.0;
/** Font stretching percentage (100 = none). */
protected float $fontstretching = 100.0;
/** Default monospaced font family. */
protected string $monospacedfont = 'courier';
/** Text color: engine color specification string. */
protected string $textcolorspec = 'black';
/** Draw (stroke) color: engine color specification string. */
protected string $drawcolorspec = 'black';
/** Fill color: engine color specification string. */
protected string $fillcolorspec = 'white';
/** @var array<int|float> Legacy components of the current text color. */
protected array $textcolorlegacy = [0, 0, 0];
/** @var array<int|float> Legacy components of the current draw color. */
protected array $drawcolorlegacy = [0, 0, 0];
/** @var array<int|float> Legacy components of the current fill color. */
protected array $fillcolorlegacy = [255, 255, 255];
/** Current line width in user units. */
protected float $linewidth = 0.2;
/** @var StyleDataOpt Current line style (engine style array fragment). */
protected array $linestyle = [];
/** RTL direction flag. */
protected bool $rtlmode = false;
/** Temporary RTL mode ('R', 'L' or false). */
protected mixed $tmprtl = false;
/** Print header flag. */
protected bool $printheader = true;
/** Print footer flag. */
protected bool $printfooter = true;
/** @var array{logo: string, logo_width: float, title: string, string: string, text_color: array<int, float|int|string>, line_color: array<int, float|int|string>} Header data. */
protected array $headerdata = [
'logo' => '',
'logo_width' => 30.0,
'title' => '',
'string' => '',
'text_color' => [0, 0, 0],
'line_color' => [0, 0, 0],
];
/** @var array{text_color: array<int, float|int|string>, line_color: array<int, float|int|string>} Footer text and line colors. */
protected array $footerdata = [
'text_color' => [0, 0, 0],
'line_color' => [0, 0, 0],
];
/** Header margin (minimum distance between header and top page margin). */
protected float $headermargin = 10.0;
/** Footer margin (minimum distance between footer and bottom page margin). */
protected float $footermargin = 10.0;
/** @var array{0: string, 1: string, 2: float} Header font: family, style, size in points. */
protected array $headerfont = ['helvetica', '', 12.0];
/** @var array{0: string, 1: string, 2: float} Footer font: family, style, size in points. */
protected array $footerfont = ['helvetica', '', 12.0];
/** True while rendering the page header or footer. */
protected bool $inheaderfooter = false;
/**
* Language dependent strings (legacy $l array): built-in English
* defaults, overridable via the K_TCPDF_DEFAULT_LANGUAGE constant or
* setLanguageArray().
*
* @var array<int|string, mixed>
*/
protected array $langdata = [
'a_meta_charset' => 'UTF-8',
'a_meta_dir' => 'ltr',
'a_meta_language' => 'en',
'w_page' => 'page',
];
/** Image scale ratio (used when width/height are not specified). */
protected float $imgscale = 1.0;
/** JPEG quality used when re-encoding images. */
protected int $jpegquality = 90;
/** Bottom-right X coordinate of the last inserted image. */
protected float $imagerbx = 0.0;
/** Bottom-right Y coordinate of the last inserted image. */
protected float $imagerby = 0.0;
/** @var array<int, string> Registered soft-mask source files, keyed by the handle returned from Image($ismask=true). */
protected array $imagemasks = [];
/** Sequence for image mask handles. */
protected int $imagemaskseq = 0;
/** @var array{stroke: float, fill: bool, clip: bool} Text rendering mode: stroke width, fill, clip. */
protected array $textrendermode = ['stroke' => 0.0, 'fill' => true, 'clip' => false];
/** @var array{enabled: bool, depth_w: int|float, depth_h: int|float, color: mixed, opacity: int|float, blend_mode: string} Legacy text shadow parameters. */
protected array $textshadow = [
'enabled' => false,
'depth_w' => 0,
'depth_h' => 0,
'color' => false,
'opacity' => 1,
'blend_mode' => 'Normal',
];
/** Starting page number (used by PageNoFormatted). */
protected int $startingpagenumber = 1;
/** Total number of pages, available while rendering deferred decorations. */
protected int $decortotalpages = 0;
/** Document barcode string (printed in the footer when set). */
protected string $docbarcode = '';
/** Booklet mode flag. */
protected bool $bookletmode = false;
/**
* True when the current page is a TOC page.
* Kept protected under its legacy name: user subclasses read it.
*/
protected $tocpage = false;
/** @var array{CA: float, ca: float, BM: string, AIS: bool} Current alpha/blend state. */
protected array $alpha = ['CA' => 1.0, 'ca' => 1.0, 'BM' => '/Normal', 'AIS' => false];
/** @var array{OP: bool, op: bool, OPM: int} Current overprint state. */
protected array $overprint = ['OP' => false, 'op' => false, 'OPM' => 0];
/** Number of currently open optional-content layers. */
protected int $openlayers = 0;
/** Snapshot of the facade object used by the transaction API. */
protected ?TCPDF $transactionsnapshot = null;
/** @var array<int, array{page: int, y: float}> Internal links created by AddLink(). */
protected array $internallinks = [];
/** @var array<string, mixed> Named destinations registered via setDestination(). */
protected array $nameddests = [];
/** Identifier of the currently open XObject template ('' = none). */
protected string $xobjtid = '';
/** Height of the currently open XObject template in user units. */
protected float $xobjheight = 0.0;
/** Page group number for the next added page (0 = default group). */
protected int $nextpagegroup = 0;
/** True when page groups are in use. */
protected bool $pagegroupsused = false;
/** Columns requested via setEqualColumns() for subsequently added pages. */
protected int $pagecolumns = 0;
/** Column width requested via setEqualColumns() (0 = divide the content width evenly). */
protected float $pagecolumnwidth = 0.0;
/** @var array<int, array{RX: float, RY: float, RW: float, RH: float}> Page regions for subsequently added pages. */
protected array $pageregions = [];
/**
* Legacy no-write page regions (setPageRegions()): rectangular/trapezoidal
* exclusion zones that flowing text and HTML must avoid. Stored verbatim in
* the legacy form and converted to engine banded writable regions at flow
* time (see applyNoWriteRegionsForFlow()).
*
* @var array<int, array{page: int, xt: float, yt: float, xb: float, yb: float, side: string}>
*/
protected array $nowriteareas = [];
/** @var array<string, mixed> Default form field properties. */
protected array $formdefaultprop = [];
/** @var array<int, float|int|string> HTML link color (legacy components). */
protected array $htmllinkcolor = [0, 0, 255];
/** HTML link font style letters. */
protected string $htmllinkstyle = 'U';
/** True while rendering HTML that must ignore the current cell padding (legacy writeHTML without $cell). */
protected bool $htmlnopadding = false;
/** @var array{create: int, modify: int} Document timestamps (facade state; the engine stamps output itself). */
protected array $doctimestamps = ['create' => 0, 'modify' => 0];
/** @var array<int, array{header: bool, footer: bool}> Per-page decoration flags, frozen when each page starts. */
protected array $pagedecor = [];
/** @var array{zoom: int|string, layout: string, mode: string} Viewer display mode storage. */
protected array $displaymode = ['zoom' => 'fullwidth', 'layout' => 'SinglePage', 'mode' => 'UseNone'];
public function __construct(
$_orientation = 'P',
$_unit = 'mm',
$_format = 'A4',
$_unicode = true,
$_encoding = 'UTF-8',
$_diskcache = false,
$_pdfa = false,
) {
// $_diskcache is deprecated and intentionally ignored.
// $_encoding: the engine always works in UTF-8.
$this->unicode = (bool) $_unicode;
$this->charencoding = (string) $_encoding;
$this->pdfamode = $this->normalizePdfaMode($_pdfa);
$this->deforientation = $this->normalizeOrientation($_orientation);
$this->curorientation = $this->deforientation;
$this->defformat = is_array($_format) ? $_format : (string) $_format;
$this->curformat = $this->defformat;
$this->engineInit((string) $_unit);
// Legacy defaults: 1cm page margins, padding L/R = margin/10.
$margin = 28.35 / $this->kratio;
$this->setMargins($margin, $margin);
$this->orig_lmargin = $this->lmargin;
$this->orig_rmargin = $this->rmargin;
$this->setCellPaddings($margin / 10, 0, $margin / 10, 0);
$this->setCellMargins(0, 0, 0, 0);
$this->linewidth = 0.57 / $this->kratio;
$this->setAutoPageBreak(true, 2 * $margin);
$this->setImageScale(PDF_IMAGE_SCALE_RATIO);
$this->headermargin = (float) PDF_MARGIN_HEADER;
$this->footermargin = (float) PDF_MARGIN_FOOTER;
// Language-dependent strings: built-in English defaults, merged
// with the optional configuration override.
$langoverride = defined('K_TCPDF_DEFAULT_LANGUAGE') ? constant('K_TCPDF_DEFAULT_LANGUAGE') : null;
$this->setLanguageArray(
is_array($langoverride) ? array_merge($this->langdata, $langoverride) : $this->langdata,
);
$fontname = defined('PDF_FONT_NAME_MAIN') ? PDF_FONT_NAME_MAIN : 'helvetica';
$this->setFont($fontname, '', 12.0);
$this->setHeaderFont([$fontname, '', 12.0]);
$this->setFooterFont([$fontname, '', 12.0]);
$this->docstate = 1;
}
public function __destruct()
{
$this->eng = null;
}
/**
* Legacy protected properties historically read by TCPDF subclasses
* (e.g. $this->AutoPageBreak, $this->lMargin), mapped to facade state.
*/
public function __get($name)
{
return match ($name) {
'AutoPageBreak' => $this->autopagebreak,
'lMargin', 'original_lMargin' => $this->lmargin,
'rMargin', 'original_rMargin' => $this->rmargin,
'tMargin' => $this->tmargin,
'bMargin' => $this->bmargin,
'x' => $this->posx,
'y' => $this->posy,
'w' => $this->getPageWidth(),
'h' => $this->getPageHeight(),
'k' => $this->kratio,
'page' => $this->getPage(),
'lasth' => $this->lasth,
'FontFamily' => $this->fontfamily,
'FontStyle' => $this->fontstyle,
'FontSizePt' => $this->fontsizept,
'FontSize' => $this->getFontSize(),
'l' => $this->langdata,
'header_margin' => $this->headermargin,
'footer_margin' => $this->footermargin,
'print_header' => $this->printheader,
'print_footer' => $this->printfooter,
'rtl' => $this->rtlmode,
'img_rb_x' => $this->imagerbx,
'img_rb_y' => $this->imagerby,
'imgscale' => $this->imgscale,
default => null,
};
}
/** @see __get() */
public function __isset($name)
{
return $this->__get($name) !== null;
}
// ===================================================================
// Internal engine and state helpers (not part of the public API).
// ===================================================================
/**
* Create (or re-create) the tc-lib-pdf engine for the given unit.
*/
protected function engineInit(string $unit): void
{
$unit = strtolower(trim($unit)) === '' ? 'mm' : strtolower(trim($unit));
$this->docunit = $unit;
$this->eng = $this->engineNew();
$this->kratio = $this->eng->toPoints(1.0);
}
/**
* Build a new engine instance wired to re-emit the facade ambient text
* state at the start of every page content stream it opens.
*/
private function engineNew(?\Com\Tecnick\Pdf\Encrypt\Encrypt $encrypt = null): TCPDF_ENGINE
{
$eng = new TCPDF_ENGINE(
$this->docunit,
$this->unicode,
false,
true,
$this->pdfamode,
$encrypt,
$this->fileOptions(),
);
$eng->pagecontexthook = $this->ambientPageContent(...);
return $eng;
}
/**
* Raw PDF operators for the ambient text state that must open every page
* content stream: the engine re-emits the current font (carrying its
* spacing/stretching) when it adds a page, so the facade only needs to
* carry the legacy text color across page breaks.
*/
protected function ambientPageContent(): string
{
return $this->engine()->color->getPdfFillColor($this->textcolorspec);
}
/**
* Local paths the engine may read files from. The legacy API loaded
* images and fonts from application-relative locations, so in addition
* to the engine defaults this allows the configured TCPDF paths, the
* current working directory and the running script directory.
*
* Applications may extend this allowlist with the K_ALLOWED_PATHS
* configuration constant (array of path prefixes): its entries are
* merged on top of the built-in defaults, never replacing them.
*
* @return array<int, string>
*/
protected function fileAllowedPaths(): array
{
$candidates = [
sys_get_temp_dir(),
K_PATH_MAIN,
dirname(__FILE__) . '/vendor/tecnickcom/',
getcwd(),
];
if (defined('K_PATH_FONTS')) {
$candidates[] = K_PATH_FONTS;
}
if (defined('K_PATH_IMAGES')) {
$candidates[] = K_PATH_IMAGES;
}
// Additional trusted read locations from the configuration; merged on
// top of the built-in defaults so bundled assets keep resolving.
// The analyzer resolves K_ALLOWED_PATHS to its default value, so the
// runtime type guard looks redundant; it still protects user overrides.
// @mago-expect analysis:redundant-logical-operation
if (defined('K_ALLOWED_PATHS') && is_array(K_ALLOWED_PATHS)) {
foreach (K_ALLOWED_PATHS as $extrapath) {
$candidates[] = $extrapath;
}
}
$candidates[] = dirname($_SERVER['SCRIPT_FILENAME']);
$paths = [];
foreach ($candidates as $candidate) {
if (!is_string($candidate) || $candidate === '') {
continue;
}
$real = realpath($candidate);
if ($real !== false) {
$paths[] = $real;
}
}
return array_values(array_unique($paths));
}
/**
* Assemble the file-access options handed to the engine's shared file
* helper (tc-lib-file). These drive the upstream security sandbox that
* governs which local paths and remote hosts external resources (images,
* fonts, SVG, ...) may be loaded from.
*
* The mapping is configuration-driven:
* - allowedPaths <- built-in defaults + K_ALLOWED_PATHS (local reads)
* - allowedHosts <- K_ALLOWED_HOSTS (remote HTTP/HTTPS reads; empty
* disables remote loading entirely — the safe default)
* - maxRemoteSize <- K_MAX_REMOTE_SIZE (byte cap on remote downloads)
* - curlopts <- K_CURLOPTS (per-request cURL overrides)
*
* Only explicitly configured keys are forwarded; anything omitted keeps
* the upstream library's secure defaults.
*
* @return array{
* allowedPaths: array<int, string>,
* allowedHosts?: array<int, string>,
* maxRemoteSize?: int,
* curlopts?: array<int, bool|int|string>,
* }
*/
protected function fileOptions(): array
{
$options = ['allowedPaths' => $this->fileAllowedPaths()];
// Remote URL loading is disabled by default in the upstream library:
// an empty (or unset) host allowlist keeps it disabled. Populate
// K_ALLOWED_HOSTS with trusted host names to opt in to remote reads.
// The K_* guards below are runtime-defensive: the analyzer resolves each
// constant to its default value, which makes the type/value checks look
// redundant even though they still validate user-supplied overrides.
// @mago-expect analysis:redundant-logical-operation
if (defined('K_ALLOWED_HOSTS') && is_array(K_ALLOWED_HOSTS) && K_ALLOWED_HOSTS !== []) {
$options['allowedHosts'] = array_values(array_map(
static fn(mixed $host): string => (string) $host,
K_ALLOWED_HOSTS,
));
}
// @mago-expect analysis:redundant-comparison
// @mago-expect analysis:redundant-logical-operation
if (defined('K_MAX_REMOTE_SIZE') && (int) K_MAX_REMOTE_SIZE > 0) {
$options['maxRemoteSize'] = (int) K_MAX_REMOTE_SIZE;
}
// @mago-expect analysis:redundant-logical-operation
if (defined('K_CURLOPTS') && is_array(K_CURLOPTS) && K_CURLOPTS !== []) {
$options['curlopts'] = K_CURLOPTS;
}
// The K_* security constants resolve to their concrete defaults during
// static analysis, so the analyzer narrows array_map(K_ALLOWED_HOSTS)
// to a less-specific nested type than the documented contract; the
// declared return type is authoritative for the runtime-configurable
// values.
// @mago-expect analysis:less-specific-nested-return-statement
return $options;
}
/**
* Return the engine instance.
*/
protected function engine(): \Com\Tecnick\Pdf\Tcpdf
{
if (!$this->eng instanceof \Com\Tecnick\Pdf\Tcpdf) {
throw new \RuntimeException('TCPDF engine is not initialized');
}
return $this->eng;
}
/**
* Append raw PDF content to the current page (no-op when no page exists).
*/
protected function emitToPage(string $content): void
{
if ($content === '' || $this->docstate < 2) {
return;
}
if ($this->xobjtid !== '') {
$this->engine()->addXObjectContent($this->xobjtid, $content);
return;
}
$this->engine()->page->addContent($content);
}
/**
* Normalize a legacy orientation value to 'P' or 'L'.
*/
protected function normalizeOrientation(mixed $orientation): string
{
$val = strtoupper(substr((string) $orientation, 0, 1));
return $val === 'L' ? 'L' : 'P';
}
/**
* Map the legacy $pdfa constructor flag onto an engine conformance mode.
*/
protected function normalizePdfaMode(mixed $pdfa): string
{
$level = (int) $pdfa;
if ($level <= 0) {
return '';
}
return match ($level) {
2 => 'pdfa2b',
3 => 'pdfa3b',
default => 'pdfa1b',
};
}
/**
* Build the engine page data array for a new page.
*/
protected function buildPageData(mixed $orientation, mixed $format): array
{
$orientation = (string) $orientation === '' ? $this->curorientation : $this->normalizeOrientation($orientation);
if (!is_array($format)) {
$format = (string) $format === '' ? $this->curformat : (string) $format;
}
$this->curorientation = $orientation;
$this->curformat = $format;
$data = [
'orientation' => $orientation,
'margin' => [
'PL' => $this->lmargin,
'PR' => $this->rmargin,
'PT' => 0.0,
'HB' => 0.0,
'CT' => $this->tmargin,
'CB' => $this->bmargin,
'FT' => 0.0,
'PB' => 0.0,
],
'autobreak' => $this->autopagebreak,
];
if ($this->pagegroupsused) {
$data['group'] = $this->nextpagegroup;
}
if ($this->pageregions !== []) {
// Columns restart at the top margin on every page after the one
// where they were defined (legacy selectColumn() behavior).
$data['region'] = array_map(fn(array $region): array => [
'RX' => $region['RX'],
'RY' => $this->tmargin,
'RW' => $region['RW'],
'RH' => $this->getPageHeight() - $this->tmargin - $this->bmargin,
], $this->pageregions);
} elseif ($this->pagecolumns > 1) {
$data['region'] = $this->equalColumnRegions($this->pagecolumns, $this->pagecolumnwidth, $this->tmargin);
}
if (is_array($format)) {
$width = (float) ($format[0] ?? 0);
$height = (float) ($format[1] ?? 0);
if ($width > 0 && $height > 0) {
$data['width'] = $width;
$data['height'] = $height;
} elseif (isset($format['MediaBox']) && is_array($format['MediaBox'])) {
// Legacy extended format array: page boxes are given in user
// units; the engine expects them in points.
$boxes = [];
foreach (['MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox'] as $boxname) {
if (!(isset($format[$boxname]) && is_array($format[$boxname]))) {
continue;
}
$boxes = $this->engine()->page->setBox(
$boxes,
$boxname,
(float) ($format[$boxname]['llx'] ?? 0) * $this->kratio,
(float) ($format[$boxname]['lly'] ?? 0) * $this->kratio,
(float) ($format[$boxname]['urx'] ?? 0) * $this->kratio,
(float) ($format[$boxname]['ury'] ?? 0) * $this->kratio,
);
}
$data['box'] = $boxes;
$mediabox = $boxes['MediaBox'] ?? ['llx' => 0.0, 'lly' => 0.0, 'urx' => 0.0, 'ury' => 0.0];
$data['width'] = abs($mediabox['urx'] - $mediabox['llx']) / $this->kratio;
$data['height'] = abs($mediabox['ury'] - $mediabox['lly']) / $this->kratio;
} elseif (isset($format['format'])) {
$data['format'] = strtoupper((string) $format['format']);
} else {
$data['format'] = is_string($this->defformat) ? strtoupper($this->defformat) : 'A4';
}
if (isset($format['Rotate']) && is_numeric($format['Rotate'])) {
$data['rotation'] = (int) $format['Rotate'];
}
if (isset($format['PZ']) && is_numeric($format['PZ'])) {
$data['zoom'] = (float) $format['PZ'];
}
$transition = [];
if (isset($format['Dur']) && is_numeric($format['Dur'])) {
$transition['Dur'] = (float) $format['Dur'];
}
if (isset($format['trans']) && is_array($format['trans'])) {
foreach (['D', 'S', 'Dm', 'M', 'Di', 'SS', 'B'] as $key) {
if (!isset($format['trans'][$key])) {
continue;
}
$transition[$key] = $format['trans'][$key];
}
}
if ($transition !== []) {
$data['transition'] = $transition;
}
} else {
$data['format'] = strtoupper((string) $format);
}
return $data;
}
/**
* Convert a legacy color definition (component list or array) to an
* engine color specification string.
*
* Legacy conventions: 1 component = grayscale 0-255; 3 components =
* RGB 0-255; 4 components = CMYK 0-100; 5th component = spot color name.
*/
protected function colorSpecFromLegacy(mixed $color): string
{
if (is_string($color) && $color !== '') {
return $color;
}
if (!is_array($color) || $color === []) {
return 'black';
}
$values = array_values($color);
$num = count($values);
if ($num >= 4 && is_numeric($values[0]) && is_numeric($values[3])) {
return (
'cmyk('
. (float) $values[0]
. '%,'
. (float) $values[1]
. '%,'
. (float) $values[2]
. '%,'
. (float) $values[3]
. '%)'
);
}
if ($num >= 3) {
return 'rgb(' . (int) $values[0] . ',' . (int) ($values[1] ?? 0) . ',' . (int) ($values[2] ?? 0) . ')';
}
$gray = (int) $values[0];
return 'rgb(' . $gray . ',' . $gray . ',' . $gray . ')';
}
/**
* Convert legacy color components (setColor-style) to a spec string.
*/
protected function colorSpecFromComponents(mixed $col1, mixed $col2, mixed $col3, mixed $col4, string $name): string
{
if ($name !== '') {
return $name;
}
if ((float) $col4 >= 0) {
return $this->colorSpecFromLegacy([(float) $col1, (float) $col2, (float) $col3, (float) $col4]);
}
if ((float) $col2 >= 0 && (float) $col3 >= 0) {
return $this->colorSpecFromLegacy([(int) $col1, (int) $col2, (int) $col3]);
}
return $this->colorSpecFromLegacy([(int) $col1]);
}
/**
* Sanitize a legacy color component array (numbers, optional spot name).
*
* @param array<int, float|int|string> $default Fallback components.
*
* @return array<int, float|int|string>
*/
protected function legacyColorComponents(mixed $color, array $default): array
{
if (!is_array($color)) {
return $default;
}
/** @var array<int, float|int|string> $out */
$out = [];
foreach (array_values($color) as $val) {
$out[] = is_string($val) ? $val : (float) $val;
}
return $out === [] ? $default : $out;
}
/**
* Current line style as an engine style array (lineWidth, lineColor, ...).
*
* @return StyleDataOpt
*/
protected function currentLineStyle(): array
{
$style = $this->linestyle;
$style['lineWidth'] = $this->linewidth;
// The draw color is the single source of truth for the stroke color:
// setLineStyle() keeps it in sync, and setDrawColor() updates it on its
// own, so an explicit setDrawColor() after a setLineStyle() still wins.
$style['lineColor'] = $this->drawcolorspec;
return $style;
}
/**
* Build the engine per-side styles array from a legacy border argument.
*
* @param mixed $border 0/false = none, 1/true = full frame,
* string with letters L,T,R,B = specific sides,
* array of side => style = per-side styles.
*
* @return array{T?: StyleDataOpt, R?: StyleDataOpt, B?: StyleDataOpt, L?: StyleDataOpt, all?: StyleDataOpt}
*/
protected function stylesFromLegacyBorder(mixed $border, bool $fill): array
{
$styles = [];
$line = $this->currentLineStyle();
if (is_array($border)) {
foreach ($border as $key => $sty) {
$side = is_string($key) ? strtoupper($key) : 'all';
$sidestyle = $line;
if (is_array($sty)) {
$sidestyle = $this->styleFromLegacyLineStyle($sty);
}
if ($side === 'all' || $side === 'LTRB' || $side === 'TRBL') {
$styles['all'] = $sidestyle;
continue;
}
foreach (str_split($side) as $letter) {
if (!in_array($letter, ['L', 'T', 'R', 'B'], true)) {
continue;
}
$styles[$letter] = $sidestyle;
}
}
} elseif ((is_int($border) || is_bool($border)) && (int) $border === 1) {
$styles['all'] = $line;
} elseif (is_string($border) && $border !== '' && $border !== '0') {
foreach (str_split(strtoupper($border)) as $letter) {
if (!in_array($letter, ['L', 'T', 'R', 'B'], true)) {
continue;
}
$styles[$letter] = $line;
}
}
if ($fill) {
if (!isset($styles['all'])) {
$styles['all'] = ['lineWidth' => 0.0];
}
$styles['all']['fillColor'] = $this->fillcolorspec;
}
if ($styles === []) {
// Explicit zero line width: otherwise the engine derives a
// minimum cell padding from the ambient line style, shifting
// the text relative to the legacy layout.
$styles['all'] = ['lineWidth' => 0.0];
}
return $styles;
}
/**
* Mirror legacy adjustCellPadding(): a cell border reserves a minimum cell
* padding so the stroke does not overlap the text, and the optional
* position mode decides how much of the stroke falls inside the cell box:
* - ext : the whole stroke is painted outside -> 0 padding, the
* border rectangle grows outward;
* - int : the whole stroke is painted inside -> a full line-width
* padding, the border rectangle shrinks inward;
* - normal : the stroke straddles the edge -> half line-width.
* The derived padding only ever increases the current cell padding (it
* never shrinks it) and grows the auto cell height exactly like legacy.
*
* @return array{pos: float, padding: array{T: float, R: float, B: float, L: float}}
*/
protected function legacyBorderCellMetrics(mixed $border): array
{
$padding = [
'T' => $this->cellpadding['T'],
'R' => $this->cellpadding['R'],
'B' => $this->cellpadding['B'],
'L' => $this->cellpadding['L'],
];
// Normalize the legacy border argument into a per-side map and pull the
// optional position mode, like legacy adjustCellPadding().
$mode = 'normal';
$sides = [];
if (is_array($border)) {
$map = $border;
if (isset($map['mode'])) {
$mode = strtolower((string) $map['mode']);
unset($map['mode']);
}
foreach ($map as $key => $style) {
$side = is_string($key) ? strtoupper($key) : 'LTRB';
if (in_array($side, ['ALL', 'LTRB', 'TRBL'], true)) {
$side = 'LTRB';
}
$sides[$side] = $style;
}
} elseif ((is_int($border) || is_bool($border)) && (int) $border === 1) {
$sides['LTRB'] = true;
} elseif (is_string($border) && $border !== '' && $border !== '0') {
$sides[strtoupper($border)] = true;
}
$pos = match ($mode) {
'ext' => \Com\Tecnick\Pdf\Tcpdf::BORDERPOS_EXTERNAL,
'int' => \Com\Tecnick\Pdf\Tcpdf::BORDERPOS_INTERNAL,
default => \Com\Tecnick\Pdf\Tcpdf::BORDERPOS_DEFAULT,
};
if ($sides === []) {
return ['pos' => $pos, 'padding' => $padding];
}
foreach ($sides as $side => $style) {
$linewidth = $this->linewidth;
if (is_array($style) && isset($style['width']) && is_numeric($style['width'])) {
$linewidth = (float) $style['width'];
}
$adj = match ($mode) {
'ext' => 0.0,