Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.76% covered (success)
97.76%
479 / 490
75.00% covered (warning)
75.00%
21 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
AbstractPart
97.76% covered (success)
97.76%
479 / 490
75.00% covered (warning)
75.00%
21 / 28
168
0.00% covered (danger)
0.00%
0 / 1
 read
n/a
0 / 0
n/a
0 / 0
0
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setRels
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setImageLoading
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 hasImageLoading
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getCommentReferences
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setCommentReferences
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setCommentReference
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 getCommentReference
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 readParagraph
98.82% covered (success)
98.82%
84 / 85
0.00% covered (danger)
0.00%
0 / 1
32
 readFormField
95.24% covered (success)
95.24%
60 / 63
0.00% covered (danger)
0.00%
0 / 1
27
 getHeadingDepth
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 readRun
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
7
 readRunChild
97.40% covered (success)
97.40%
75 / 77
0.00% covered (danger)
0.00%
0 / 1
28
 readRubyProperties
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 readTable
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
12
 readParagraphStyle
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
2
 readFontStyle
93.10% covered (success)
93.10%
27 / 29
0.00% covered (danger)
0.00%
0 / 1
4.01
 readTableStyle
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
7
 readTablePosition
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 readTableIndent
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 readCellStyle
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
3
 findPossibleElement
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 findPossibleAttribute
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 readStyleDefs
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
6
 readStyleDef
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 isOn
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
4
 getMediaTarget
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getTargetMode
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3/**
4 * This file is part of PHPWord - A pure PHP library for reading and writing
5 * word processing documents.
6 *
7 * PHPWord is free software distributed under the terms of the GNU Lesser
8 * General Public License version 3 as published by the Free Software Foundation.
9 *
10 * For the full copyright and license information, please read the LICENSE
11 * file that was distributed with this source code. For the full list of
12 * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
13 *
14 * @see         https://github.com/PHPOffice/PHPWord
15 *
16 * @license     http://www.gnu.org/licenses/lgpl.txt LGPL version 3
17 */
18
19namespace PhpOffice\PhpWord\Reader\Word2007;
20
21use DateTime;
22use DOMElement;
23use InvalidArgumentException;
24use PhpOffice\Math\Reader\OfficeMathML;
25use PhpOffice\PhpWord\ComplexType\RubyProperties;
26use PhpOffice\PhpWord\ComplexType\TblWidth as TblWidthComplexType;
27use PhpOffice\PhpWord\Element\AbstractContainer;
28use PhpOffice\PhpWord\Element\AbstractElement;
29use PhpOffice\PhpWord\Element\FormField;
30use PhpOffice\PhpWord\Element\Ruby;
31use PhpOffice\PhpWord\Element\Text;
32use PhpOffice\PhpWord\Element\TextRun;
33use PhpOffice\PhpWord\Element\TrackChange;
34use PhpOffice\PhpWord\PhpWord;
35use PhpOffice\PhpWord\Shared\XMLReader;
36
37/**
38 * Abstract part reader.
39 *
40 * This class is inherited by ODText reader
41 *
42 * @since 0.10.0
43 */
44abstract class AbstractPart
45{
46    /**
47     * Conversion method.
48     *
49     * @const int
50     */
51    const READ_VALUE = 'attributeValue';            // Read attribute value
52    const READ_EQUAL = 'attributeEquals';           // Read `true` when attribute value equals specified value
53    const READ_TRUE = 'attributeTrue';              // Read `true` when element exists
54    const READ_FALSE = 'attributeFalse';            // Read `false` when element exists
55    const READ_SIZE = 'attributeMultiplyByTwo';     // Read special attribute value for Font::$size
56
57    /**
58     * Document file.
59     *
60     * @var string
61     */
62    protected $docFile;
63
64    /**
65     * XML file.
66     *
67     * @var string
68     */
69    protected $xmlFile;
70
71    /**
72     * Part relationships.
73     *
74     * @var array
75     */
76    protected $rels = [];
77
78    /**
79     * Comment references.
80     *
81     * @var array<string, array<string, AbstractElement>>
82     */
83    protected $commentRefs = [];
84
85    /**
86     * Image Loading.
87     *
88     * @var bool
89     */
90    protected $imageLoading = true;
91
92    /**
93     * Read part.
94     */
95    abstract public function read(PhpWord $phpWord);
96
97    /**
98     * Create new instance.
99     *
100     * @param string $docFile
101     * @param string $xmlFile
102     */
103    public function __construct($docFile, $xmlFile)
104    {
105        $this->docFile = $docFile;
106        $this->xmlFile = $xmlFile;
107    }
108
109    /**
110     * Set relationships.
111     *
112     * @param array $value
113     */
114    public function setRels($value): void
115    {
116        $this->rels = $value;
117    }
118
119    public function setImageLoading(bool $value): self
120    {
121        $this->imageLoading = $value;
122
123        return $this;
124    }
125
126    public function hasImageLoading(): bool
127    {
128        return $this->imageLoading;
129    }
130
131    /**
132     * Get comment references.
133     *
134     * @return array<string, array<string, null|AbstractElement>>
135     */
136    public function getCommentReferences(): array
137    {
138        return $this->commentRefs;
139    }
140
141    /**
142     * Set comment references.
143     *
144     * @param array<string, array<string, null|AbstractElement>> $commentRefs
145     */
146    public function setCommentReferences(array $commentRefs): self
147    {
148        $this->commentRefs = $commentRefs;
149
150        return $this;
151    }
152
153    /**
154     * Set comment reference.
155     */
156    private function setCommentReference(string $type, string $id, AbstractElement $element): self
157    {
158        if (!in_array($type, ['start', 'end'])) {
159            throw new InvalidArgumentException('Type must be "start" or "end"');
160        }
161
162        if (!array_key_exists($id, $this->commentRefs)) {
163            $this->commentRefs[$id] = [
164                'start' => null,
165                'end' => null,
166            ];
167        }
168        $this->commentRefs[$id][$type] = $element;
169
170        return $this;
171    }
172
173    /**
174     * Get comment reference.
175     *
176     * @return array<string, null|AbstractElement>
177     */
178    protected function getCommentReference(string $id): array
179    {
180        if (!array_key_exists($id, $this->commentRefs)) {
181            throw new InvalidArgumentException(sprintf('Comment with id %s isn\'t referenced in document', $id));
182        }
183
184        return $this->commentRefs[$id];
185    }
186
187    /**
188     * Read w:p.
189     *
190     * @param AbstractContainer $parent
191     * @param string $docPart
192     *
193     * @todo Get font style for preserve text
194     */
195    protected function readParagraph(XMLReader $xmlReader, DOMElement $domNode, $parent, $docPart = 'document'): void
196    {
197        // Paragraph style
198        $paragraphStyle = $xmlReader->elementExists('w:pPr', $domNode) ? $this->readParagraphStyle($xmlReader, $domNode) : null;
199
200        if ($xmlReader->elementExists('w:r/w:fldChar/w:ffData', $domNode)) {
201            // FormField
202            $partOfFormField = false;
203            $formNodes = [];
204            $formType = null;
205            $textRunContainers = $xmlReader->countElements('w:r|w:ins|w:del|w:hyperlink|w:smartTag', $domNode);
206            if ($textRunContainers > 0) {
207                $nodes = $xmlReader->getElements('*', $domNode);
208                $paragraph = $parent->addTextRun($paragraphStyle);
209                foreach ($nodes as $node) {
210                    if ($xmlReader->elementExists('w:fldChar/w:ffData', $node)) {
211                        $partOfFormField = true;
212                        $formNodes[] = $node;
213                        if ($xmlReader->elementExists('w:fldChar/w:ffData/w:ddList', $node)) {
214                            $formType = 'dropdown';
215                        } elseif ($xmlReader->elementExists('w:fldChar/w:ffData/w:textInput', $node)) {
216                            $formType = 'textinput';
217                        } elseif ($xmlReader->elementExists('w:fldChar/w:ffData/w:checkBox', $node)) {
218                            $formType = 'checkbox';
219                        }
220                    } elseif ($partOfFormField &&
221                        $xmlReader->elementExists('w:fldChar', $node) &&
222                        'end' == $xmlReader->getAttribute('w:fldCharType', $node, 'w:fldChar')
223                    ) {
224                        $formNodes[] = $node;
225                        $partOfFormField = false;
226                        // Process the form fields
227                        $this->readFormField($xmlReader, $formNodes, $paragraph, $paragraphStyle, $formType);
228                    } elseif ($partOfFormField) {
229                        $formNodes[] = $node;
230                    } else {
231                        // normal runs
232                        $this->readRun($xmlReader, $node, $paragraph, $docPart, $paragraphStyle);
233                    }
234                }
235            }
236        } elseif ($xmlReader->elementExists('w:r/w:instrText', $domNode)) {
237            // PreserveText
238            $ignoreText = false;
239            $textContent = '';
240            $fontStyle = $this->readFontStyle($xmlReader, $domNode);
241            $nodes = $xmlReader->getElements('w:r', $domNode);
242            foreach ($nodes as $node) {
243                if ($xmlReader->elementExists('w:lastRenderedPageBreak', $node)) {
244                    $parent->addPageBreak();
245                }
246                $instrText = $xmlReader->getValue('w:instrText', $node);
247                if (null !== $instrText) {
248                    $textContent .= '{' . $instrText . '}';
249                } else {
250                    if ($xmlReader->elementExists('w:fldChar', $node)) {
251                        $fldCharType = $xmlReader->getAttribute('w:fldCharType', $node, 'w:fldChar');
252                        if ('begin' == $fldCharType) {
253                            $ignoreText = true;
254                        } elseif ('end' == $fldCharType) {
255                            $ignoreText = false;
256                        }
257                    }
258                    if (false === $ignoreText) {
259                        $textContent .= $xmlReader->getValue('w:t', $node);
260                    }
261                }
262            }
263            $parent->addPreserveText(htmlspecialchars($textContent, ENT_QUOTES, 'UTF-8'), $fontStyle, $paragraphStyle);
264
265            return;
266        }
267
268        // Formula
269        $xmlReader->registerNamespace('m', 'http://schemas.openxmlformats.org/officeDocument/2006/math');
270        if ($xmlReader->elementExists('m:oMath', $domNode)) {
271            $mathElement = $xmlReader->getElement('m:oMath', $domNode);
272            $mathXML = $mathElement->ownerDocument->saveXML($mathElement);
273            if (is_string($mathXML)) {
274                $reader = new OfficeMathML();
275                $math = $reader->read($mathXML);
276
277                $parent->addFormula($math);
278            }
279
280            return;
281        }
282
283        // List item
284        if ($xmlReader->elementExists('w:pPr/w:numPr', $domNode)) {
285            $numId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:numId');
286            $levelId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:ilvl');
287            $nodes = $xmlReader->getElements('*', $domNode);
288
289            $listItemRun = $parent->addListItemRun($levelId, "PHPWordList{$numId}", $paragraphStyle);
290
291            foreach ($nodes as $node) {
292                $this->readRun($xmlReader, $node, $listItemRun, $docPart, $paragraphStyle);
293            }
294
295            return;
296        }
297
298        // Heading or Title
299        $headingDepth = $xmlReader->elementExists('w:pPr', $domNode) ? $this->getHeadingDepth($paragraphStyle) : null;
300        if ($headingDepth !== null) {
301            $textContent = null;
302            $nodes = $xmlReader->getElements('w:r|w:hyperlink', $domNode);
303            $hasRubyElement = $xmlReader->elementExists('w:r/w:ruby', $domNode);
304            if ($nodes->length === 1 && !$hasRubyElement) {
305                $textContent = htmlspecialchars($xmlReader->getValue('w:t', $nodes->item(0)) ?? '', ENT_QUOTES, 'UTF-8');
306            } else {
307                $textContent = new TextRun($paragraphStyle);
308                foreach ($nodes as $node) {
309                    $this->readRun($xmlReader, $node, $textContent, $docPart, $paragraphStyle);
310                }
311            }
312            $parent->addTitle($textContent, $headingDepth);
313
314            return;
315        }
316
317        // Text and TextRun
318        $textRunContainers = $xmlReader->countElements('w:r|w:ins|w:del|w:hyperlink|w:smartTag|w:commentReference|w:commentRangeStart|w:commentRangeEnd', $domNode);
319        if (0 === $textRunContainers) {
320            $parent->addTextBreak(1, $paragraphStyle);
321        } else {
322            $nodes = $xmlReader->getElements('*', $domNode);
323            $paragraph = $parent->addTextRun($paragraphStyle);
324            foreach ($nodes as $node) {
325                $this->readRun($xmlReader, $node, $paragraph, $docPart, $paragraphStyle);
326            }
327        }
328    }
329
330    /**
331     * @param DOMElement[] $domNodes
332     * @param AbstractContainer $parent
333     * @param mixed $paragraphStyle
334     * @param string $formType
335     */
336    private function readFormField(XMLReader $xmlReader, array $domNodes, $parent, $paragraphStyle, $formType): void
337    {
338        if (!in_array($formType, ['textinput', 'checkbox', 'dropdown'])) {
339            return;
340        }
341
342        $formField = $parent->addFormField($formType, null, $paragraphStyle);
343        $ffData = $xmlReader->getElement('w:fldChar/w:ffData', $domNodes[0]);
344
345        foreach ($xmlReader->getElements('*', $ffData) as $node) {
346            /** @var DOMElement $node */
347            switch ($node->localName) {
348                case 'name':
349                    $formField->setName($node->getAttribute('w:val'));
350
351                    break;
352                case 'ddList':
353                    $listEntries = [];
354                    foreach ($xmlReader->getElements('*', $node) as $ddListNode) {
355                        switch ($ddListNode->localName) {
356                            case 'result':
357                                $formField->setValue($xmlReader->getAttribute('w:val', $ddListNode));
358
359                                break;
360                            case 'default':
361                                $formField->setDefault($xmlReader->getAttribute('w:val', $ddListNode));
362
363                                break;
364                            case 'listEntry':
365                                $listEntries[] = $xmlReader->getAttribute('w:val', $ddListNode);
366
367                                break;
368                        }
369                    }
370                    $formField->setEntries($listEntries);
371                    if (null !== $formField->getValue()) {
372                        /** @phpstan-ignore offsetAccess.notFound */
373                        $formField->setText($listEntries[$formField->getValue()]);
374                    }
375
376                    break;
377                case 'textInput':
378                    foreach ($xmlReader->getElements('*', $node) as $ddListNode) {
379                        switch ($ddListNode->localName) {
380                            case 'default':
381                                $formField->setDefault($xmlReader->getAttribute('w:val', $ddListNode));
382
383                                break;
384                            case 'format':
385                            case 'maxLength':
386                                break;
387                        }
388                    }
389
390                    break;
391                case 'checkBox':
392                    foreach ($xmlReader->getElements('*', $node) as $ddListNode) {
393                        switch ($ddListNode->localName) {
394                            case 'default':
395                                $formField->setDefault($xmlReader->getAttribute('w:val', $ddListNode));
396
397                                break;
398                            case 'checked':
399                                $formField->setValue($xmlReader->getAttribute('w:val', $ddListNode));
400
401                                break;
402                            case 'size':
403                            case 'sizeAuto':
404                                break;
405                        }
406                    }
407
408                    break;
409            }
410        }
411
412        if ('textinput' == $formType) {
413            $ignoreText = true;
414            $textContent = '';
415            foreach ($domNodes as $node) {
416                if ($xmlReader->elementExists('w:fldChar', $node)) {
417                    $fldCharType = $xmlReader->getAttribute('w:fldCharType', $node, 'w:fldChar');
418                    if ('separate' == $fldCharType) {
419                        $ignoreText = false;
420                    } elseif ('end' == $fldCharType) {
421                        $ignoreText = true;
422                    }
423                }
424
425                if (false === $ignoreText) {
426                    $textContent .= $xmlReader->getValue('w:t', $node);
427                }
428            }
429            $formField->setValue(htmlspecialchars($textContent, ENT_QUOTES, 'UTF-8'));
430            $formField->setText(htmlspecialchars($textContent, ENT_QUOTES, 'UTF-8'));
431        }
432    }
433
434    /**
435     * Returns the depth of the Heading, returns 0 for a Title.
436     *
437     * @return null|number
438     */
439    private function getHeadingDepth(?array $paragraphStyle = null)
440    {
441        if (is_array($paragraphStyle) && isset($paragraphStyle['styleName'])) {
442            if ('Title' === $paragraphStyle['styleName']) {
443                return 0;
444            }
445
446            $headingMatches = [];
447            preg_match('/Heading(\d)/', $paragraphStyle['styleName'], $headingMatches);
448            if (!empty($headingMatches)) {
449                return $headingMatches[1];
450            }
451        }
452
453        return null;
454    }
455
456    /**
457     * Read w:r.
458     *
459     * @param AbstractContainer $parent
460     * @param string $docPart
461     * @param mixed $paragraphStyle
462     *
463     * @todo Footnote paragraph style
464     */
465    protected function readRun(XMLReader $xmlReader, DOMElement $domNode, $parent, $docPart, $paragraphStyle = null): void
466    {
467        if (in_array($domNode->nodeName, ['w:ins', 'w:del', 'w:smartTag', 'w:hyperlink', 'w:commentReference'])) {
468            $nodes = $xmlReader->getElements('*', $domNode);
469            foreach ($nodes as $node) {
470                $this->readRun($xmlReader, $node, $parent, $docPart, $paragraphStyle);
471            }
472        } elseif ($domNode->nodeName == 'w:r') {
473            $fontStyle = $this->readFontStyle($xmlReader, $domNode);
474            $nodes = $xmlReader->getElements('*', $domNode);
475            foreach ($nodes as $node) {
476                $this->readRunChild($xmlReader, $node, $parent, $docPart, $paragraphStyle, $fontStyle);
477            }
478        }
479
480        if ($xmlReader->elementExists('.//*["commentReference"=local-name()]', $domNode)) {
481            $node = iterator_to_array($xmlReader->getElements('.//*["commentReference"=local-name()]', $domNode))[0];
482            $attributeIdentifier = $node->attributes->getNamedItem('id');
483            if ($attributeIdentifier) {
484                $id = $attributeIdentifier->nodeValue;
485
486                $this->setCommentReference('start', $id, $parent->getElement($parent->countElements() - 1));
487                $this->setCommentReference('end', $id, $parent->getElement($parent->countElements() - 1));
488            }
489        }
490    }
491
492    /**
493     * Parses nodes under w:r.
494     *
495     * @param string $docPart
496     * @param mixed $paragraphStyle
497     * @param mixed $fontStyle
498     */
499    protected function readRunChild(XMLReader $xmlReader, DOMElement $node, AbstractContainer $parent, $docPart, $paragraphStyle = null, $fontStyle = null): void
500    {
501        $runParent = $node->parentNode->parentNode;
502        if ($node->nodeName == 'w:footnoteReference') {
503            // Footnote
504            $wId = $xmlReader->getAttribute('w:id', $node);
505            $footnote = $parent->addFootnote();
506            $footnote->setRelationId($wId);
507        } elseif ($node->nodeName == 'w:endnoteReference') {
508            // Endnote
509            $wId = $xmlReader->getAttribute('w:id', $node);
510            $endnote = $parent->addEndnote();
511            $endnote->setRelationId($wId);
512        } elseif ($node->nodeName == 'w:pict') {
513            // Image
514            $xmlReader->registerNamespace('w10', 'urn:schemas-microsoft-com:office:word');
515            $shape = $xmlReader->getElement('v:shape', $node);
516            $rId = $xmlReader->getAttribute('r:id', $shape, 'v:imagedata');
517            $target = $this->getMediaTarget($docPart, $rId);
518            if ($this->hasImageLoading() && null !== $shape && null !== $target) {
519                if ('External' == $this->getTargetMode($docPart, $rId)) {
520                    $imageSource = $target;
521                } else {
522                    $imageSource = "zip://{$this->docFile}#{$target}";
523                }
524                $parent->addImage($imageSource, ImageStyle::readVml($xmlReader, $shape), false, null, $xmlReader->getAttribute('alt', $shape));
525            }
526        } elseif ($node->nodeName == 'w:drawing') {
527            // Office 2011 Image
528            $xmlReader->registerNamespace('wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing');
529            $xmlReader->registerNamespace('r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
530            $xmlReader->registerNamespace('pic', 'http://schemas.openxmlformats.org/drawingml/2006/picture');
531            $xmlReader->registerNamespace('a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
532
533            // An inline image, or a floating one
534            $frame = $xmlReader->getElement('wp:inline', $node) ?? $xmlReader->getElement('wp:anchor', $node);
535            $picture = 'a:graphic/a:graphicData/pic:pic';
536            // The alternative text is wp:docPr/@descr; pic:cNvPr may repeat it
537            $name = $xmlReader->getAttribute('name', $frame, $picture . '/pic:nvPicPr/pic:cNvPr');
538            $altText = $xmlReader->getAttribute('descr', $frame, 'wp:docPr') ?? $xmlReader->getAttribute('descr', $frame, $picture . '/pic:nvPicPr/pic:cNvPr');
539            $embedId = $xmlReader->getAttribute('r:embed', $frame, $picture . '/pic:blipFill/a:blip');
540            $target = $this->getMediaTarget($docPart, $embedId);
541            if ($this->hasImageLoading() && null !== $frame && null !== $target) {
542                $imageSource = "zip://{$this->docFile}#{$target}";
543                $parent->addImage($imageSource, ImageStyle::readDrawing($xmlReader, $frame), false, $name, $altText);
544            }
545        } elseif ($node->nodeName == 'w:object') {
546            // Object
547            $rId = $xmlReader->getAttribute('r:id', $node, 'o:OLEObject');
548            // $rIdIcon = $xmlReader->getAttribute('r:id', $domNode, 'w:object/v:shape/v:imagedata');
549            $target = $this->getMediaTarget($docPart, $rId);
550            if (null !== $target) {
551                $textContent = "&lt;Object: {$target}>";
552                $parent->addText($textContent, $fontStyle, $paragraphStyle);
553            }
554        } elseif ($node->nodeName == 'w:br') {
555            $parent->addTextBreak();
556        } elseif ($node->nodeName == 'w:tab') {
557            $parent->addText("\t");
558        } elseif ($node->nodeName == 'mc:AlternateContent') {
559            if ($node->hasChildNodes()) {
560                // Get fallback instead of mc:Choice to make sure it is compatible
561                $fallbackElements = $node->getElementsByTagName('Fallback');
562
563                if ($fallbackElements->length) {
564                    $fallback = $fallbackElements->item(0);
565                    // TextRun
566                    $textContent = htmlspecialchars($fallback->nodeValue ?? '', ENT_QUOTES, 'UTF-8');
567
568                    $parent->addText($textContent, $fontStyle, $paragraphStyle);
569                }
570            }
571        } elseif ($node->nodeName == 'w:t' || $node->nodeName == 'w:delText') {
572            // TextRun
573            $textContent = htmlspecialchars($xmlReader->getValue('.', $node) ?? '', ENT_QUOTES, 'UTF-8');
574
575            if ($runParent->nodeName == 'w:hyperlink') {
576                $rId = $xmlReader->getAttribute('r:id', $runParent);
577                $target = $this->getMediaTarget($docPart, $rId);
578                if (null !== $target) {
579                    $parent->addLink($target, $textContent, $fontStyle, $paragraphStyle);
580                } else {
581                    $parent->addText($textContent, $fontStyle, $paragraphStyle);
582                }
583            } else {
584                /** @var AbstractElement $element */
585                $element = $parent->addText($textContent, $fontStyle, $paragraphStyle);
586                if (in_array($runParent->nodeName, ['w:ins', 'w:del'])) {
587                    $type = ($runParent->nodeName == 'w:del') ? TrackChange::DELETED : TrackChange::INSERTED;
588                    $author = $runParent->getAttribute('w:author');
589                    $date = DateTime::createFromFormat('Y-m-d\TH:i:s\Z', $runParent->getAttribute('w:date'));
590                    $date = $date instanceof DateTime ? $date : null;
591                    $element->setChangeInfo($type, $author, $date);
592                }
593            }
594        } elseif ($node->nodeName == 'w:softHyphen') {
595            $element = $parent->addText("\u{200c}", $fontStyle, $paragraphStyle);
596        } elseif ($node->nodeName == 'w:ruby') {
597            $rubyPropertiesNode = $xmlReader->getElement('w:rubyPr', $node);
598            $properties = $this->readRubyProperties($xmlReader, $rubyPropertiesNode);
599            // read base text node
600            $baseText = new TextRun($paragraphStyle);
601            $baseTextNode = $xmlReader->getElement('w:rubyBase/w:r', $node);
602            $this->readRun($xmlReader, $baseTextNode, $baseText, $docPart, $paragraphStyle);
603            // read the actual ruby text (e.g. furigana in Japanese)
604            $rubyText = new TextRun($paragraphStyle);
605            $rubyTextNode = $xmlReader->getElement('w:rt/w:r', $node);
606            $this->readRun($xmlReader, $rubyTextNode, $rubyText, $docPart, $paragraphStyle);
607            // add element to parent
608            $parent->addRuby($baseText, $rubyText, $properties);
609        }
610    }
611
612    /**
613     * Read w:rubyPr element.
614     *
615     * @param XMLReader $xmlReader reader for XML
616     * @param DOMElement $domNode w:RubyPr element
617     *
618     * @return RubyProperties ruby properties from element
619     */
620    protected function readRubyProperties(XMLReader $xmlReader, DOMElement $domNode): RubyProperties
621    {
622        $rubyAlignment = $xmlReader->getElement('w:rubyAlign', $domNode)->getAttribute('w:val');
623        $rubyHps = $xmlReader->getElement('w:hps', $domNode)->getAttribute('w:val'); // font face
624        $rubyHpsRaise = $xmlReader->getElement('w:hpsRaise', $domNode)->getAttribute('w:val'); // pts above base text
625        $rubyHpsBaseText = $xmlReader->getElement('w:hpsBaseText', $domNode)->getAttribute('w:val'); // base text size
626        $rubyLid = $xmlReader->getElement('w:lid', $domNode)->getAttribute('w:val'); // type of ruby
627        $properties = new RubyProperties();
628        $properties->setAlignment($rubyAlignment);
629        $properties->setFontFaceSize((float) $rubyHps);
630        $properties->setFontPointsAboveBaseText((float) $rubyHpsRaise);
631        $properties->setFontSizeForBaseText((float) $rubyHpsBaseText);
632        $properties->setLanguageId($rubyLid);
633
634        return $properties;
635    }
636
637    /**
638     * Read w:tbl.
639     *
640     * @param mixed $parent
641     * @param string $docPart
642     */
643    protected function readTable(XMLReader $xmlReader, DOMElement $domNode, $parent, $docPart = 'document'): void
644    {
645        // Table style
646        $tblStyle = null;
647        if ($xmlReader->elementExists('w:tblPr', $domNode)) {
648            $tblStyle = $this->readTableStyle($xmlReader, $domNode);
649        }
650
651        /** @var \PhpOffice\PhpWord\Element\Table $table Type hint */
652        $table = $parent->addTable($tblStyle);
653        $tblNodes = $xmlReader->getElements('*', $domNode);
654        foreach ($tblNodes as $tblNode) {
655            if ('w:tblGrid' == $tblNode->nodeName) { // Column
656                // @todo Do something with table columns
657            } elseif ('w:tr' == $tblNode->nodeName) { // Row
658                $rowHeight = $xmlReader->getAttribute('w:val', $tblNode, 'w:trPr/w:trHeight');
659                $rowHRule = $xmlReader->getAttribute('w:hRule', $tblNode, 'w:trPr/w:trHeight');
660                $rowHRule = $rowHRule == 'exact';
661                $rowStyle = [
662                    'tblHeader' => $xmlReader->elementExists('w:trPr/w:tblHeader', $tblNode),
663                    'cantSplit' => $xmlReader->elementExists('w:trPr/w:cantSplit', $tblNode),
664                    'exactHeight' => $rowHRule,
665                ];
666
667                $row = $table->addRow($rowHeight, $rowStyle);
668                $rowNodes = $xmlReader->getElements('*', $tblNode);
669                foreach ($rowNodes as $rowNode) {
670                    if ('w:trPr' == $rowNode->nodeName) { // Row style
671                        // @todo Do something with row style
672                    } elseif ('w:tc' == $rowNode->nodeName) { // Cell
673                        $cellWidth = $xmlReader->getAttribute('w:w', $rowNode, 'w:tcPr/w:tcW');
674                        $cellStyle = null;
675                        if ($xmlReader->elementExists('w:tcPr', $rowNode)) {
676                            $cellStyle = $this->readCellStyle($xmlReader, $rowNode);
677                        }
678
679                        $cell = $row->addCell($cellWidth, $cellStyle);
680                        $cellNodes = $xmlReader->getElements('*', $rowNode);
681                        foreach ($cellNodes as $cellNode) {
682                            if ('w:p' == $cellNode->nodeName) { // Paragraph
683                                $this->readParagraph($xmlReader, $cellNode, $cell, $docPart);
684                            } elseif ($cellNode->nodeName == 'w:tbl') { // Table
685                                $this->readTable($xmlReader, $cellNode, $cell, $docPart);
686                            }
687                        }
688                    }
689                }
690            }
691        }
692    }
693
694    /**
695     * Read w:pPr.
696     *
697     * @return null|array
698     */
699    protected function readParagraphStyle(XMLReader $xmlReader, DOMElement $domNode)
700    {
701        if (!$xmlReader->elementExists('w:pPr', $domNode)) {
702            return null;
703        }
704
705        $styleNode = $xmlReader->getElement('w:pPr', $domNode);
706        $styleDefs = [
707            'styleName' => [self::READ_VALUE, ['w:pStyle', 'w:name']],
708            'alignment' => [self::READ_VALUE, 'w:jc'],
709            'basedOn' => [self::READ_VALUE, 'w:basedOn'],
710            'next' => [self::READ_VALUE, 'w:next'],
711            'indentLeft' => [self::READ_VALUE, 'w:ind', 'w:left'],
712            'indentRight' => [self::READ_VALUE, 'w:ind', 'w:right'],
713            'indentHanging' => [self::READ_VALUE, 'w:ind', 'w:hanging'],
714            'indentFirstLine' => [self::READ_VALUE, 'w:ind', 'w:firstLine'],
715            'indentFirstLineChars' => [self::READ_VALUE, 'w:ind', 'w:firstLineChars'],
716            'spaceAfter' => [self::READ_VALUE, 'w:spacing', 'w:after'],
717            'spaceBefore' => [self::READ_VALUE, 'w:spacing', 'w:before'],
718            'widowControl' => [self::READ_FALSE, 'w:widowControl'],
719            'keepNext' => [self::READ_TRUE,  'w:keepNext'],
720            'keepLines' => [self::READ_TRUE,  'w:keepLines'],
721            'pageBreakBefore' => [self::READ_TRUE,  'w:pageBreakBefore'],
722            'contextualSpacing' => [self::READ_TRUE,  'w:contextualSpacing'],
723            'bidi' => [self::READ_TRUE,  'w:bidi'],
724            'suppressAutoHyphens' => [self::READ_TRUE,  'w:suppressAutoHyphens'],
725            'borderTopStyle' => [self::READ_VALUE, 'w:pBdr/w:top'],
726            'borderTopColor' => [self::READ_VALUE, 'w:pBdr/w:top', 'w:color'],
727            'borderTopSize' => [self::READ_VALUE, 'w:pBdr/w:top', 'w:sz'],
728            'borderRightStyle' => [self::READ_VALUE, 'w:pBdr/w:right'],
729            'borderRightColor' => [self::READ_VALUE, 'w:pBdr/w:right', 'w:color'],
730            'borderRightSize' => [self::READ_VALUE, 'w:pBdr/w:right', 'w:sz'],
731            'borderBottomStyle' => [self::READ_VALUE, 'w:pBdr/w:bottom'],
732            'borderBottomColor' => [self::READ_VALUE, 'w:pBdr/w:bottom', 'w:color'],
733            'borderBottomSize' => [self::READ_VALUE, 'w:pBdr/w:bottom', 'w:sz'],
734            'borderLeftStyle' => [self::READ_VALUE, 'w:pBdr/w:left'],
735            'borderLeftColor' => [self::READ_VALUE, 'w:pBdr/w:left', 'w:color'],
736            'borderLeftSize' => [self::READ_VALUE, 'w:pBdr/w:left', 'w:sz'],
737        ];
738
739        return $this->readStyleDefs($xmlReader, $styleNode, $styleDefs);
740    }
741
742    /**
743     * Read w:rPr.
744     *
745     * @return null|array
746     */
747    protected function readFontStyle(XMLReader $xmlReader, DOMElement $domNode)
748    {
749        if (null === $domNode) {
750            return null;
751        }
752        // Hyperlink has an extra w:r child
753        if ('w:hyperlink' == $domNode->nodeName) {
754            $domNode = $xmlReader->getElement('w:r', $domNode);
755        }
756        if (!$xmlReader->elementExists('w:rPr', $domNode)) {
757            return null;
758        }
759
760        $styleNode = $xmlReader->getElement('w:rPr', $domNode);
761        $styleDefs = [
762            'styleName' => [self::READ_VALUE, 'w:rStyle'],
763            'name' => [self::READ_VALUE, 'w:rFonts', ['w:ascii', 'w:hAnsi', 'w:eastAsia', 'w:cs']],
764            'hint' => [self::READ_VALUE, 'w:rFonts', 'w:hint'],
765            'size' => [self::READ_SIZE,  ['w:sz', 'w:szCs']],
766            'color' => [self::READ_VALUE, 'w:color'],
767            'underline' => [self::READ_VALUE, 'w:u'],
768            'bold' => [self::READ_TRUE,  'w:b'],
769            'italic' => [self::READ_TRUE,  'w:i'],
770            'strikethrough' => [self::READ_TRUE,  'w:strike'],
771            'doubleStrikethrough' => [self::READ_TRUE,  'w:dstrike'],
772            'smallCaps' => [self::READ_TRUE,  'w:smallCaps'],
773            'allCaps' => [self::READ_TRUE,  'w:caps'],
774            'superScript' => [self::READ_EQUAL, 'w:vertAlign', 'w:val', 'superscript'],
775            'subScript' => [self::READ_EQUAL, 'w:vertAlign', 'w:val', 'subscript'],
776            'fgColor' => [self::READ_VALUE, 'w:highlight'],
777            'rtl' => [self::READ_TRUE,  'w:rtl'],
778            'lang' => [self::READ_VALUE, 'w:lang'],
779            'position' => [self::READ_VALUE, 'w:position'],
780            'hidden' => [self::READ_TRUE,  'w:vanish'],
781        ];
782
783        return $this->readStyleDefs($xmlReader, $styleNode, $styleDefs);
784    }
785
786    /**
787     * Read w:tblPr.
788     *
789     * @return null|array|string
790     *
791     * @todo Capture w:tblStylePr w:type="firstRow"
792     */
793    protected function readTableStyle(XMLReader $xmlReader, DOMElement $domNode)
794    {
795        $style = null;
796        $margins = ['top', 'left', 'bottom', 'right'];
797        $borders = array_merge($margins, ['insideH', 'insideV']);
798
799        if ($xmlReader->elementExists('w:tblPr', $domNode)) {
800            if ($xmlReader->elementExists('w:tblPr/w:tblStyle', $domNode)) {
801                $style = $xmlReader->getAttribute('w:val', $domNode, 'w:tblPr/w:tblStyle');
802            } else {
803                $styleNode = $xmlReader->getElement('w:tblPr', $domNode);
804                $styleDefs = [];
805                foreach ($margins as $side) {
806                    $ucfSide = ucfirst($side);
807                    $styleDefs["cellMargin$ucfSide"] = [self::READ_VALUE, "w:tblCellMar/w:$side", 'w:w'];
808                }
809                foreach ($borders as $side) {
810                    $ucfSide = ucfirst($side);
811                    $styleDefs["border{$ucfSide}Size"] = [self::READ_VALUE, "w:tblBorders/w:$side", 'w:sz'];
812                    $styleDefs["border{$ucfSide}Color"] = [self::READ_VALUE, "w:tblBorders/w:$side", 'w:color'];
813                    $styleDefs["border{$ucfSide}Style"] = [self::READ_VALUE, "w:tblBorders/w:$side", 'w:val'];
814                }
815                $styleDefs['layout'] = [self::READ_VALUE, 'w:tblLayout', 'w:type'];
816                $styleDefs['bidiVisual'] = [self::READ_TRUE, 'w:bidiVisual'];
817                $styleDefs['cellSpacing'] = [self::READ_VALUE, 'w:tblCellSpacing', 'w:w'];
818                $style = $this->readStyleDefs($xmlReader, $styleNode, $styleDefs);
819
820                $tablePositionNode = $xmlReader->getElement('w:tblpPr', $styleNode);
821                if ($tablePositionNode !== null) {
822                    $style['position'] = $this->readTablePosition($xmlReader, $tablePositionNode);
823                }
824
825                $indentNode = $xmlReader->getElement('w:tblInd', $styleNode);
826                if ($indentNode !== null) {
827                    $style['indent'] = $this->readTableIndent($xmlReader, $indentNode);
828                }
829            }
830        }
831
832        return $style;
833    }
834
835    /**
836     * Read w:tblpPr.
837     *
838     * @return array
839     */
840    private function readTablePosition(XMLReader $xmlReader, DOMElement $domNode)
841    {
842        $styleDefs = [
843            'leftFromText' => [self::READ_VALUE, '.', 'w:leftFromText'],
844            'rightFromText' => [self::READ_VALUE, '.', 'w:rightFromText'],
845            'topFromText' => [self::READ_VALUE, '.', 'w:topFromText'],
846            'bottomFromText' => [self::READ_VALUE, '.', 'w:bottomFromText'],
847            'vertAnchor' => [self::READ_VALUE, '.', 'w:vertAnchor'],
848            'horzAnchor' => [self::READ_VALUE, '.', 'w:horzAnchor'],
849            'tblpXSpec' => [self::READ_VALUE, '.', 'w:tblpXSpec'],
850            'tblpX' => [self::READ_VALUE, '.', 'w:tblpX'],
851            'tblpYSpec' => [self::READ_VALUE, '.', 'w:tblpYSpec'],
852            'tblpY' => [self::READ_VALUE, '.', 'w:tblpY'],
853        ];
854
855        return $this->readStyleDefs($xmlReader, $domNode, $styleDefs);
856    }
857
858    /**
859     * Read w:tblInd.
860     *
861     * @return TblWidthComplexType
862     */
863    private function readTableIndent(XMLReader $xmlReader, DOMElement $domNode)
864    {
865        $styleDefs = [
866            'value' => [self::READ_VALUE, '.', 'w:w'],
867            'type' => [self::READ_VALUE, '.', 'w:type'],
868        ];
869        $styleDefs = $this->readStyleDefs($xmlReader, $domNode, $styleDefs);
870
871        return new TblWidthComplexType((int) $styleDefs['value'], $styleDefs['type']);
872    }
873
874    /**
875     * Read w:tcPr.
876     *
877     * @return null|array
878     */
879    private function readCellStyle(XMLReader $xmlReader, DOMElement $domNode)
880    {
881        $styleDefs = [
882            'valign' => [self::READ_VALUE, 'w:vAlign'],
883            'textDirection' => [self::READ_VALUE, 'w:textDirection'],
884            'gridSpan' => [self::READ_VALUE, 'w:gridSpan'],
885            'vMerge' => [self::READ_VALUE, 'w:vMerge', null, null, 'continue'],
886            'bgColor' => [self::READ_VALUE, 'w:shd', 'w:fill'],
887            'noWrap' => [self::READ_VALUE, 'w:noWrap', null, null, true],
888        ];
889        $style = null;
890
891        if ($xmlReader->elementExists('w:tcPr', $domNode)) {
892            $styleNode = $xmlReader->getElement('w:tcPr', $domNode);
893
894            $borders = ['top', 'left', 'bottom', 'right'];
895            foreach ($borders as $side) {
896                $ucfSide = ucfirst($side);
897
898                $styleDefs['border' . $ucfSide . 'Size'] = [self::READ_VALUE, 'w:tcBorders/w:' . $side, 'w:sz'];
899                $styleDefs['border' . $ucfSide . 'Color'] = [self::READ_VALUE, 'w:tcBorders/w:' . $side, 'w:color'];
900                $styleDefs['border' . $ucfSide . 'Style'] = [self::READ_VALUE, 'w:tcBorders/w:' . $side, 'w:val'];
901            }
902
903            $style = $this->readStyleDefs($xmlReader, $styleNode, $styleDefs);
904        }
905
906        return $style;
907    }
908
909    /**
910     * Returns the first child element found.
911     *
912     * @param null|array|string $elements
913     *
914     * @return null|string
915     */
916    private function findPossibleElement(XMLReader $xmlReader, ?DOMElement $parentNode = null, $elements = null)
917    {
918        if (is_array($elements)) {
919            //if element is an array, we take the first element that exists in the XML
920            foreach ($elements as $possibleElement) {
921                if ($xmlReader->elementExists($possibleElement, $parentNode)) {
922                    return $possibleElement;
923                }
924            }
925        } else {
926            return $elements;
927        }
928
929        return null;
930    }
931
932    /**
933     * Returns the first attribute found.
934     *
935     * @param array|string $attributes
936     *
937     * @return null|string
938     */
939    private function findPossibleAttribute(XMLReader $xmlReader, DOMElement $node, $attributes)
940    {
941        //if attribute is an array, we take the first attribute that exists in the XML
942        if (is_array($attributes)) {
943            foreach ($attributes as $possibleAttribute) {
944                if ($xmlReader->getAttribute($possibleAttribute, $node)) {
945                    return $possibleAttribute;
946                }
947            }
948
949            return null;
950        }
951
952        return $attributes;
953    }
954
955    /**
956     * Read style definition.
957     *
958     * @param array $styleDefs
959     *
960     * @ignoreScrutinizerPatch
961     *
962     * @return array
963     */
964    protected function readStyleDefs(XMLReader $xmlReader, ?DOMElement $parentNode = null, $styleDefs = [])
965    {
966        $styles = [];
967
968        foreach ($styleDefs as $styleProp => $styleVal) {
969            [$method, $element, $attribute, $expected, $default] = array_pad($styleVal, 5, null);
970
971            $element = $this->findPossibleElement($xmlReader, $parentNode, $element);
972            if ($element === null) {
973                continue;
974            }
975
976            if ($xmlReader->elementExists($element, $parentNode)) {
977                $node = $xmlReader->getElement($element, $parentNode);
978
979                $attribute = $this->findPossibleAttribute($xmlReader, $node, $attribute);
980
981                // Use w:val as default if no attribute assigned
982                $attribute = ($attribute === null) ? 'w:val' : $attribute;
983                $attributeValue = $xmlReader->getAttribute($attribute, $node) ?? $default;
984
985                $styleValue = $this->readStyleDef($method, $attributeValue, $expected);
986                if ($styleValue !== null) {
987                    $styles[$styleProp] = $styleValue;
988                }
989            }
990        }
991
992        return $styles;
993    }
994
995    /**
996     * Return style definition based on conversion method.
997     *
998     * @param string $method
999     *
1000     * @ignoreScrutinizerPatch
1001     *
1002     * @param null|string $attributeValue
1003     * @param mixed $expected
1004     *
1005     * @return mixed
1006     */
1007    private function readStyleDef($method, $attributeValue, $expected)
1008    {
1009        $style = $attributeValue;
1010
1011        if (self::READ_SIZE == $method) {
1012            $style = $attributeValue / 2;
1013        } elseif (self::READ_TRUE == $method) {
1014            $style = $this->isOn($attributeValue);
1015        } elseif (self::READ_FALSE == $method) {
1016            $style = !$this->isOn($attributeValue);
1017        } elseif (self::READ_EQUAL == $method) {
1018            $style = $attributeValue == $expected;
1019        }
1020
1021        return $style;
1022    }
1023
1024    /**
1025     * Parses the value of the on/off value, null is considered true as it means the w:val attribute was not present.
1026     *
1027     * @see http://www.datypic.com/sc/ooxml/t-w_ST_OnOff.html
1028     *
1029     * @param string $value
1030     *
1031     * @return bool
1032     */
1033    private function isOn($value = null)
1034    {
1035        return $value === null || $value === '1' || $value === 'true' || $value === 'on';
1036    }
1037
1038    /**
1039     * Returns the target of image, object, or link as stored in ::readMainRels.
1040     *
1041     * @param string $docPart
1042     * @param string $rId
1043     *
1044     * @return null|string
1045     */
1046    private function getMediaTarget($docPart, $rId)
1047    {
1048        $target = null;
1049
1050        if (isset($this->rels[$docPart], $this->rels[$docPart][$rId])) {
1051            $target = $this->rels[$docPart][$rId]['target'];
1052        }
1053
1054        return $target;
1055    }
1056
1057    /**
1058     * Returns the target mode.
1059     *
1060     * @param string $docPart
1061     * @param string $rId
1062     *
1063     * @return null|string
1064     */
1065    private function getTargetMode($docPart, $rId)
1066    {
1067        $mode = null;
1068
1069        if (isset($this->rels[$docPart], $this->rels[$docPart][$rId])) {
1070            $mode = $this->rels[$docPart][$rId]['targetMode'];
1071        }
1072
1073        return $mode;
1074    }
1075}