-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathTemplateProcessor.php
1504 lines (1302 loc) · 52.6 KB
/
TemplateProcessor.php
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
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord;
use DOMDocument;
use PhpOffice\PhpWord\Escaper\RegExp;
use PhpOffice\PhpWord\Escaper\Xml;
use PhpOffice\PhpWord\Exception\CopyFileException;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use PhpOffice\PhpWord\Exception\Exception;
use PhpOffice\PhpWord\Shared\Text;
use PhpOffice\PhpWord\Shared\XMLWriter;
use PhpOffice\PhpWord\Shared\ZipArchive;
use Throwable;
use XSLTProcessor;
class TemplateProcessor
{
const MAXIMUM_REPLACEMENTS_DEFAULT = -1;
/**
* ZipArchive object.
*
* @var mixed
*/
protected $zipClass;
/**
* @var string Temporary document filename (with path)
*/
protected $tempDocumentFilename;
/**
* Content of main document part (in XML format) of the temporary document.
*
* @var string
*/
protected $tempDocumentMainPart;
/**
* Content of settings part (in XML format) of the temporary document.
*
* @var string
*/
protected $tempDocumentSettingsPart;
/**
* Content of headers (in XML format) of the temporary document.
*
* @var string[]
*/
protected $tempDocumentHeaders = [];
/**
* Content of footers (in XML format) of the temporary document.
*
* @var string[]
*/
protected $tempDocumentFooters = [];
/**
* Document relations (in XML format) of the temporary document.
*
* @var string[]
*/
protected $tempDocumentRelations = [];
/**
* Document content types (in XML format) of the temporary document.
*
* @var string
*/
protected $tempDocumentContentTypes = '';
/**
* new inserted images list.
*
* @var string[]
*/
protected $tempDocumentNewImages = [];
protected static $macroOpeningChars = '${';
protected static $macroClosingChars = '}';
/**
* @since 0.12.0 Throws CreateTemporaryFileException and CopyFileException instead of Exception
*
* @param string $documentTemplate The fully qualified template filename
*/
public function __construct($documentTemplate)
{
// Temporary document filename initialization
$this->tempDocumentFilename = tempnam(Settings::getTempDir(), 'PhpWord');
if (false === $this->tempDocumentFilename) {
throw new CreateTemporaryFileException(); // @codeCoverageIgnore
}
// Template file cloning
if (false === copy($documentTemplate, $this->tempDocumentFilename)) {
throw new CopyFileException($documentTemplate, $this->tempDocumentFilename); // @codeCoverageIgnore
}
// Temporary document content extraction
$this->zipClass = new ZipArchive();
$this->zipClass->open($this->tempDocumentFilename);
$index = 1;
while (false !== $this->zipClass->locateName($this->getHeaderName($index))) {
$this->tempDocumentHeaders[$index] = $this->readPartWithRels($this->getHeaderName($index));
++$index;
}
$index = 1;
while (false !== $this->zipClass->locateName($this->getFooterName($index))) {
$this->tempDocumentFooters[$index] = $this->readPartWithRels($this->getFooterName($index));
++$index;
}
$this->tempDocumentMainPart = $this->readPartWithRels($this->getMainPartName());
$this->tempDocumentSettingsPart = $this->readPartWithRels($this->getSettingsPartName());
$this->tempDocumentContentTypes = $this->zipClass->getFromName($this->getDocumentContentTypesName());
}
public function __destruct()
{
// ZipClass
if ($this->zipClass) {
try {
$this->zipClass->close();
} catch (Throwable $e) {
// Nothing to do here.
}
}
}
/**
* Expose zip class.
*
* To replace an image: $templateProcessor->zip()->AddFromString("word/media/image1.jpg", file_get_contents($file));<br>
* To read a file: $templateProcessor->zip()->getFromName("word/media/image1.jpg");
*
* @return ZipArchive
*/
public function zip()
{
return $this->zipClass;
}
/**
* @param string $fileName
*
* @return string
*/
protected function readPartWithRels($fileName)
{
$relsFileName = $this->getRelationsName($fileName);
$partRelations = $this->zipClass->getFromName($relsFileName);
if ($partRelations !== false) {
$this->tempDocumentRelations[$fileName] = $partRelations;
}
return $this->fixBrokenMacros($this->zipClass->getFromName($fileName));
}
/**
* @param string $xml
* @param XSLTProcessor $xsltProcessor
*
* @return string
*/
protected function transformSingleXml($xml, $xsltProcessor)
{
if (\PHP_VERSION_ID < 80000) {
$orignalLibEntityLoader = libxml_disable_entity_loader(true);
}
$domDocument = new DOMDocument();
if (false === $domDocument->loadXML($xml)) {
throw new Exception('Could not load the given XML document.');
}
$transformedXml = $xsltProcessor->transformToXml($domDocument);
if (false === $transformedXml) {
throw new Exception('Could not transform the given XML document.');
}
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader($orignalLibEntityLoader);
}
return $transformedXml;
}
/**
* @param mixed $xml
* @param XSLTProcessor $xsltProcessor
*
* @return mixed
*/
protected function transformXml($xml, $xsltProcessor)
{
if (is_array($xml)) {
foreach ($xml as &$item) {
$item = $this->transformSingleXml($item, $xsltProcessor);
}
unset($item);
} else {
$xml = $this->transformSingleXml($xml, $xsltProcessor);
}
return $xml;
}
/**
* Applies XSL style sheet to template's parts.
*
* Note: since the method doesn't make any guess on logic of the provided XSL style sheet,
* make sure that output is correctly escaped. Otherwise you may get broken document.
*
* @param DOMDocument $xslDomDocument
* @param array $xslOptions
* @param string $xslOptionsUri
*/
public function applyXslStyleSheet($xslDomDocument, $xslOptions = [], $xslOptionsUri = ''): void
{
$xsltProcessor = new XSLTProcessor();
$xsltProcessor->importStylesheet($xslDomDocument);
if (false === $xsltProcessor->setParameter($xslOptionsUri, $xslOptions)) {
throw new Exception('Could not set values for the given XSL style sheet parameters.');
}
$this->tempDocumentHeaders = $this->transformXml($this->tempDocumentHeaders, $xsltProcessor);
$this->tempDocumentMainPart = $this->transformXml($this->tempDocumentMainPart, $xsltProcessor);
$this->tempDocumentFooters = $this->transformXml($this->tempDocumentFooters, $xsltProcessor);
}
/**
* @param string $macro
*
* @return string
*/
protected static function ensureMacroCompleted($macro)
{
if (substr($macro, 0, 2) !== self::$macroOpeningChars && substr($macro, -1) !== self::$macroClosingChars) {
$macro = self::$macroOpeningChars . $macro . self::$macroClosingChars;
}
return $macro;
}
/**
* @param ?string $subject
*
* @return string
*/
protected static function ensureUtf8Encoded($subject)
{
return $subject ? Text::toUTF8($subject) : '';
}
/**
* @param string $search
*/
public function setComplexValue($search, Element\AbstractElement $complexType): void
{
$elementName = substr(get_class($complexType), strrpos(get_class($complexType), '\\') + 1);
$objectClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Element\\' . $elementName;
$xmlWriter = new XMLWriter();
/** @var Writer\Word2007\Element\AbstractElement $elementWriter */
$elementWriter = new $objectClass($xmlWriter, $complexType, true);
$elementWriter->write();
$where = $this->findContainingXmlBlockForMacro($search, 'w:r');
if ($where === false) {
return;
}
$block = $this->getSlice($where['start'], $where['end']);
$textParts = $this->splitTextIntoTexts($block);
$this->replaceXmlBlock($search, $textParts, 'w:r');
$search = static::ensureMacroCompleted($search);
$this->replaceXmlBlock($search, $xmlWriter->getData(), 'w:r');
}
/**
* @param string $search
*/
public function setComplexBlock($search, Element\AbstractElement $complexType): void
{
$elementName = substr(get_class($complexType), strrpos(get_class($complexType), '\\') + 1);
$objectClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Element\\' . $elementName;
$xmlWriter = new XMLWriter();
/** @var Writer\Word2007\Element\AbstractElement $elementWriter */
$elementWriter = new $objectClass($xmlWriter, $complexType, false);
$elementWriter->write();
$this->replaceXmlBlock($search, $xmlWriter->getData(), 'w:p');
}
/**
* @param mixed $search
* @param mixed $replace
* @param int $limit
*/
public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT): void
{
if (is_array($search)) {
foreach ($search as &$item) {
$item = static::ensureMacroCompleted($item);
}
unset($item);
} else {
$search = static::ensureMacroCompleted($search);
}
if (is_array($replace)) {
foreach ($replace as &$item) {
$item = static::ensureUtf8Encoded($item);
}
unset($item);
} else {
$replace = static::ensureUtf8Encoded($replace);
}
if (Settings::isOutputEscapingEnabled()) {
$xmlEscaper = new Xml();
$replace = $xmlEscaper->escape($replace);
}
// convert carriage returns
if (is_array($replace)) {
foreach ($replace as &$item) {
$item = $this->replaceCarriageReturns($item);
}
} else {
$replace = $this->replaceCarriageReturns($replace);
}
$this->tempDocumentHeaders = $this->setValueForPart($search, $replace, $this->tempDocumentHeaders, $limit);
$this->tempDocumentMainPart = $this->setValueForPart($search, $replace, $this->tempDocumentMainPart, $limit);
$this->tempDocumentFooters = $this->setValueForPart($search, $replace, $this->tempDocumentFooters, $limit);
}
/**
* Set values from a one-dimensional array of "variable => value"-pairs.
*/
public function setValues(array $values): void
{
foreach ($values as $macro => $replace) {
$this->setValue($macro, $replace);
}
}
public function setCheckbox(string $search, bool $checked): void
{
$search = static::ensureMacroCompleted($search);
$blockType = 'w:sdt';
$where = $this->findContainingXmlBlockForMacro($search, $blockType);
if (!is_array($where)) {
return;
}
$block = $this->getSlice($where['start'], $where['end']);
$val = $checked ? '1' : '0';
$block = preg_replace('/(<w14:checked w14:val=)".*?"(\/>)/', '$1"' . $val . '"$2', $block);
$text = $checked ? '☒' : '☐';
$block = preg_replace('/(<w:t>).*?(<\/w:t>)/', '$1' . $text . '$2', $block);
$this->replaceXmlBlock($search, $block, $blockType);
}
/**
* @param string $search
*/
public function setChart($search, Element\AbstractElement $chart): void
{
$elementName = substr(get_class($chart), strrpos(get_class($chart), '\\') + 1);
$objectClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Element\\' . $elementName;
// Get the next relation id
$rId = $this->getNextRelationsIndex($this->getMainPartName());
$chart->setRelationId($rId);
// Define the chart filename
$filename = "charts/chart{$rId}.xml";
// Get the part writer
$writerPart = new Writer\Word2007\Part\Chart();
$writerPart->setElement($chart);
// ContentTypes.xml
$this->zipClass->addFromString("word/{$filename}", $writerPart->write());
// add chart to content type
$xmlRelationsType = "<Override PartName=\"/word/{$filename}\" ContentType=\"application/vnd.openxmlformats-officedocument.drawingml.chart+xml\"/>";
$this->tempDocumentContentTypes = str_replace('</Types>', $xmlRelationsType, $this->tempDocumentContentTypes) . '</Types>';
// Add the chart to relations
$xmlChartRelation = "<Relationship Id=\"rId{$rId}\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart\" Target=\"charts/chart{$rId}.xml\"/>";
$this->tempDocumentRelations[$this->getMainPartName()] = str_replace('</Relationships>', $xmlChartRelation, $this->tempDocumentRelations[$this->getMainPartName()]) . '</Relationships>';
// Write the chart
$xmlWriter = new XMLWriter();
$elementWriter = new $objectClass($xmlWriter, $chart, true);
$elementWriter->write();
// Place it in the template
$this->replaceXmlBlock($search, '<w:p>' . $xmlWriter->getData() . '</w:p>', 'w:p');
}
private function getImageArgs($varNameWithArgs)
{
$varElements = explode(':', $varNameWithArgs);
array_shift($varElements); // first element is name of variable => remove it
$varInlineArgs = [];
// size format documentation: https://msdn.microsoft.com/en-us/library/documentformat.openxml.vml.shape%28v=office.14%29.aspx?f=255&MSPPError=-2147217396
foreach ($varElements as $argIdx => $varArg) {
if (strpos($varArg, '=')) { // arg=value
[$argName, $argValue] = explode('=', $varArg, 2);
$argName = strtolower($argName);
if ($argName == 'size') {
[$varInlineArgs['width'], $varInlineArgs['height']] = explode('x', $argValue, 2);
} else {
$varInlineArgs[strtolower($argName)] = $argValue;
}
} elseif (preg_match('/^([0-9]*[a-z%]{0,2}|auto)x([0-9]*[a-z%]{0,2}|auto)$/i', $varArg)) { // 60x40
[$varInlineArgs['width'], $varInlineArgs['height']] = explode('x', $varArg, 2);
} else { // :60:40:f
switch ($argIdx) {
case 0:
$varInlineArgs['width'] = $varArg;
break;
case 1:
$varInlineArgs['height'] = $varArg;
break;
case 2:
$varInlineArgs['ratio'] = $varArg;
break;
}
}
}
return $varInlineArgs;
}
private function chooseImageDimension($baseValue, $inlineValue, $defaultValue)
{
$value = $baseValue;
if (null === $value && isset($inlineValue)) {
$value = $inlineValue;
}
if (!preg_match('/^([0-9\.]*(cm|mm|in|pt|pc|px|%|em|ex|)|auto)$/i', $value ?? '')) {
$value = null;
}
if (null === $value) {
$value = $defaultValue;
}
if (is_numeric($value)) {
$value .= 'px';
}
return $value;
}
private function fixImageWidthHeightRatio(&$width, &$height, $actualWidth, $actualHeight): void
{
$imageRatio = $actualWidth / $actualHeight;
if (($width === '') && ($height === '')) { // defined size are empty
$width = $actualWidth . 'px';
$height = $actualHeight . 'px';
} elseif ($width === '') { // defined width is empty
$heightFloat = (float) $height;
$widthFloat = $heightFloat * $imageRatio;
$matches = [];
preg_match('/\\d([a-z%]+)$/', $height, $matches);
$width = $widthFloat . (!empty($matches) ? $matches[1] : 'px');
} elseif ($height === '') { // defined height is empty
$widthFloat = (float) $width;
$heightFloat = $widthFloat / $imageRatio;
$matches = [];
preg_match('/\\d([a-z%]+)$/', $width, $matches);
$height = $heightFloat . (!empty($matches) ? $matches[1] : 'px');
} else { // we have defined size, but we need also check it aspect ratio
$widthMatches = [];
preg_match('/\\d([a-z%]+)$/', $width, $widthMatches);
$heightMatches = [];
preg_match('/\\d([a-z%]+)$/', $height, $heightMatches);
// try to fix only if dimensions are same
if (!empty($widthMatches)
&& !empty($heightMatches)
&& $widthMatches[1] == $heightMatches[1]) {
$dimention = $widthMatches[1];
$widthFloat = (float) $width;
$heightFloat = (float) $height;
$definedRatio = $widthFloat / $heightFloat;
if ($imageRatio > $definedRatio) { // image wider than defined box
$height = ($widthFloat / $imageRatio) . $dimention;
} elseif ($imageRatio < $definedRatio) { // image higher than defined box
$width = ($heightFloat * $imageRatio) . $dimention;
}
}
}
}
private function prepareImageAttrs($replaceImage, $varInlineArgs)
{
// get image path and size
$width = null;
$height = null;
$ratio = null;
// a closure can be passed as replacement value which after resolving, can contain the replacement info for the image
// use case: only when a image if found, the replacement tags can be generated
if (is_callable($replaceImage)) {
$replaceImage = $replaceImage();
}
if (is_array($replaceImage) && isset($replaceImage['path'])) {
$imgPath = $replaceImage['path'];
if (isset($replaceImage['width'])) {
$width = $replaceImage['width'];
}
if (isset($replaceImage['height'])) {
$height = $replaceImage['height'];
}
if (isset($replaceImage['ratio'])) {
$ratio = $replaceImage['ratio'];
}
} else {
$imgPath = $replaceImage;
}
$width = $this->chooseImageDimension($width, $varInlineArgs['width'] ?? null, 115);
$height = $this->chooseImageDimension($height, $varInlineArgs['height'] ?? null, 70);
$imageData = @getimagesize($imgPath);
if (!is_array($imageData)) {
throw new Exception(sprintf('Invalid image: %s', $imgPath));
}
[$actualWidth, $actualHeight, $imageType] = $imageData;
// fix aspect ratio (by default)
if (null === $ratio && isset($varInlineArgs['ratio'])) {
$ratio = $varInlineArgs['ratio'];
}
if (null === $ratio || !in_array(strtolower($ratio), ['', '-', 'f', 'false'])) {
$this->fixImageWidthHeightRatio($width, $height, $actualWidth, $actualHeight);
}
$imageAttrs = [
'src' => $imgPath,
'mime' => image_type_to_mime_type($imageType),
'width' => $width,
'height' => $height,
];
return $imageAttrs;
}
private function addImageToRelations($partFileName, $rid, $imgPath, $imageMimeType): void
{
// define templates
$typeTpl = '<Override PartName="/word/media/{IMG}" ContentType="image/{EXT}"/>';
$relationTpl = '<Relationship Id="{RID}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/{IMG}"/>';
$newRelationsTpl = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n" . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>';
$newRelationsTypeTpl = '<Override PartName="/{RELS}" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
$extTransform = [
'image/jpeg' => 'jpeg',
'image/png' => 'png',
'image/bmp' => 'bmp',
'image/gif' => 'gif',
];
// get image embed name
if (isset($this->tempDocumentNewImages[$imgPath])) {
$imgName = $this->tempDocumentNewImages[$imgPath];
} else {
// transform extension
if (isset($extTransform[$imageMimeType])) {
$imgExt = $extTransform[$imageMimeType];
} else {
throw new Exception("Unsupported image type $imageMimeType");
}
// add image to document
$imgName = 'image_' . $rid . '_' . pathinfo($partFileName, PATHINFO_FILENAME) . '.' . $imgExt;
$this->zipClass->pclzipAddFile($imgPath, 'word/media/' . $imgName);
$this->tempDocumentNewImages[$imgPath] = $imgName;
// setup type for image
$xmlImageType = str_replace(['{IMG}', '{EXT}'], [$imgName, $imgExt], $typeTpl);
$this->tempDocumentContentTypes = str_replace('</Types>', $xmlImageType, $this->tempDocumentContentTypes) . '</Types>';
}
$xmlImageRelation = str_replace(['{RID}', '{IMG}'], [$rid, $imgName], $relationTpl);
if (!isset($this->tempDocumentRelations[$partFileName])) {
// create new relations file
$this->tempDocumentRelations[$partFileName] = $newRelationsTpl;
// and add it to content types
$xmlRelationsType = str_replace('{RELS}', $this->getRelationsName($partFileName), $newRelationsTypeTpl);
$this->tempDocumentContentTypes = str_replace('</Types>', $xmlRelationsType, $this->tempDocumentContentTypes) . '</Types>';
}
// add image to relations
$this->tempDocumentRelations[$partFileName] = str_replace('</Relationships>', $xmlImageRelation, $this->tempDocumentRelations[$partFileName]) . '</Relationships>';
}
/**
* @param mixed $search
* @param mixed $replace Path to image, or array("path" => xx, "width" => yy, "height" => zz)
* @param int $limit
*/
public function setImageValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT): void
{
// prepare $search_replace
if (!is_array($search)) {
$search = [$search];
}
$replacesList = [];
if (!is_array($replace) || isset($replace['path'])) {
$replacesList[] = $replace;
} else {
$replacesList = array_values($replace);
}
$searchReplace = [];
foreach ($search as $searchIdx => $searchString) {
$searchReplace[$searchString] = $replacesList[$searchIdx] ?? $replacesList[0];
}
// collect document parts
$searchParts = [
$this->getMainPartName() => &$this->tempDocumentMainPart,
];
foreach (array_keys($this->tempDocumentHeaders) as $headerIndex) {
$searchParts[$this->getHeaderName($headerIndex)] = &$this->tempDocumentHeaders[$headerIndex];
}
foreach (array_keys($this->tempDocumentFooters) as $footerIndex) {
$searchParts[$this->getFooterName($footerIndex)] = &$this->tempDocumentFooters[$footerIndex];
}
// define templates
// result can be verified via "Open XML SDK 2.5 Productivity Tool" (http://www.microsoft.com/en-us/download/details.aspx?id=30425)
$imgTpl = '<w:pict><v:shape type="#_x0000_t75" style="width:{WIDTH};height:{HEIGHT}" stroked="f" filled="f"><v:imagedata r:id="{RID}" o:title=""/></v:shape></w:pict>';
$i = 0;
foreach ($searchParts as $partFileName => &$partContent) {
$partVariables = $this->getVariablesForPart($partContent);
foreach ($searchReplace as $searchString => $replaceImage) {
$varsToReplace = array_filter($partVariables, function ($partVar) use ($searchString) {
return ($partVar == $searchString) || preg_match('/^' . preg_quote($searchString) . ':/', $partVar);
});
foreach ($varsToReplace as $varNameWithArgs) {
$varInlineArgs = $this->getImageArgs($varNameWithArgs);
$preparedImageAttrs = $this->prepareImageAttrs($replaceImage, $varInlineArgs);
$imgPath = $preparedImageAttrs['src'];
// get image index
$imgIndex = $this->getNextRelationsIndex($partFileName);
$rid = 'rId' . $imgIndex;
// replace preparations
$this->addImageToRelations($partFileName, $rid, $imgPath, $preparedImageAttrs['mime']);
$xmlImage = str_replace(['{RID}', '{WIDTH}', '{HEIGHT}'], [$rid, $preparedImageAttrs['width'], $preparedImageAttrs['height']], $imgTpl);
// replace variable
$varNameWithArgsFixed = static::ensureMacroCompleted($varNameWithArgs);
$matches = [];
if (preg_match('/(<[^<]+>)([^<]*)(' . preg_quote($varNameWithArgsFixed) . ')([^>]*)(<[^>]+>)/Uu', $partContent, $matches)) {
$wholeTag = $matches[0];
array_shift($matches);
[$openTag, $prefix, , $postfix, $closeTag] = $matches;
$replaceXml = $openTag . $prefix . $closeTag . $xmlImage . $openTag . $postfix . $closeTag;
// replace on each iteration, because in one tag we can have 2+ inline variables => before proceed next variable we need to change $partContent
$partContent = $this->setValueForPart($wholeTag, $replaceXml, $partContent, $limit);
}
if (++$i >= $limit) {
break;
}
}
}
}
}
/**
* Returns count of all variables in template.
*
* @return array
*/
public function getVariableCount()
{
$variables = $this->getVariablesForPart($this->tempDocumentMainPart);
foreach ($this->tempDocumentHeaders as $headerXML) {
$variables = array_merge(
$variables,
$this->getVariablesForPart($headerXML)
);
}
foreach ($this->tempDocumentFooters as $footerXML) {
$variables = array_merge(
$variables,
$this->getVariablesForPart($footerXML)
);
}
return array_count_values($variables);
}
/**
* Returns array of all variables in template.
*
* @return string[]
*/
public function getVariables()
{
return array_keys($this->getVariableCount());
}
/**
* Clone a table row in a template document.
*
* @param string $search
* @param int $numberOfClones
*/
public function cloneRow($search, $numberOfClones): void
{
$search = static::ensureMacroCompleted($search);
$tagPos = strpos($this->tempDocumentMainPart, $search);
if (!$tagPos) {
throw new Exception('Can not clone row, template variable not found or variable contains markup.');
}
$rowStart = $this->findRowStart($tagPos);
$rowEnd = $this->findRowEnd($tagPos);
$xmlRow = $this->getSlice($rowStart, $rowEnd);
// Check if there's a cell spanning multiple rows.
if (preg_match('#<w:vMerge w:val="restart"/>#', $xmlRow)) {
// $extraRowStart = $rowEnd;
$extraRowEnd = $rowEnd;
while (true) {
$extraRowStart = $this->findRowStart($extraRowEnd + 1);
$extraRowEnd = $this->findRowEnd($extraRowEnd + 1);
// If extraRowEnd is lower then 7, there was no next row found.
if ($extraRowEnd < 7) {
break;
}
// If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row.
$tmpXmlRow = $this->getSlice($extraRowStart, $extraRowEnd);
if (!preg_match('#<w:vMerge/>#', $tmpXmlRow) &&
!preg_match('#<w:vMerge w:val="continue"\s*/>#', $tmpXmlRow)
) {
break;
}
// This row was a spanned row, update $rowEnd and search for the next row.
$rowEnd = $extraRowEnd;
}
$xmlRow = $this->getSlice($rowStart, $rowEnd);
}
$result = $this->getSlice(0, $rowStart);
$result .= implode('', $this->indexClonedVariables($numberOfClones, $xmlRow));
$result .= $this->getSlice($rowEnd);
$this->tempDocumentMainPart = $result;
}
/**
* Delete a table row in a template document.
*/
public function deleteRow(string $search): void
{
if (self::$macroOpeningChars !== substr($search, 0, 2) && self::$macroClosingChars !== substr($search, -1)) {
$search = self::$macroOpeningChars . $search . self::$macroClosingChars;
}
$tagPos = strpos($this->tempDocumentMainPart, $search);
if (!$tagPos) {
throw new Exception(sprintf('Can not delete row %s, template variable not found or variable contains markup.', $search));
}
$tableStart = $this->findTableStart($tagPos);
$tableEnd = $this->findTableEnd($tagPos);
$xmlTable = $this->getSlice($tableStart, $tableEnd);
if (substr_count($xmlTable, '<w:tr') === 1) {
$this->tempDocumentMainPart = $this->getSlice(0, $tableStart) . $this->getSlice($tableEnd);
return;
}
$rowStart = $this->findRowStart($tagPos);
$rowEnd = $this->findRowEnd($tagPos);
$xmlRow = $this->getSlice($rowStart, $rowEnd);
$this->tempDocumentMainPart = $this->getSlice(0, $rowStart) . $this->getSlice($rowEnd);
// Check if there's a cell spanning multiple rows.
if (preg_match('#<w:vMerge w:val="restart"/>#', $xmlRow)) {
$extraRowStart = $rowStart;
while (true) {
$extraRowStart = $this->findRowStart($extraRowStart + 1);
$extraRowEnd = $this->findRowEnd($extraRowStart + 1);
// If extraRowEnd is lower then 7, there was no next row found.
if ($extraRowEnd < 7) {
break;
}
// If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row.
$tmpXmlRow = $this->getSlice($extraRowStart, $extraRowEnd);
if (!preg_match('#<w:vMerge/>#', $tmpXmlRow) &&
!preg_match('#<w:vMerge w:val="continue" />#', $tmpXmlRow)
) {
break;
}
$tableStart = $this->findTableStart($extraRowEnd + 1);
$tableEnd = $this->findTableEnd($extraRowEnd + 1);
$xmlTable = $this->getSlice($tableStart, $tableEnd);
if (substr_count($xmlTable, '<w:tr') === 1) {
$this->tempDocumentMainPart = $this->getSlice(0, $tableStart) . $this->getSlice($tableEnd);
return;
}
$this->tempDocumentMainPart = $this->getSlice(0, $extraRowStart) . $this->getSlice($extraRowEnd);
}
}
}
/**
* Clones a table row and populates it's values from a two-dimensional array in a template document.
*
* @param string $search
* @param array $values
*/
public function cloneRowAndSetValues($search, $values): void
{
$this->cloneRow($search, count($values));
foreach ($values as $rowKey => $rowData) {
$rowNumber = $rowKey + 1;
foreach ($rowData as $macro => $replace) {
$this->setValue($macro . '#' . $rowNumber, $replace);
}
}
}
/**
* Clone a block.
*
* @param string $blockname
* @param int $clones How many time the block should be cloned
* @param bool $replace
* @param bool $indexVariables If true, any variables inside the block will be indexed (postfixed with #1, #2, ...)
* @param array $variableReplacements Array containing replacements for macros found inside the block to clone
*
* @return null|string
*/
public function cloneBlock($blockname, $clones = 1, $replace = true, $indexVariables = false, $variableReplacements = null)
{
$xmlBlock = null;
$matches = [];
$escapedMacroOpeningChars = self::$macroOpeningChars;
$escapedMacroClosingChars = self::$macroClosingChars;
preg_match(
//'/(.*((?s)<w:p\b(?:(?!<w:p\b).)*?\{{' . $blockname . '}<\/w:.*?p>))(.*)((?s)<w:p\b(?:(?!<w:p\b).)[^$]*?\{{\/' . $blockname . '}<\/w:.*?p>)/is',
'/(.*((?s)<w:p\b(?:(?!<w:p\b).)*?\\' . $escapedMacroOpeningChars . $blockname . $escapedMacroClosingChars . '<\/w:.*?p>))(.*)((?s)<w:p\b(?:(?!<w:p\b).)[^$]*?\\' . $escapedMacroOpeningChars . '\/' . $blockname . $escapedMacroClosingChars . '<\/w:.*?p>)/is',
//'/(.*((?s)<w:p\b(?:(?!<w:p\b).)*?\\'. $escapedMacroOpeningChars . $blockname . '}<\/w:.*?p>))(.*)((?s)<w:p\b(?:(?!<w:p\b).)[^$]*?\\'.$escapedMacroOpeningChars.'\/' . $blockname . '}<\/w:.*?p>)/is',
$this->tempDocumentMainPart,
$matches
);
if (isset($matches[3])) {
$xmlBlock = $matches[3];
if ($indexVariables) {
$cloned = $this->indexClonedVariables($clones, $xmlBlock);
} elseif ($variableReplacements !== null && is_array($variableReplacements)) {
$cloned = $this->replaceClonedVariables($variableReplacements, $xmlBlock);
} else {
$cloned = [];
for ($i = 1; $i <= $clones; ++$i) {
$cloned[] = $xmlBlock;
}
}
if ($replace) {
$this->tempDocumentMainPart = str_replace(
$matches[2] . $matches[3] . $matches[4],
implode('', $cloned),
$this->tempDocumentMainPart
);
}
}
return $xmlBlock;
}
/**
* Replace a block.
*
* @param string $blockname
* @param string $replacement
*/
public function replaceBlock($blockname, $replacement): void
{
$matches = [];
$escapedMacroOpeningChars = preg_quote(self::$macroOpeningChars);
$escapedMacroClosingChars = preg_quote(self::$macroClosingChars);
preg_match(
'/(<\?xml.*)(<w:p.*>' . $escapedMacroOpeningChars . $blockname . $escapedMacroClosingChars . '<\/w:.*?p>)(.*)(<w:p.*' . $escapedMacroOpeningChars . '\/' . $blockname . $escapedMacroClosingChars . '<\/w:.*?p>)/is',
$this->tempDocumentMainPart,
$matches
);
if (isset($matches[3])) {
$this->tempDocumentMainPart = str_replace(
$matches[2] . $matches[3] . $matches[4],
$replacement,
$this->tempDocumentMainPart
);
}
}
/**
* Delete a block of text.
*
* @param string $blockname
*/
public function deleteBlock($blockname): void
{
$this->replaceBlock($blockname, '');
}
/**
* Automatically Recalculate Fields on Open.
*
* @param bool $update
*/
public function setUpdateFields($update = true): void
{
$string = $update ? 'true' : 'false';
$matches = [];
if (preg_match('/<w:updateFields w:val=\"(true|false|1|0|on|off)\"\/>/', $this->tempDocumentSettingsPart, $matches)) {
$this->tempDocumentSettingsPart = str_replace($matches[0], '<w:updateFields w:val="' . $string . '"/>', $this->tempDocumentSettingsPart);
} else {
$this->tempDocumentSettingsPart = str_replace('</w:settings>', '<w:updateFields w:val="' . $string . '"/></w:settings>', $this->tempDocumentSettingsPart);
}
}
/**
* Saves the result document.
*
* @return string
*/
public function save()
{
foreach ($this->tempDocumentHeaders as $index => $xml) {
$this->savePartWithRels($this->getHeaderName($index), $xml);
}
$this->savePartWithRels($this->getMainPartName(), $this->tempDocumentMainPart);