Blame view

addons/fastflow/library/PHPWord-master/src/PhpWord/TemplateProcessor.php 45.9 KB
2db47680   hexiaodong   chore: 初始提交 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
  <?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
   * @copyright   2010-2018 PHPWord contributors
   * @license     http://www.gnu.org/licenses/lgpl.txt LGPL version 3
   */
  
  namespace PhpOffice\PhpWord;
  
  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;
  
  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 = array();
  
      /**
       * Content of footers (in XML format) of the temporary document
       *
       * @var string[]
       */
      protected $tempDocumentFooters = array();
  
      /**
       * Document relations (in XML format) of the temporary document.
       *
       * @var string[]
       */
      protected $tempDocumentRelations = array();
  
      /**
       * Document content types (in XML format) of the temporary document.
       *
       * @var string
       */
      protected $tempDocumentContentTypes = '';
  
      /**
       * new inserted images list
       *
       * @var string[]
       */
      protected $tempDocumentNewImages = array();
  
      /**
       * @since 0.12.0 Throws CreateTemporaryFileException and CopyFileException instead of Exception
       *
       * @param string $documentTemplate The fully qualified template filename
       *
       * @throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException
       * @throws \PhpOffice\PhpWord\Exception\CopyFileException
       */
      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());
      }
  
      /**
       * 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 \PhpOffice\PhpWord\Shared\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
       *
       * @throws \PhpOffice\PhpWord\Exception\Exception
       *
       * @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
       *
       * @throws \PhpOffice\PhpWord\Exception\Exception
       */
      public function applyXslStyleSheet($xslDomDocument, $xslOptions = array(), $xslOptionsUri = '')
      {
          $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) !== '${' && substr($macro, -1) !== '}') {
              $macro = '${' . $macro . '}';
          }
  
          return $macro;
      }
  
      /**
       * @param string $subject
       *
       * @return string
       */
      protected static function ensureUtf8Encoded($subject)
      {
          if (!Text::isUTF8($subject)) {
              $subject = utf8_encode($subject);
          }
  
          return $subject;
      }
  
      /**
       * @param string $search
       * @param \PhpOffice\PhpWord\Element\AbstractElement $complexType
       */
      public function setComplexValue($search, \PhpOffice\PhpWord\Element\AbstractElement $complexType)
      {
          $elementName = substr(get_class($complexType), strrpos(get_class($complexType), '\\') + 1);
          $objectClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Element\\' . $elementName;
  
          $xmlWriter = new XMLWriter();
          /** @var \PhpOffice\PhpWord\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
       * @param \PhpOffice\PhpWord\Element\AbstractElement $complexType
       */
      public function setComplexBlock($search, \PhpOffice\PhpWord\Element\AbstractElement $complexType)
      {
          $elementName = substr(get_class($complexType), strrpos(get_class($complexType), '\\') + 1);
          $objectClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Element\\' . $elementName;
  
          $xmlWriter = new XMLWriter();
          /** @var \PhpOffice\PhpWord\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)
      {
          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);
          }
  
          $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.
       *
       * @param array $values
       */
      public function setValues(array $values)
      {
          foreach ($values as $macro => $replace) {
              $this->setValue($macro, $replace);
          }
      }
  
      /**
       * @param string $search
       * @param \PhpOffice\PhpWord\Element\AbstractElement $complexType
       */
      public function setChart($search, \PhpOffice\PhpWord\Element\AbstractElement $chart)
      {
          $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 \PhpOffice\PhpWord\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 = array();
          // 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
                  list($argName, $argValue) = explode('=', $varArg, 2);
                  $argName = strtolower($argName);
                  if ($argName == 'size') {
                      list($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
                  list($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 (is_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 (is_null($value)) {
              $value = $defaultValue;
          }
          if (is_numeric($value)) {
              $value .= 'px';
          }
  
          return $value;
      }
  
      private function fixImageWidthHeightRatio(&$width, &$height, $actualWidth, $actualHeight)
      {
          $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 = array();
              preg_match("/\d([a-z%]+)$/", $height, $matches);
              $width = $widthFloat . $matches[1];
          } elseif ($height === '') { // defined height is empty
              $widthFloat = (float) $width;
              $heightFloat = $widthFloat / $imageRatio;
              $matches = array();
              preg_match("/\d([a-z%]+)$/", $width, $matches);
              $height = $heightFloat . $matches[1];
          } else { // we have defined size, but we need also check it aspect ratio
              $widthMatches = array();
              preg_match("/\d([a-z%]+)$/", $width, $widthMatches);
              $heightMatches = array();
              preg_match("/\d([a-z%]+)$/", $height, $heightMatches);
              // try to fix only if dimensions are same
              if ($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, isset($varInlineArgs['width']) ? $varInlineArgs['width'] : null, 115);
          $height = $this->chooseImageDimension($height, isset($varInlineArgs['height']) ? $varInlineArgs['height'] : null, 70);
  
          $imageData = @getimagesize($imgPath);
          if (!is_array($imageData)) {
              throw new Exception(sprintf('Invalid image: %s', $imgPath));
          }
          list($actualWidth, $actualHeight, $imageType) = $imageData;
  
          // fix aspect ratio (by default)
          if (is_null($ratio) && isset($varInlineArgs['ratio'])) {
              $ratio = $varInlineArgs['ratio'];
          }
          if (is_null($ratio) || !in_array(strtolower($ratio), array('', '-', 'f', 'false'))) {
              $this->fixImageWidthHeightRatio($width, $height, $actualWidth, $actualHeight);
          }
  
          $imageAttrs = array(
              'src'    => $imgPath,
              'mime'   => image_type_to_mime_type($imageType),
              'width'  => $width,
              'height' => $height,
          );
  
          return $imageAttrs;
      }
  
      private function addImageToRelations($partFileName, $rid, $imgPath, $imageMimeType)
      {
          // 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 = array(
              '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(array('{IMG}', '{EXT}'), array($imgName, $imgExt), $typeTpl);
              $this->tempDocumentContentTypes = str_replace('</Types>', $xmlImageType, $this->tempDocumentContentTypes) . '</Types>';
          }
  
          $xmlImageRelation = str_replace(array('{RID}', '{IMG}'), array($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)
      {
          // prepare $search_replace
          if (!is_array($search)) {
              $search = array($search);
          }
  
          $replacesList = array();
          if (!is_array($replace) || isset($replace['path'])) {
              $replacesList[] = $replace;
          } else {
              $replacesList = array_values($replace);
          }
  
          $searchReplace = array();
          foreach ($search as $searchIdx => $searchString) {
              $searchReplace[$searchString] = isset($replacesList[$searchIdx]) ? $replacesList[$searchIdx] : $replacesList[0];
          }
  
          // collect document parts
          $searchParts = array(
              $this->getMainPartName() => &$this->tempDocumentMainPart,
          );
          foreach (array_keys($this->tempDocumentHeaders) as $headerIndex) {
              $searchParts[$this->getHeaderName($headerIndex)] = &$this->tempDocumentHeaders[$headerIndex];
          }
          foreach (array_keys($this->tempDocumentFooters) as $headerIndex) {
              $searchParts[$this->getFooterName($headerIndex)] = &$this->tempDocumentFooters[$headerIndex];
          }
  
          // 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"><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(array('{RID}', '{WIDTH}', '{HEIGHT}'), array($rid, $preparedImageAttrs['width'], $preparedImageAttrs['height']), $imgTpl);
  
                      // replace variable
                      $varNameWithArgsFixed = static::ensureMacroCompleted($varNameWithArgs);
                      $matches = array();
                      if (preg_match('/(<[^<]+>)([^<]*)(' . preg_quote($varNameWithArgsFixed) . ')([^>]*)(<[^>]+>)/Uu', $partContent, $matches)) {
                          $wholeTag = $matches[0];
                          array_shift($matches);
                          list($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
       *
       * @throws \PhpOffice\PhpWord\Exception\Exception
       */
      public function cloneRow($search, $numberOfClones)
      {
          $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;
      }
  
      /**
       * 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)
      {
          $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 string|null
       */
      public function cloneBlock($blockname, $clones = 1, $replace = true, $indexVariables = false, $variableReplacements = null)
      {
          $xmlBlock = null;
          $matches = array();
          preg_match(
              '/(.*((?s)<w:p\b(?:(?!<w:p\b).)*?\${' . $blockname . '}<\/w:.*?p>))(.*)((?s)<w:p\b(?:(?!<w:p\b).)[^$]*?\${\/' . $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 = array();
                  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)
      {
          $matches = array();
          preg_match(
              '/(<\?xml.*)(<w:p.*>\${' . $blockname . '}<\/w:.*?p>)(.*)(<w:p.*\${\/' . $blockname . '}<\/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)
      {
          $this->replaceBlock($blockname, '');
      }
  
      /**
       * Automatically Recalculate Fields on Open
       *
       * @param bool $update
       */
      public function setUpdateFields($update = true)
      {
          $string = $update ? 'true' : 'false';
          $matches = array();
          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.
       *
       * @throws \PhpOffice\PhpWord\Exception\Exception
       *
       * @return string
       */
      public function save()
      {
          foreach ($this->tempDocumentHeaders as $index => $xml) {
              $this->savePartWithRels($this->getHeaderName($index), $xml);
          }
  
          $this->savePartWithRels($this->getMainPartName(), $this->tempDocumentMainPart);
          $this->savePartWithRels($this->getSettingsPartName(), $this->tempDocumentSettingsPart);
  
          foreach ($this->tempDocumentFooters as $index => $xml) {
              $this->savePartWithRels($this->getFooterName($index), $xml);
          }
  
          $this->zipClass->addFromString($this->getDocumentContentTypesName(), $this->tempDocumentContentTypes);
  
          // Close zip file
          if (false === $this->zipClass->close()) {
              throw new Exception('Could not close zip file.'); // @codeCoverageIgnore
          }
  
          return $this->tempDocumentFilename;
      }
  
      /**
       * @param string $fileName
       * @param string $xml
       */
      protected function savePartWithRels($fileName, $xml)
      {
          $this->zipClass->addFromString($fileName, $xml);
          if (isset($this->tempDocumentRelations[$fileName])) {
              $relsFileName = $this->getRelationsName($fileName);
              $this->zipClass->addFromString($relsFileName, $this->tempDocumentRelations[$fileName]);
          }
      }
  
      /**
       * Saves the result document to the user defined file.
       *
       * @since 0.8.0
       *
       * @param string $fileName
       */
      public function saveAs($fileName)
      {
          $tempFileName = $this->save();
  
          if (file_exists($fileName)) {
              unlink($fileName);
          }
  
          /*
           * Note: we do not use `rename` function here, because it loses file ownership data on Windows platform.
           * As a result, user cannot open the file directly getting "Access denied" message.
           *
           * @see https://github.com/PHPOffice/PHPWord/issues/532
           */
          copy($tempFileName, $fileName);
          unlink($tempFileName);
      }
  
      /**
       * Finds parts of broken macros and sticks them together.
       * Macros, while being edited, could be implicitly broken by some of the word processors.
       *
       * @param string $documentPart The document part in XML representation
       *
       * @return string
       */
      protected function fixBrokenMacros($documentPart)
      {
          return preg_replace_callback(
              '/\$(?:\{|[^{$]*\>\{)[^}$]*\}/U',
              function ($match) {
                  return strip_tags($match[0]);
              },
              $documentPart
          );
      }
  
      /**
       * Find and replace macros in the given XML section.
       *
       * @param mixed $search
       * @param mixed $replace
       * @param string $documentPartXML
       * @param int $limit
       *
       * @return string
       */
      protected function setValueForPart($search, $replace, $documentPartXML, $limit)
      {
          // Note: we can't use the same function for both cases here, because of performance considerations.
          if (self::MAXIMUM_REPLACEMENTS_DEFAULT === $limit) {
              return str_replace($search, $replace, $documentPartXML);
          }
          $regExpEscaper = new RegExp();
  
          return preg_replace($regExpEscaper->escape($search), $replace, $documentPartXML, $limit);
      }
  
      /**
       * Find all variables in $documentPartXML.
       *
       * @param string $documentPartXML
       *
       * @return string[]
       */
      protected function getVariablesForPart($documentPartXML)
      {
          $matches = array();
          preg_match_all('/\$\{(.*?)}/i', $documentPartXML, $matches);
  
          return $matches[1];
      }
  
      /**
       * Get the name of the header file for $index.
       *
       * @param int $index
       *
       * @return string
       */
      protected function getHeaderName($index)
      {
          return sprintf('word/header%d.xml', $index);
      }
  
      /**
       * Usually, the name of main part document will be 'document.xml'. However, some .docx files (possibly those from Office 365, experienced also on documents from Word Online created from blank templates) have file 'document22.xml' in their zip archive instead of 'document.xml'. This method searches content types file to correctly determine the file name.
       *
       * @return string
       */
      protected function getMainPartName()
      {
          $contentTypes = $this->zipClass->getFromName('[Content_Types].xml');
  
          $pattern = '~PartName="\/(word\/document.*?\.xml)" ContentType="application\/vnd\.openxmlformats-officedocument\.wordprocessingml\.document\.main\+xml"~';
  
          $matches = array();
          preg_match($pattern, $contentTypes, $matches);
  
          return array_key_exists(1, $matches) ? $matches[1] : 'word/document.xml';
      }
  
      /**
       * The name of the file containing the Settings part
       *
       * @return string
       */
      protected function getSettingsPartName()
      {
          return 'word/settings.xml';
      }
  
      /**
       * Get the name of the footer file for $index.
       *
       * @param int $index
       *
       * @return string
       */
      protected function getFooterName($index)
      {
          return sprintf('word/footer%d.xml', $index);
      }
  
      /**
       * Get the name of the relations file for document part.
       *
       * @param string $documentPartName
       *
       * @return string
       */
      protected function getRelationsName($documentPartName)
      {
          return 'word/_rels/' . pathinfo($documentPartName, PATHINFO_BASENAME) . '.rels';
      }
  
      protected function getNextRelationsIndex($documentPartName)
      {
          if (isset($this->tempDocumentRelations[$documentPartName])) {
              $candidate = substr_count($this->tempDocumentRelations[$documentPartName], '<Relationship');
              while (strpos($this->tempDocumentRelations[$documentPartName], 'Id="rId' . $candidate . '"') !== false) {
                  $candidate++;
              }
  
              return $candidate;
          }
  
          return 1;
      }
  
      /**
       * @return string
       */
      protected function getDocumentContentTypesName()
      {
          return '[Content_Types].xml';
      }
  
      /**
       * Find the start position of the nearest table row before $offset.
       *
       * @param int $offset
       *
       * @throws \PhpOffice\PhpWord\Exception\Exception
       *
       * @return int
       */
      protected function findRowStart($offset)
      {
          $rowStart = strrpos($this->tempDocumentMainPart, '<w:tr ', ((strlen($this->tempDocumentMainPart) - $offset) * -1));
  
          if (!$rowStart) {
              $rowStart = strrpos($this->tempDocumentMainPart, '<w:tr>', ((strlen($this->tempDocumentMainPart) - $offset) * -1));
          }
          if (!$rowStart) {
              throw new Exception('Can not find the start position of the row to clone.');
          }
  
          return $rowStart;
      }
  
      /**
       * Find the end position of the nearest table row after $offset.
       *
       * @param int $offset
       *
       * @return int
       */
      protected function findRowEnd($offset)
      {
          return strpos($this->tempDocumentMainPart, '</w:tr>', $offset) + 7;
      }
  
      /**
       * Get a slice of a string.
       *
       * @param int $startPosition
       * @param int $endPosition
       *
       * @return string
       */
      protected function getSlice($startPosition, $endPosition = 0)
      {
          if (!$endPosition) {
              $endPosition = strlen($this->tempDocumentMainPart);
          }
  
          return substr($this->tempDocumentMainPart, $startPosition, ($endPosition - $startPosition));
      }
  
      /**
       * Replaces variable names in cloned
       * rows/blocks with indexed names
       *
       * @param int $count
       * @param string $xmlBlock
       *
       * @return string
       */
      protected function indexClonedVariables($count, $xmlBlock)
      {
          $results = array();
          for ($i = 1; $i <= $count; $i++) {
              $results[] = preg_replace('/\$\{([^:]*?)(:.*?)?\}/', '\${\1#' . $i . '\2}', $xmlBlock);
          }
  
          return $results;
      }
  
      /**
       * Raplaces variables with values from array, array keys are the variable names
       *
       * @param array $variableReplacements
       * @param string $xmlBlock
       *
       * @return string[]
       */
      protected function replaceClonedVariables($variableReplacements, $xmlBlock)
      {
          $results = array();
          foreach ($variableReplacements as $replacementArray) {
              $localXmlBlock = $xmlBlock;
              foreach ($replacementArray as $search => $replacement) {
                  $localXmlBlock = $this->setValueForPart(self::ensureMacroCompleted($search), $replacement, $localXmlBlock, self::MAXIMUM_REPLACEMENTS_DEFAULT);
              }
              $results[] = $localXmlBlock;
          }
  
          return $results;
      }
  
      /**
       * Replace an XML block surrounding a macro with a new block
       *
       * @param string $macro Name of macro
       * @param string $block New block content
       * @param string $blockType XML tag type of block
       * @return \PhpOffice\PhpWord\TemplateProcessor Fluent interface
       */
      public function replaceXmlBlock($macro, $block, $blockType = 'w:p')
      {
          $where = $this->findContainingXmlBlockForMacro($macro, $blockType);
          if (is_array($where)) {
              $this->tempDocumentMainPart = $this->getSlice(0, $where['start']) . $block . $this->getSlice($where['end']);
          }
  
          return $this;
      }
  
      /**
       * Find start and end of XML block containing the given macro
       * e.g. <w:p>...${macro}...</w:p>
       *
       * Note that only the first instance of the macro will be found
       *
       * @param string $macro Name of macro
       * @param string $blockType XML tag for block
       * @return bool|int[] FALSE if not found, otherwise array with start and end
       */
      protected function findContainingXmlBlockForMacro($macro, $blockType = 'w:p')
      {
          $macroPos = $this->findMacro($macro);
          if (0 > $macroPos) {
              return false;
          }
          $start = $this->findXmlBlockStart($macroPos, $blockType);
          if (0 > $start) {
              return false;
          }
          $end = $this->findXmlBlockEnd($start, $blockType);
          //if not found or if resulting string does not contain the macro we are searching for
          if (0 > $end || strstr($this->getSlice($start, $end), $macro) === false) {
              return false;
          }
  
          return array('start' => $start, 'end' => $end);
      }
  
      /**
       * Find the position of (the start of) a macro
       *
       * Returns -1 if not found, otherwise position of opening $
       *
       * Note that only the first instance of the macro will be found
       *
       * @param string $search Macro name
       * @param int $offset Offset from which to start searching
       * @return int -1 if macro not found
       */
      protected function findMacro($search, $offset = 0)
      {
          $search = static::ensureMacroCompleted($search);
          $pos = strpos($this->tempDocumentMainPart, $search, $offset);
  
          return ($pos === false) ? -1 : $pos;
      }
  
      /**
       * Find the start position of the nearest XML block start before $offset
       *
       * @param int $offset    Search position
       * @param string  $blockType XML Block tag
       * @return int -1 if block start not found
       */
      protected function findXmlBlockStart($offset, $blockType)
      {
          $reverseOffset = (strlen($this->tempDocumentMainPart) - $offset) * -1;
          // first try XML tag with attributes
          $blockStart = strrpos($this->tempDocumentMainPart, '<' . $blockType . ' ', $reverseOffset);
          // if not found, or if found but contains the XML tag without attribute
          if (false === $blockStart || strrpos($this->getSlice($blockStart, $offset), '<' . $blockType . '>')) {
              // also try XML tag without attributes
              $blockStart = strrpos($this->tempDocumentMainPart, '<' . $blockType . '>', $reverseOffset);
          }
  
          return ($blockStart === false) ? -1 : $blockStart;
      }
  
      /**
       * Find the nearest block end position after $offset
       *
       * @param int $offset    Search position
       * @param string  $blockType XML Block tag
       * @return int -1 if block end not found
       */
      protected function findXmlBlockEnd($offset, $blockType)
      {
          $blockEndStart = strpos($this->tempDocumentMainPart, '</' . $blockType . '>', $offset);
          // return position of end of tag if found, otherwise -1
  
          return ($blockEndStart === false) ? -1 : $blockEndStart + 3 + strlen($blockType);
      }
  
      /**
       * Splits a w:r/w:t into a list of w:r where each ${macro} is in a separate w:r
       *
       * @param string $text
       * @return string
       */
      protected function splitTextIntoTexts($text)
      {
          if (!$this->textNeedsSplitting($text)) {
              return $text;
          }
          $matches = array();
          if (preg_match('/(<w:rPr.*<\/w:rPr>)/i', $text, $matches)) {
              $extractedStyle = $matches[0];
          } else {
              $extractedStyle = '';
          }
  
          $unformattedText = preg_replace('/>\s+</', '><', $text);
          $result = str_replace(array('${', '}'), array('</w:t></w:r><w:r>' . $extractedStyle . '<w:t xml:space="preserve">${', '}</w:t></w:r><w:r>' . $extractedStyle . '<w:t xml:space="preserve">'), $unformattedText);
  
          return str_replace(array('<w:r>' . $extractedStyle . '<w:t xml:space="preserve"></w:t></w:r>', '<w:r><w:t xml:space="preserve"></w:t></w:r>', '<w:t>'), array('', '', '<w:t xml:space="preserve">'), $result);
      }
  
      /**
       * Returns true if string contains a macro that is not in it's own w:r
       *
       * @param string $text
       * @return bool
       */
      protected function textNeedsSplitting($text)
      {
          return preg_match('/[^>]\${|}[^<]/i', $text) == 1;
      }
  }