Failed Conditions
Pull Request — master (#4118)
by Owen
13:53
created

Xls::readPalette()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 0
dl 0
loc 16
ccs 6
cts 6
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
6
use PhpOffice\PhpSpreadsheet\Cell\DataType;
7
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
8
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
9
use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\CellFont;
10
use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\FillPattern;
11
use PhpOffice\PhpSpreadsheet\RichText\RichText;
12
use PhpOffice\PhpSpreadsheet\Shared\CodePage;
13
use PhpOffice\PhpSpreadsheet\Shared\Date;
14
use PhpOffice\PhpSpreadsheet\Shared\Escher;
15
use PhpOffice\PhpSpreadsheet\Shared\File;
16
use PhpOffice\PhpSpreadsheet\Shared\OLE;
17
use PhpOffice\PhpSpreadsheet\Shared\OLERead;
18
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
19
use PhpOffice\PhpSpreadsheet\Spreadsheet;
20
use PhpOffice\PhpSpreadsheet\Style\Alignment;
21
use PhpOffice\PhpSpreadsheet\Style\Border;
22
use PhpOffice\PhpSpreadsheet\Style\Borders;
23
use PhpOffice\PhpSpreadsheet\Style\Conditional;
24
use PhpOffice\PhpSpreadsheet\Style\Fill;
25
use PhpOffice\PhpSpreadsheet\Style\Font;
26
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
27
use PhpOffice\PhpSpreadsheet\Style\Protection;
28
use PhpOffice\PhpSpreadsheet\Style\Style;
29
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
30
use PhpOffice\PhpSpreadsheet\Worksheet\SheetView;
31
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
32
33
// Original file header of ParseXL (used as the base for this class):
34
// --------------------------------------------------------------------------------
35
// Adapted from Excel_Spreadsheet_Reader developed by users bizon153,
36
// trex005, and mmp11 (SourceForge.net)
37
// https://sourceforge.net/projects/phpexcelreader/
38
// Primary changes made by canyoncasa (dvc) for ParseXL 1.00 ...
39
//     Modelled moreso after Perl Excel Parse/Write modules
40
//     Added Parse_Excel_Spreadsheet object
41
//         Reads a whole worksheet or tab as row,column array or as
42
//         associated hash of indexed rows and named column fields
43
//     Added variables for worksheet (tab) indexes and names
44
//     Added an object call for loading individual woorksheets
45
//     Changed default indexing defaults to 0 based arrays
46
//     Fixed date/time and percent formats
47
//     Includes patches found at SourceForge...
48
//         unicode patch by nobody
49
//         unpack("d") machine depedency patch by matchy
50
//         boundsheet utf16 patch by bjaenichen
51
//     Renamed functions for shorter names
52
//     General code cleanup and rigor, including <80 column width
53
//     Included a testcase Excel file and PHP example calls
54
//     Code works for PHP 5.x
55
56
// Primary changes made by canyoncasa (dvc) for ParseXL 1.10 ...
57
// http://sourceforge.net/tracker/index.php?func=detail&aid=1466964&group_id=99160&atid=623334
58
//     Decoding of formula conditions, results, and tokens.
59
//     Support for user-defined named cells added as an array "namedcells"
60
//         Patch code for user-defined named cells supports single cells only.
61
//         NOTE: this patch only works for BIFF8 as BIFF5-7 use a different
62
//         external sheet reference structure
63
class Xls extends XlsBase
64
{
65
    /**
66
     * Summary Information stream data.
67
     */
68
    protected ?string $summaryInformation = null;
69
70
    /**
71
     * Extended Summary Information stream data.
72
     */
73
    protected ?string $documentSummaryInformation = null;
74
75
    /**
76
     * Workbook stream data. (Includes workbook globals substream as well as sheet substreams).
77
     */
78
    protected string $data;
79
80
    /**
81
     * Size in bytes of $this->data.
82
     */
83
    protected int $dataSize;
84
85
    /**
86
     * Current position in stream.
87
     */
88
    protected int $pos;
89
90
    /**
91
     * Workbook to be returned by the reader.
92
     */
93
    protected Spreadsheet $spreadsheet;
94
95
    /**
96
     * Worksheet that is currently being built by the reader.
97
     */
98
    protected Worksheet $phpSheet;
99
100
    /**
101
     * BIFF version.
102
     */
103
    protected int $version = 0;
104
105
    /**
106
     * Shared formats.
107
     */
108
    protected array $formats;
109
110
    /**
111
     * Shared fonts.
112
     *
113
     * @var Font[]
114
     */
115
    protected array $objFonts;
116
117
    /**
118
     * Color palette.
119
     */
120
    protected array $palette;
121
122
    /**
123
     * Worksheets.
124
     */
125
    protected array $sheets;
126
127
    /**
128
     * External books.
129
     */
130
    protected array $externalBooks;
131
132
    /**
133
     * REF structures. Only applies to BIFF8.
134
     */
135
    protected array $ref;
136
137
    /**
138
     * External names.
139
     */
140
    protected array $externalNames;
141
142
    /**
143
     * Defined names.
144
     */
145
    protected array $definedname;
146
147
    /**
148
     * Shared strings. Only applies to BIFF8.
149
     */
150
    protected array $sst;
151
152
    /**
153
     * Panes are frozen? (in sheet currently being read). See WINDOW2 record.
154
     */
155
    protected bool $frozen;
156
157
    /**
158
     * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record.
159
     */
160
    protected bool $isFitToPages;
161
162
    /**
163
     * Objects. One OBJ record contributes with one entry.
164
     */
165
    protected array $objs;
166
167
    /**
168
     * Text Objects. One TXO record corresponds with one entry.
169
     */
170
    protected array $textObjects;
171
172
    /**
173
     * Cell Annotations (BIFF8).
174
     */
175
    protected array $cellNotes;
176
177
    /**
178
     * The combined MSODRAWINGGROUP data.
179
     */
180
    protected string $drawingGroupData;
181
182
    /**
183
     * The combined MSODRAWING data (per sheet).
184
     */
185
    protected string $drawingData;
186
187
    /**
188
     * Keep track of XF index.
189
     */
190
    protected int $xfIndex;
191
192
    /**
193
     * Mapping of XF index (that is a cell XF) to final index in cellXf collection.
194
     */
195
    protected array $mapCellXfIndex;
196
197
    /**
198
     * Mapping of XF index (that is a style XF) to final index in cellStyleXf collection.
199
     */
200
    protected array $mapCellStyleXfIndex;
201
202
    /**
203
     * The shared formulas in a sheet. One SHAREDFMLA record contributes with one value.
204
     */
205
    protected array $sharedFormulas;
206
207
    /**
208
     * The shared formula parts in a sheet. One FORMULA record contributes with one value if it
209
     * refers to a shared formula.
210
     */
211
    protected array $sharedFormulaParts;
212
213
    /**
214
     * The type of encryption in use.
215
     */
216
    protected int $encryption = 0;
217
218
    /**
219
     * The position in the stream after which contents are encrypted.
220
     */
221
    protected int $encryptionStartPos = 0;
222
223
    /**
224
     * The current RC4 decryption object.
225
     */
226
    protected ?Xls\RC4 $rc4Key = null;
227
228
    /**
229
     * The position in the stream that the RC4 decryption object was left at.
230
     */
231
    protected int $rc4Pos = 0;
232
233
    /**
234
     * The current MD5 context state.
235
     * It is never set in the program, so code which uses it is suspect.
236
     */
237
    private string $md5Ctxt; // @phpstan-ignore-line
238
239
    protected int $textObjRef;
240
241
    protected string $baseCell;
242
243
    protected bool $activeSheetSet = false;
244
245
    /**
246
     * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object.
247
     */
248
    public function listWorksheetNames(string $filename): array
249
    {
250
        return (new Xls\ListFunctions())->listWorksheetNames2($filename, $this);
251
    }
252
253
    /**
254
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
255
     */
256
    public function listWorksheetInfo(string $filename): array
257
    {
258
        return (new Xls\ListFunctions())->listWorksheetInfo2($filename, $this);
259
    }
260
261
    /**
262
     * Loads PhpSpreadsheet from file.
263
     */
264
    protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
265
    {
266
        return (new Xls\LoadSpreadsheet())->loadSpreadsheetFromFile2($filename, $this);
267
    }
268
269
    /**
270
     * Read record data from stream, decrypting as required.
271
     *
272
     * @param string $data Data stream to read from
273
     * @param int $pos Position to start reading from
274
     * @param int $len Record data length
275
     *
276
     * @return string Record data
277
     */
278
    protected function readRecordData(string $data, int $pos, int $len): string
279
    {
280
        $data = substr($data, $pos, $len);
281
282
        // File not encrypted, or record before encryption start point
283
        if ($this->encryption == self::MS_BIFF_CRYPTO_NONE || $pos < $this->encryptionStartPos) {
284
            return $data;
285
        }
286
287
        $recordData = '';
288
        if ($this->encryption == self::MS_BIFF_CRYPTO_RC4) {
289
            $oldBlock = floor($this->rc4Pos / self::REKEY_BLOCK);
290
            $block = (int) floor($pos / self::REKEY_BLOCK);
291
            $endBlock = (int) floor(($pos + $len) / self::REKEY_BLOCK);
292
293
            // Spin an RC4 decryptor to the right spot. If we have a decryptor sitting
294
            // at a point earlier in the current block, re-use it as we can save some time.
295
            if ($block != $oldBlock || $pos < $this->rc4Pos || !$this->rc4Key) {
296
                $this->rc4Key = $this->makeKey($block, $this->md5Ctxt);
297
                $step = $pos % self::REKEY_BLOCK;
298
            } else {
299
                $step = $pos - $this->rc4Pos;
300
            }
301
            $this->rc4Key->RC4(str_repeat("\0", $step));
302
303
            // Decrypt record data (re-keying at the end of every block)
304
            while ($block != $endBlock) {
305
                $step = self::REKEY_BLOCK - ($pos % self::REKEY_BLOCK);
306
                $recordData .= $this->rc4Key->RC4(substr($data, 0, $step));
307
                $data = substr($data, $step);
308
                $pos += $step;
309
                $len -= $step;
310
                ++$block;
311
                $this->rc4Key = $this->makeKey($block, $this->md5Ctxt);
312
            }
313
            $recordData .= $this->rc4Key->RC4(substr($data, 0, $len));
314
315
            // Keep track of the position of this decryptor.
316
            // We'll try and re-use it later if we can to speed things up
317
            $this->rc4Pos = $pos + $len;
318
        } elseif ($this->encryption == self::MS_BIFF_CRYPTO_XOR) {
319
            throw new Exception('XOr encryption not supported');
320
        }
321
322
        return $recordData;
323
    }
324
325
    /**
326
     * Use OLE reader to extract the relevant data streams from the OLE file.
327
     */
328
    protected function loadOLE(string $filename): void
329
    {
330
        // OLE reader
331
        $ole = new OLERead();
332
        // get excel data,
333
        $ole->read($filename);
334
        // Get workbook data: workbook stream + sheet streams
335
        $this->data = $ole->getStream($ole->wrkbook); // @phpstan-ignore-line
336
        // Get summary information data
337
        $this->summaryInformation = $ole->getStream($ole->summaryInformation);
338
        // Get additional document summary information data
339
        $this->documentSummaryInformation = $ole->getStream($ole->documentSummaryInformation);
340
    }
341
342
    /**
343
     * Read summary information.
344
     */
345
    protected function readSummaryInformation(): void
346
    {
347
        if (!isset($this->summaryInformation)) {
348
            return;
349
        }
350
351
        // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
352
        // offset: 2; size: 2;
353
        // offset: 4; size: 2; OS version
354
        // offset: 6; size: 2; OS indicator
355
        // offset: 8; size: 16
356
        // offset: 24; size: 4; section count
357
        //$secCount = self::getInt4d($this->summaryInformation, 24);
358
359
        // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
360
        // offset: 44; size: 4
361
        $secOffset = self::getInt4d($this->summaryInformation, 44);
362
363
        // section header
364
        // offset: $secOffset; size: 4; section length
365
        //$secLength = self::getInt4d($this->summaryInformation, $secOffset);
366
367
        // offset: $secOffset+4; size: 4; property count
368
        $countProperties = self::getInt4d($this->summaryInformation, $secOffset + 4);
369
370
        // initialize code page (used to resolve string values)
371
        $codePage = 'CP1252';
372
373
        // offset: ($secOffset+8); size: var
374
        // loop through property decarations and properties
375
        for ($i = 0; $i < $countProperties; ++$i) {
376 142
            // offset: ($secOffset+8) + (8 * $i); size: 4; property ID
377
            $id = self::getInt4d($this->summaryInformation, ($secOffset + 8) + (8 * $i));
378 142
379
            // Use value of property id as appropriate
380
            // offset: ($secOffset+12) + (8 * $i); size: 4; offset from beginning of section (48)
381
            $offset = self::getInt4d($this->summaryInformation, ($secOffset + 12) + (8 * $i));
382
383
            $type = self::getInt4d($this->summaryInformation, $secOffset + $offset);
384 24
385
            // initialize property value
386 24
            $value = null;
387 1
388
            // extract property value based on property type
389
            switch ($type) {
390
                case 0x02: // 2 byte signed integer
391
                    $value = self::getUInt2d($this->summaryInformation, $secOffset + 4 + $offset);
392 23
393
                    break;
394
                case 0x03: // 4 byte signed integer
395 23
                    $value = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset);
396 13
397 3
                    break;
398
                case 0x13: // 4 byte unsigned integer
399
                    // not needed yet, fix later if necessary
400 10
                    break;
401 13
                case 0x1E: // null-terminated string prepended by dword string length
402 13
                    $byteLength = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset);
403
                    $value = substr($this->summaryInformation, $secOffset + 8 + $offset, $byteLength);
404
                    $value = StringHelper::convertEncoding($value, 'UTF-8', $codePage);
405
                    $value = rtrim($value);
406
407
                    break;
408
                case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
409
                    // PHP-time
410
                    $value = OLE::OLE2LocalDate(substr($this->summaryInformation, $secOffset + 4 + $offset, 8));
411
412
                    break;
413
                case 0x47: // Clipboard format
414
                    // not needed yet, fix later if necessary
415 5
                    break;
416
            }
417 5
418
            switch ($id) {
419
                case 0x01:    //    Code Page
420
                    $codePage = CodePage::numberToName((int) $value);
421
422
                    break;
423 6
                case 0x02:    //    Title
424
                    $this->spreadsheet->getProperties()->setTitle("$value");
425 6
426
                    break;
427 6
                case 0x03:    //    Subject
428
                    $this->spreadsheet->getProperties()->setSubject("$value");
429
430 6
                    break;
431
                case 0x04:    //    Author (Creator)
432
                    $this->spreadsheet->getProperties()->setCreator("$value");
433 6
434
                    break;
435 6
                case 0x05:    //    Keywords
436 6
                    $this->spreadsheet->getProperties()->setKeywords("$value");
437
438
                    break;
439 6
                case 0x06:    //    Comments (Description)
440 6
                    $this->spreadsheet->getProperties()->setDescription("$value");
441
442 6
                    break;
443 6
                case 0x07:    //    Template
444 6
                    //    Not supported by PhpSpreadsheet
445 6
                    break;
446 6
                case 0x08:    //    Last Saved By (LastModifiedBy)
447 6
                    $this->spreadsheet->getProperties()->setLastModifiedBy("$value");
448 6
449
                    break;
450 6
                case 0x09:    //    Revision
451 6
                    //    Not supported by PhpSpreadsheet
452
                    break;
453
                case 0x0A:    //    Total Editing Time
454
                    //    Not supported by PhpSpreadsheet
455 6
                    break;
456 6
                case 0x0B:    //    Last Printed
457
                    //    Not supported by PhpSpreadsheet
458
                    break;
459
                case 0x0C:    //    Created Date/Time
460
                    $this->spreadsheet->getProperties()->setCreated($value);
461 6
462
                    break;
463
                case 0x0D:    //    Modified Date/Time
464 6
                    $this->spreadsheet->getProperties()->setModified($value);
465
466
                    break;
467
                case 0x0E:    //    Number of Pages
468
                    //    Not supported by PhpSpreadsheet
469
                    break;
470 4
                case 0x0F:    //    Number of Words
471
                    //    Not supported by PhpSpreadsheet
472 4
                    break;
473
                case 0x10:    //    Number of Characters
474 4
                    //    Not supported by PhpSpreadsheet
475
                    break;
476
                case 0x11:    //    Thumbnail
477 4
                    //    Not supported by PhpSpreadsheet
478
                    break;
479
                case 0x12:    //    Name of creating application
480 4
                    //    Not supported by PhpSpreadsheet
481
                    break;
482
                case 0x13:    //    Security
483 4
                    //    Not supported by PhpSpreadsheet
484 4
                    break;
485
            }
486
        }
487 4
    }
488 4
489
    /**
490 4
     * Read additional document summary information.
491 4
     */
492 4
    protected function readDocumentSummaryInformation(): void
493 4
    {
494 4
        if (!isset($this->documentSummaryInformation)) {
495 4
            return;
496 4
        }
497
498 4
        //    offset: 0;    size: 2;    must be 0xFE 0xFF (UTF-16 LE byte order mark)
499 4
        //    offset: 2;    size: 2;
500
        //    offset: 4;    size: 2;    OS version
501
        //    offset: 6;    size: 2;    OS indicator
502
        //    offset: 8;    size: 16
503
        //    offset: 24;    size: 4;    section count
504 4
        //$secCount = self::getInt4d($this->documentSummaryInformation, 24);
505 4
506
        // offset: 28;    size: 16;    first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
507
        // offset: 44;    size: 4;    first section offset
508
        $secOffset = self::getInt4d($this->documentSummaryInformation, 44);
509
510
        //    section header
511
        //    offset: $secOffset;    size: 4;    section length
512 4
        //$secLength = self::getInt4d($this->documentSummaryInformation, $secOffset);
513 4
514 4
        //    offset: $secOffset+4;    size: 4;    property count
515 4
        $countProperties = self::getInt4d($this->documentSummaryInformation, $secOffset + 4);
516 4
517 4
        // initialize code page (used to resolve string values)
518
        $codePage = 'CP1252';
519 4
520
        //    offset: ($secOffset+8);    size: var
521 4
        //    loop through property decarations and properties
522 4
        for ($i = 0; $i < $countProperties; ++$i) {
523
            //    offset: ($secOffset+8) + (8 * $i);    size: 4;    property ID
524
            $id = self::getInt4d($this->documentSummaryInformation, ($secOffset + 8) + (8 * $i));
525
526
            // Use value of property id as appropriate
527
            // offset: 60 + 8 * $i;    size: 4;    offset from beginning of section (48)
528
            $offset = self::getInt4d($this->documentSummaryInformation, ($secOffset + 12) + (8 * $i));
529
530
            $type = self::getInt4d($this->documentSummaryInformation, $secOffset + $offset);
531 4
532 4
            // initialize property value
533
            $value = null;
534
535 4
            // extract property value based on property type
536
            switch ($type) {
537 4
                case 0x02:    //    2 byte signed integer
538 4
                    $value = self::getUInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset);
539
540 4
                    break;
541 4
                case 0x03:    //    4 byte signed integer
542
                    $value = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset);
543 4
544
                    break;
545 4
                case 0x0B:  // Boolean
546
                    $value = self::getUInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset);
547 4
                    $value = ($value == 0 ? false : true);
548
549 4
                    break;
550
                case 0x13:    //    4 byte unsigned integer
551 4
                    // not needed yet, fix later if necessary
552
                    break;
553 4
                case 0x1E:    //    null-terminated string prepended by dword string length
554
                    $byteLength = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset);
555 4
                    $value = substr($this->documentSummaryInformation, $secOffset + 8 + $offset, $byteLength);
556
                    $value = StringHelper::convertEncoding($value, 'UTF-8', $codePage);
557
                    $value = rtrim($value);
558
559 4
                    break;
560 4
                case 0x40:    //    Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
561
                    // PHP-Time
562 4
                    $value = OLE::OLE2LocalDate(substr($this->documentSummaryInformation, $secOffset + 4 + $offset, 8));
563
564
                    break;
565 4
                case 0x47:    //    Clipboard format
566
                    // not needed yet, fix later if necessary
567
                    break;
568
            }
569
570
            switch ($id) {
571 114
                case 0x01:    //    Code Page
572
                    $codePage = CodePage::numberToName((int) $value);
573
574 114
                    break;
575
                case 0x02:    //    Category
576
                    $this->spreadsheet->getProperties()->setCategory("$value");
577 114
578 114
                    break;
579 114
                case 0x03:    //    Presentation Target
580 112
                    //    Not supported by PhpSpreadsheet
581 112
                    break;
582
                case 0x04:    //    Bytes
583
                    //    Not supported by PhpSpreadsheet
584
                    break;
585 114
                case 0x05:    //    Lines
586
                    //    Not supported by PhpSpreadsheet
587
                    break;
588 114
                case 0x06:    //    Paragraphs
589
                    //    Not supported by PhpSpreadsheet
590
                    break;
591 114
                case 0x07:    //    Slides
592
                    //    Not supported by PhpSpreadsheet
593
                    break;
594 114
                case 0x08:    //    Notes
595 114
                    //    Not supported by PhpSpreadsheet
596 114
                    break;
597 114
                case 0x09:    //    Hidden Slides
598 114
                    //    Not supported by PhpSpreadsheet
599 114
                    break;
600 114
                case 0x0A:    //    MM Clips
601 114
                    //    Not supported by PhpSpreadsheet
602 114
                    break;
603 114
                case 0x0B:    //    Scale Crop
604 114
                    //    Not supported by PhpSpreadsheet
605 114
                    break;
606 114
                case 0x0C:    //    Heading Pairs
607 114
                    //    Not supported by PhpSpreadsheet
608
                    break;
609
                case 0x0D:    //    Titles of Parts
610 114
                    //    Not supported by PhpSpreadsheet
611 114
                    break;
612
                case 0x0E:    //    Manager
613 114
                    $this->spreadsheet->getProperties()->setManager("$value");
614 114
615
                    break;
616 111
                case 0x0F:    //    Company
617 113
                    $this->spreadsheet->getProperties()->setCompany("$value");
618 113
619 62
                    break;
620 114
                case 0x10:    //    Links up-to-date
621 49
                    //    Not supported by PhpSpreadsheet
622 114
                    break;
623 74
            }
624 114
        }
625 87
    }
626 1
627 88
    /**
628 16
     * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record.
629 18
     */
630 108
    protected function readDefault(): void
631 114
    {
632 114
        $length = self::getUInt2d($this->data, $this->pos + 2);
633 114
634
        // move stream pointer to next record
635 114
        $this->pos += 4 + $length;
636 114
    }
637
638
    /**
639
     *    The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions,
640
     *        this record stores a note (cell note). This feature was significantly enhanced in Excel 97.
641
     */
642 114
    protected function readNote(): void
643 112
    {
644 111
        $length = self::getUInt2d($this->data, $this->pos + 2);
645 111
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
646 111
647
        // move stream pointer to next record
648
        $this->pos += 4 + $length;
649
650 112
        if ($this->readDataOnly) {
651
            return;
652 112
        }
653
654 112
        $cellAddress = Xls\Biff8::readBIFF8CellAddress(substr($recordData, 0, 4));
655 112
        if ($this->version == self::XLS_BIFF8) {
656 112
            $noteObjID = self::getUInt2d($recordData, 6);
657
            $noteAuthor = self::readUnicodeStringLong(substr($recordData, 8));
658 112
            $noteAuthor = $noteAuthor['value'];
659 112
            $this->cellNotes[$noteObjID] = [
660 112
                'cellRef' => $cellAddress,
661
                'objectID' => $noteObjID,
662
                'author' => $noteAuthor,
663
            ];
664 112
        } else {
665 112
            $extension = false;
666 112
            if ($cellAddress == '$B$65536') {
667 112
                //    If the address row is -1 and the column is 0, (which translates as $B$65536) then this is a continuation
668 112
                //        note from the previous cell annotation. We're not yet handling this, so annotations longer than the
669
                //        max 2048 bytes will probably throw a wobbly.
670 112
                //$row = self::getUInt2d($recordData, 0);
671 112
                $extension = true;
672 112
                $arrayKeys = array_keys($this->phpSheet->getComments());
673
                $cellAddress = array_pop($arrayKeys);
674 112
            }
675 112
676 112
            $cellAddress = str_replace('$', '', (string) $cellAddress);
677
            //$noteLength = self::getUInt2d($recordData, 4);
678 112
            $noteText = trim(substr($recordData, 6));
679 112
680 112
            if ($extension) {
681
                //    Concatenate this extension with the currently set comment for the cell
682 112
                $comment = $this->phpSheet->getComment($cellAddress);
683 112
                $commentText = $comment->getText()->getPlainText();
684 112
                $comment->setText($this->parseRichText($commentText . $noteText));
685
            } else {
686 112
                //    Set comment for the cell
687 110
                $this->phpSheet->getComment($cellAddress)->setText($this->parseRichText($noteText));
688 110
//                                                    ->setAuthor($author)
689
            }
690
        }
691
    }
692
693
    /**
694 114
     * The TEXT Object record contains the text associated with a cell annotation.
695 114
     */
696 18
    protected function readTextObject(): void
697 18
    {
698 18
        $length = self::getUInt2d($this->data, $this->pos + 2);
699
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
700
701
        // move stream pointer to next record
702 114
        $this->pos += 4 + $length;
703 114
704 114
        if ($this->readDataOnly) {
705 114
            return;
706
        }
707
708
        // recordData consists of an array of subrecords looking like this:
709
        //    grbit: 2 bytes; Option Flags
710
        //    rot: 2 bytes; rotation
711 114
        //    cchText: 2 bytes; length of the text (in the first continue record)
712 8
        //    cbRuns: 2 bytes; length of the formatting (in the second continue record)
713
        // followed by the continuation records containing the actual text and formatting
714
        $grbitOpts = self::getUInt2d($recordData, 0);
715
        $rot = self::getUInt2d($recordData, 2);
716 113
        //$cchText = self::getUInt2d($recordData, 10);
717
        $cbRuns = self::getUInt2d($recordData, 12);
718
        $text = $this->getSplicedRecordData();
719
720 113
        $textByte = $text['spliceOffsets'][1] - $text['spliceOffsets'][0] - 1;
721 113
        $textStr = substr($text['recordData'], $text['spliceOffsets'][0] + 1, $textByte);
722
        // get 1 byte
723 113
        $is16Bit = ord($text['recordData'][0]);
724
        // it is possible to use a compressed format,
725
        // which omits the high bytes of all characters, if they are all zero
726 113
        if (($is16Bit & 0x01) === 0) {
727
            $textStr = StringHelper::ConvertEncoding($textStr, 'UTF-8', 'ISO-8859-1');
728
        } else {
729 113
            $textStr = $this->decodeCodepage($textStr);
730
        }
731
732 113
        $this->textObjects[$this->textObjRef] = [
733
            'text' => $textStr,
734
            'format' => substr($text['recordData'], $text['spliceOffsets'][1], $cbRuns),
735 113
            'alignment' => $grbitOpts,
736
            'rotation' => $rot,
737
        ];
738 113
    }
739
740
    /**
741 113
     * Read BOF.
742
     */
743
    protected function readBof(): void
744 113
    {
745 113
        $length = self::getUInt2d($this->data, $this->pos + 2);
746
        $recordData = substr($this->data, $this->pos + 4, $length);
747 113
748 113
        // move stream pointer to next record
749
        $this->pos += 4 + $length;
750
751
        // offset: 2; size: 2; type of the following data
752 113
        $substreamType = self::getUInt2d($recordData, 2);
753
754 113
        switch ($substreamType) {
755
            case self::XLS_WORKBOOKGLOBALS:
756 110
                $version = self::getUInt2d($recordData, 0);
757
                if (($version != self::XLS_BIFF8) && ($version != self::XLS_BIFF7)) {
758 110
                    throw new Exception('Cannot read this Excel file. Version is too old.');
759
                }
760 61
                $this->version = $version;
761
762 61
                break;
763
            case self::XLS_WORKSHEET:
764 112
                // do not use this version information for anything
765
                // it is unreliable (OpenOffice doc, 5.8), use only version information from the global stream
766 112
                break;
767
            default:
768 5
                // substream, e.g. chart
769
                // just skip the entire substream
770 5
                do {
771
                    $code = self::getUInt2d($this->data, $this->pos);
772 5
                    $this->readDefault();
773
                } while ($code != self::XLS_TYPE_EOF && $this->pos < $this->dataSize);
774 5
775
                break;
776 110
        }
777
    }
778 110
779
    /**
780 110
     * FILEPASS.
781
     *
782 110
     * This record is part of the File Protection Block. It
783
     * contains information about the read/write password of the
784 110
     * file. All record contents following this record will be
785
     * encrypted.
786 110
     *
787
     * --    "OpenOffice.org's Documentation of the Microsoft
788 110
     *         Excel File Format"
789
     *
790 110
     * The decryption functions and objects used from here on in
791
     * are based on the source of Spreadsheet-ParseExcel:
792 105
     * https://metacpan.org/release/Spreadsheet-ParseExcel
793
     */
794 105
    protected function readFilepass(): void
795
    {
796 105
        $length = self::getUInt2d($this->data, $this->pos + 2);
797
798 105
        if ($length != 54) {
799
            throw new Exception('Unexpected file pass record length');
800 105
        }
801
802 105
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
803
804 105
        // move stream pointer to next record
805
        $this->pos += 4 + $length;
806 105
807
        if (!$this->verifyPassword('VelvetSweatshop', substr($recordData, 6, 16), substr($recordData, 22, 16), substr($recordData, 38, 16), $this->md5Ctxt)) {
808 112
            throw new Exception('Decryption password incorrect');
809
        }
810 112
811
        $this->encryption = self::MS_BIFF_CRYPTO_RC4;
812 7
813
        // Decryption required from the record after next onwards
814 7
        $this->encryptionStartPos = $this->pos + self::getUInt2d($this->data, $this->pos + 2);
815
    }
816
817
    /**
818
     * Make an RC4 decryptor for the given block.
819
     *
820 2
     * @param int $block Block for which to create decrypto
821
     * @param string $valContext MD5 context state
822 2
     */
823
    private function makeKey(int $block, string $valContext): Xls\RC4
824 3
    {
825
        $pwarray = str_repeat("\0", 64);
826 3
827
        for ($i = 0; $i < 5; ++$i) {
828 111
            $pwarray[$i] = $valContext[$i];
829
        }
830 111
831
        $pwarray[5] = chr($block & 0xFF);
832 101
        $pwarray[6] = chr(($block >> 8) & 0xFF);
833
        $pwarray[7] = chr(($block >> 16) & 0xFF);
834 101
        $pwarray[8] = chr(($block >> 24) & 0xFF);
835
836 113
        $pwarray[9] = "\x80";
837
        $pwarray[56] = "\x48";
838 113
839
        $md5 = new Xls\MD5();
840 69
        $md5->add($pwarray);
841
842 69
        $s = $md5->getContext();
843
844 55
        return new Xls\RC4($s);
845
    }
846 55
847
    /**
848 35
     * Verify RC4 file password.
849
     *
850 35
     * @param string $password Password to check
851
     * @param string $docid Document id
852 62
     * @param string $salt_data Salt data
853
     * @param string $hashedsalt_data Hashed salt data
854 62
     * @param string $valContext Set to the MD5 context of the value
855
     *
856 22
     * @return bool Success
857
     */
858 22
    private function verifyPassword(string $password, string $docid, string $salt_data, string $hashedsalt_data, string &$valContext): bool
859
    {
860 55
        $pwarray = str_repeat("\0", 64);
861
862 55
        $iMax = strlen($password);
863
        for ($i = 0; $i < $iMax; ++$i) {
864 37
            $o = ord(substr($password, $i, 1));
865
            $pwarray[2 * $i] = chr($o & 0xFF);
866 37
            $pwarray[2 * $i + 1] = chr(($o >> 8) & 0xFF);
867
        }
868 1
        $pwarray[2 * $i] = chr(0x80);
869
        $pwarray[56] = chr(($i << 4) & 0xFF);
870 1
871
        $md5 = new Xls\MD5();
872 11
        $md5->add($pwarray);
873
874 11
        $mdContext1 = $md5->getContext();
875
876 26
        $offset = 0;
877
        $keyoffset = 0;
878 26
        $tocopy = 5;
879
880 4
        $md5->reset();
881
882 4
        while ($offset != 16) {
883
            if ((64 - $offset) < 5) {
884 25
                $tocopy = 64 - $offset;
885
            }
886 25
            for ($i = 0; $i <= $tocopy; ++$i) {
887
                $pwarray[$offset + $i] = $mdContext1[$keyoffset + $i];
888 17
            }
889
            $offset += $tocopy;
890 17
891
            if ($offset == 64) {
892 13
                $md5->add($pwarray);
893
                $keyoffset = $tocopy;
894 13
                $tocopy = 5 - $tocopy;
895
                $offset = 0;
896 113
897
                continue;
898 113
            }
899
900 100
            $keyoffset = 0;
901
            $tocopy = 5;
902 100
            for ($i = 0; $i < 16; ++$i) {
903
                $pwarray[$offset + $i] = $docid[$i];
904 6
            }
905
            $offset += 16;
906 6
        }
907
908 8
        $pwarray[16] = "\x80";
909
        for ($i = 0; $i < 47; ++$i) {
910 8
            $pwarray[17 + $i] = "\0";
911
        }
912 110
        $pwarray[56] = "\x80";
913
        $pwarray[57] = "\x0a";
914 110
915
        $md5->add($pwarray);
916 19
        $valContext = $md5->getContext();
917
918 19
        $key = $this->makeKey(0, $valContext);
919
920 6
        $salt = $key->RC4($salt_data);
921
        $hashedsalt = $key->RC4($hashedsalt_data);
922 6
923
        $salt .= "\x80" . str_repeat("\0", 47);
924 3
        $salt[56] = "\x80";
925
926 3
        $md5->reset();
927
        $md5->add($salt);
928 3
        $mdContext2 = $md5->getContext();
929
930 3
        return $mdContext2 == $hashedsalt;
931
    }
932 24
933
    /**
934 24
     * CODEPAGE.
935
     *
936 24
     * This record stores the text encoding used to write byte
937
     * strings, stored as MS Windows code page identifier.
938 24
     *
939
     * --    "OpenOffice.org's Documentation of the Microsoft
940 5
     *         Excel File Format"
941
     */
942 5
    protected function readCodepage(): void
943
    {
944 104
        $length = self::getUInt2d($this->data, $this->pos + 2);
945
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
946 104
947
        // move stream pointer to next record
948 2
        $this->pos += 4 + $length;
949
950 2
        // offset: 0; size: 2; code page identifier
951
        $codepage = self::getUInt2d($recordData, 0);
952 3
953
        $this->codepage = CodePage::numberToName($codepage);
954 3
    }
955
956 2
    /**
957
     * DATEMODE.
958 2
     *
959
     * This record specifies the base date for displaying date
960 1
     * values. All dates are stored as count of days past this
961
     * base date. In BIFF2-BIFF4 this record is part of the
962 1
     * Calculation Settings Block. In BIFF5-BIFF8 it is
963
     * stored in the Workbook Globals Substream.
964 113
     *
965
     * --    "OpenOffice.org's Documentation of the Microsoft
966 113
     *         Excel File Format"
967
     */
968 112
    protected function readDateMode(): void
969
    {
970 112
        $length = self::getUInt2d($this->data, $this->pos + 2);
971
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
972
973
        // move stream pointer to next record
974
        $this->pos += 4 + $length;
975 113
976 17
        // offset: 0; size: 2; 0 = base 1900, 1 = base 1904
977 17
        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
978 17
        $this->spreadsheet->setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
979
        if (ord($recordData[0]) == 1) {
980
            Date::setExcelCalendar(Date::CALENDAR_MAC_1904);
981
            $this->spreadsheet->setExcelCalendar(Date::CALENDAR_MAC_1904);
982 17
        }
983
    }
984
985
    /**
986 113
     * Read a FONT record.
987
     */
988 12
    protected function readFont(): void
989 12
    {
990
        $length = self::getUInt2d($this->data, $this->pos + 2);
991
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
992 12
993
        // move stream pointer to next record
994
        $this->pos += 4 + $length;
995
996
        if (!$this->readDataOnly) {
997
            $objFont = new Font();
998 12
999
            // offset: 0; size: 2; height of the font (in twips = 1/20 of a point)
1000 12
            $size = self::getUInt2d($recordData, 0);
1001
            $objFont->setSize($size / 20);
1002 12
1003 12
            // offset: 2; size: 2; option flags
1004 12
            // bit: 0; mask 0x0001; bold (redundant in BIFF5-BIFF8)
1005 12
            // bit: 1; mask 0x0002; italic
1006
            $isItalic = (0x0002 & self::getUInt2d($recordData, 2)) >> 1;
1007 12
            if ($isItalic) {
1008 12
                $objFont->setItalic(true);
1009
            }
1010
1011 12
            // bit: 2; mask 0x0004; underlined (redundant in BIFF5-BIFF8)
1012 12
            // bit: 3; mask 0x0008; strikethrough
1013
            $isStrike = (0x0008 & self::getUInt2d($recordData, 2)) >> 3;
1014 12
            if ($isStrike) {
1015 12
                $objFont->setStrikethrough(true);
1016
            }
1017 2
1018
            // offset: 4; size: 2; colour index
1019
            $colorIndex = self::getUInt2d($recordData, 4);
1020 2
            $objFont->colorIndex = $colorIndex;
1021 2
1022 2
            // offset: 6; size: 2; font weight
1023
            $weight = self::getUInt2d($recordData, 6); // regular=400 bold=700
1024
            if ($weight >= 550) {
1025
                $objFont->setBold(true);
1026 2
            }
1027 12
1028
            // offset: 8; size: 2; escapement type
1029
            $escapement = self::getUInt2d($recordData, 8);
1030 12
            CellFont::escapement($objFont, $escapement);
1031
1032
            // offset: 10; size: 1; underline type
1033
            $underlineType = ord($recordData[10]);
1034
            CellFont::underline($objFont, $underlineType);
1035
1036 12
            // offset: 11; size: 1; font family
1037
            // offset: 12; size: 1; character set
1038
            // offset: 13; size: 1; not used
1039
            // offset: 14; size: var; font name
1040 12
            if ($this->version == self::XLS_BIFF8) {
1041 12
                $string = self::readUnicodeStringShort(substr($recordData, 14));
1042 12
            } else {
1043 12
                $string = $this->readByteStringShort(substr($recordData, 14));
1044
            }
1045
            $objFont->setName($string['value']);
1046 12
1047 12
            $this->objFonts[] = $objFont;
1048 12
        }
1049 12
    }
1050 12
1051
    /**
1052
     * FORMAT.
1053 12
     *
1054 12
     * This record contains information about a number format.
1055 12
     * All FORMAT records occur together in a sequential list.
1056 12
     *
1057 12
     * In BIFF2-BIFF4 other records referencing a FORMAT record
1058
     * contain a zero-based index into this list. From BIFF5 on
1059
     * the FORMAT record contains the index itself that will be
1060 11
     * used by other records.
1061 9
     *
1062 9
     * --    "OpenOffice.org's Documentation of the Microsoft
1063
     *         Excel File Format"
1064 9
     */
1065 11
    protected function readFormat(): void
1066 12
    {
1067 12
        $length = self::getUInt2d($this->data, $this->pos + 2);
1068 12
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1069 12
1070
        // move stream pointer to next record
1071 12
        $this->pos += 4 + $length;
1072
1073
        if (!$this->readDataOnly) {
1074 12
            $indexCode = self::getUInt2d($recordData, 0);
1075 12
1076
            if ($this->version == self::XLS_BIFF8) {
1077
                $string = self::readUnicodeStringLong(substr($recordData, 2));
1078
            } else {
1079
                // BIFF7
1080 12
                $string = $this->readByteStringShort(substr($recordData, 2));
1081
            }
1082
1083
            $formatString = $string['value'];
1084
            // Apache Open Office sets wrong case writing to xls - issue 2239
1085
            if ($formatString === 'GENERAL') {
1086
                $formatString = NumberFormat::FORMAT_GENERAL;
1087
            }
1088
            $this->formats[$indexCode] = $formatString;
1089 113
        }
1090 111
    }
1091
1092 1
    /**
1093 1
     * XF - Extended Format.
1094 1
     *
1095 1
     * This record contains formatting information for cells, rows, columns or styles.
1096
     * According to https://support.microsoft.com/en-us/help/147732 there are always at least 15 cell style XF
1097
     * and 1 cell XF.
1098
     * Inspection of Excel files generated by MS Office Excel shows that XF records 0-14 are cell style XF
1099
     * and XF record 15 is a cell XF
1100 113
     * We only read the first cell style XF and skip the remaining cell style XF records
1101 2
     * We read all cell XF records.
1102 2
     *
1103
     * --    "OpenOffice.org's Documentation of the Microsoft
1104
     *         Excel File Format"
1105
     */
1106
    protected function readXf(): void
1107
    {
1108
        $length = self::getUInt2d($this->data, $this->pos + 2);
1109
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1110 2
1111 2
        // move stream pointer to next record
1112
        $this->pos += 4 + $length;
1113
1114 113
        $objStyle = new Style();
1115 108
1116
        if (!$this->readDataOnly) {
1117
            // offset:  0; size: 2; Index to FONT record
1118 114
            if (self::getUInt2d($recordData, 0) < 4) {
1119 5
                $fontIndex = self::getUInt2d($recordData, 0);
1120
            } else {
1121
                // this has to do with that index 4 is omitted in all BIFF versions for some strange reason
1122
                // check the OpenOffice documentation of the FONT record
1123 113
                $fontIndex = self::getUInt2d($recordData, 0) - 1;
1124 15
            }
1125 5
            if (isset($this->objFonts[$fontIndex])) {
1126 5
                $objStyle->setFont($this->objFonts[$fontIndex]);
1127
            }
1128
1129 5
            // offset:  2; size: 2; Index to FORMAT record
1130
            $numberFormatIndex = self::getUInt2d($recordData, 2);
1131 5
            if (isset($this->formats[$numberFormatIndex])) {
1132 5
                // then we have user-defined format code
1133
                $numberFormat = ['formatCode' => $this->formats[$numberFormatIndex]];
1134 5
            } elseif (($code = NumberFormat::builtInFormatCode($numberFormatIndex)) !== '') {
1135
                // then we have built-in format code
1136
                $numberFormat = ['formatCode' => $code];
1137
            } else {
1138 5
                // we set the general format code
1139 5
                $numberFormat = ['formatCode' => NumberFormat::FORMAT_GENERAL];
1140 5
            }
1141
            $objStyle->getNumberFormat()->setFormatCode($numberFormat['formatCode']);
1142
1143 5
            // offset:  4; size: 2; XF type, cell protection, and parent style XF
1144
            // bit 2-0; mask 0x0007; XF_TYPE_PROT
1145 5
            $xfTypeProt = self::getUInt2d($recordData, 4);
1146 5
            // bit 0; mask 0x01; 1 = cell is locked
1147
            $isLocked = (0x01 & $xfTypeProt) >> 0;
1148
            $objStyle->getProtection()->setLocked($isLocked ? Protection::PROTECTION_INHERIT : Protection::PROTECTION_UNPROTECTED);
1149 5
1150
            // bit 1; mask 0x02; 1 = Formula is hidden
1151
            $isHidden = (0x02 & $xfTypeProt) >> 1;
1152
            $objStyle->getProtection()->setHidden($isHidden ? Protection::PROTECTION_PROTECTED : Protection::PROTECTION_UNPROTECTED);
1153
1154
            // bit 2; mask 0x04; 0 = Cell XF, 1 = Cell Style XF
1155
            $isCellStyleXf = (0x04 & $xfTypeProt) >> 2;
1156
1157
            // offset:  6; size: 1; Alignment and text break
1158
            // bit 2-0, mask 0x07; horizontal alignment
1159
            $horAlign = (0x07 & ord($recordData[6])) >> 0;
1160
            Xls\Style\CellAlignment::horizontal($objStyle->getAlignment(), $horAlign);
1161
1162
            // bit 3, mask 0x08; wrap text
1163
            $wrapText = (0x08 & ord($recordData[6])) >> 3;
1164
            Xls\Style\CellAlignment::wrap($objStyle->getAlignment(), $wrapText);
1165
1166
            // bit 6-4, mask 0x70; vertical alignment
1167
            $vertAlign = (0x70 & ord($recordData[6])) >> 4;
1168
            Xls\Style\CellAlignment::vertical($objStyle->getAlignment(), $vertAlign);
1169
1170
            if ($this->version == self::XLS_BIFF8) {
1171
                // offset:  7; size: 1; XF_ROTATION: Text rotation angle
1172
                $angle = ord($recordData[7]);
1173
                $rotation = 0;
1174
                if ($angle <= 90) {
1175
                    $rotation = $angle;
1176
                } elseif ($angle <= 180) {
1177
                    $rotation = 90 - $angle;
1178
                } elseif ($angle == Alignment::TEXTROTATION_STACK_EXCEL) {
1179
                    $rotation = Alignment::TEXTROTATION_STACK_PHPSPREADSHEET;
1180
                }
1181
                $objStyle->getAlignment()->setTextRotation($rotation);
1182
1183
                // offset:  8; size: 1; Indentation, shrink to cell size, and text direction
1184
                // bit: 3-0; mask: 0x0F; indent level
1185
                $indent = (0x0F & ord($recordData[8])) >> 0;
1186
                $objStyle->getAlignment()->setIndent($indent);
1187
1188
                // bit: 4; mask: 0x10; 1 = shrink content to fit into cell
1189
                $shrinkToFit = (0x10 & ord($recordData[8])) >> 4;
1190
                switch ($shrinkToFit) {
1191
                    case 0:
1192
                        $objStyle->getAlignment()->setShrinkToFit(false);
1193
1194 10
                        break;
1195 10
                    case 1:
1196 5
                        $objStyle->getAlignment()->setShrinkToFit(true);
1197
1198 5
                        break;
1199 5
                }
1200
1201 5
                // offset:  9; size: 1; Flags used for attribute groups
1202
1203 5
                // offset: 10; size: 4; Cell border lines and background area
1204
                // bit: 3-0; mask: 0x0000000F; left style
1205 5
                if ($bordersLeftStyle = Xls\Style\Border::lookup((0x0000000F & self::getInt4d($recordData, 10)) >> 0)) {
1206
                    $objStyle->getBorders()->getLeft()->setBorderStyle($bordersLeftStyle);
1207 5
                }
1208
                // bit: 7-4; mask: 0x000000F0; right style
1209
                if ($bordersRightStyle = Xls\Style\Border::lookup((0x000000F0 & self::getInt4d($recordData, 10)) >> 4)) {
1210
                    $objStyle->getBorders()->getRight()->setBorderStyle($bordersRightStyle);
1211
                }
1212
                // bit: 11-8; mask: 0x00000F00; top style
1213
                if ($bordersTopStyle = Xls\Style\Border::lookup((0x00000F00 & self::getInt4d($recordData, 10)) >> 8)) {
1214 113
                    $objStyle->getBorders()->getTop()->setBorderStyle($bordersTopStyle);
1215
                }
1216 113
                // bit: 15-12; mask: 0x0000F000; bottom style
1217
                if ($bordersBottomStyle = Xls\Style\Border::lookup((0x0000F000 & self::getInt4d($recordData, 10)) >> 12)) {
1218
                    $objStyle->getBorders()->getBottom()->setBorderStyle($bordersBottomStyle);
1219
                }
1220
                // bit: 22-16; mask: 0x007F0000; left color
1221
                $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & self::getInt4d($recordData, 10)) >> 16;
1222
1223
                // bit: 29-23; mask: 0x3F800000; right color
1224
                $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & self::getInt4d($recordData, 10)) >> 23;
1225
1226
                // bit: 30; mask: 0x40000000; 1 = diagonal line from top left to right bottom
1227
                $diagonalDown = (0x40000000 & self::getInt4d($recordData, 10)) >> 30 ? true : false;
1228 123
1229
                // bit: 31; mask: 0x800000; 1 = diagonal line from bottom left to top right
1230 123
                $diagonalUp = (self::HIGH_ORDER_BIT & self::getInt4d($recordData, 10)) >> 31 ? true : false;
1231
1232
                if ($diagonalUp === false) {
1233 123
                    if ($diagonalDown === false) {
1234 123
                        $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
1235
                    } else {
1236
                        $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
1237
                    }
1238
                } elseif ($diagonalDown === false) {
1239
                    $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
1240
                } else {
1241
                    $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
1242
                }
1243
1244
                // offset: 14; size: 4;
1245
                // bit: 6-0; mask: 0x0000007F; top color
1246
                $objStyle->getBorders()->getTop()->colorIndex = (0x0000007F & self::getInt4d($recordData, 14)) >> 0;
1247
1248
                // bit: 13-7; mask: 0x00003F80; bottom color
1249
                $objStyle->getBorders()->getBottom()->colorIndex = (0x00003F80 & self::getInt4d($recordData, 14)) >> 7;
1250
1251
                // bit: 20-14; mask: 0x001FC000; diagonal color
1252
                $objStyle->getBorders()->getDiagonal()->colorIndex = (0x001FC000 & self::getInt4d($recordData, 14)) >> 14;
1253
1254
                // bit: 24-21; mask: 0x01E00000; diagonal style
1255
                if ($bordersDiagonalStyle = Xls\Style\Border::lookup((0x01E00000 & self::getInt4d($recordData, 14)) >> 21)) {
1256
                    $objStyle->getBorders()->getDiagonal()->setBorderStyle($bordersDiagonalStyle);
1257
                }
1258
1259
                // bit: 31-26; mask: 0xFC000000 fill pattern
1260
                if ($fillType = FillPattern::lookup((self::FC000000 & self::getInt4d($recordData, 14)) >> 26)) {
1261
                    $objStyle->getFill()->setFillType($fillType);
1262
                }
1263
                // offset: 18; size: 2; pattern and background colour
1264
                // bit: 6-0; mask: 0x007F; color index for pattern color
1265
                $objStyle->getFill()->startcolorIndex = (0x007F & self::getUInt2d($recordData, 18)) >> 0;
1266
1267
                // bit: 13-7; mask: 0x3F80; color index for pattern background
1268
                $objStyle->getFill()->endcolorIndex = (0x3F80 & self::getUInt2d($recordData, 18)) >> 7;
1269
            } else {
1270
                // BIFF5
1271
1272
                // offset: 7; size: 1; Text orientation and flags
1273
                $orientationAndFlags = ord($recordData[7]);
1274
1275
                // bit: 1-0; mask: 0x03; XF_ORIENTATION: Text orientation
1276
                $xfOrientation = (0x03 & $orientationAndFlags) >> 0;
1277
                switch ($xfOrientation) {
1278 123
                    case 0:
1279
                        $objStyle->getAlignment()->setTextRotation(0);
1280
1281 123
                        break;
1282
                    case 1:
1283 123
                        $objStyle->getAlignment()->setTextRotation(Alignment::TEXTROTATION_STACK_PHPSPREADSHEET);
1284
1285 123
                        break;
1286
                    case 2:
1287 123
                        $objStyle->getAlignment()->setTextRotation(90);
1288
1289 123
                        break;
1290
                    case 3:
1291
                        $objStyle->getAlignment()->setTextRotation(-90);
1292
1293
                        break;
1294
                }
1295 114
1296
                // offset: 8; size: 4; cell border lines and background area
1297 114
                $borderAndBackground = self::getInt4d($recordData, 8);
1298 3
1299
                // bit: 6-0; mask: 0x0000007F; color index for pattern color
1300
                $objStyle->getFill()->startcolorIndex = (0x0000007F & $borderAndBackground) >> 0;
1301
1302
                // bit: 13-7; mask: 0x00003F80; color index for pattern background
1303
                $objStyle->getFill()->endcolorIndex = (0x00003F80 & $borderAndBackground) >> 7;
1304
1305
                // bit: 21-16; mask: 0x003F0000; fill pattern
1306
                $objStyle->getFill()->setFillType(FillPattern::lookup((0x003F0000 & $borderAndBackground) >> 16));
1307
1308
                // bit: 24-22; mask: 0x01C00000; bottom line style
1309
                $objStyle->getBorders()->getBottom()->setBorderStyle(Xls\Style\Border::lookup((0x01C00000 & $borderAndBackground) >> 22));
1310
1311 111
                // bit: 31-25; mask: 0xFE000000; bottom line color
1312
                $objStyle->getBorders()->getBottom()->colorIndex = (self::FE000000 & $borderAndBackground) >> 25;
1313
1314
                // offset: 12; size: 4; cell border lines
1315
                $borderLines = self::getInt4d($recordData, 12);
1316
1317
                // bit: 2-0; mask: 0x00000007; top line style
1318 111
                $objStyle->getBorders()->getTop()->setBorderStyle(Xls\Style\Border::lookup((0x00000007 & $borderLines) >> 0));
1319
1320
                // bit: 5-3; mask: 0x00000038; left line style
1321 111
                $objStyle->getBorders()->getLeft()->setBorderStyle(Xls\Style\Border::lookup((0x00000038 & $borderLines) >> 3));
1322
1323
                // bit: 8-6; mask: 0x000001C0; right line style
1324
                $objStyle->getBorders()->getRight()->setBorderStyle(Xls\Style\Border::lookup((0x000001C0 & $borderLines) >> 6));
1325 111
1326
                // bit: 15-9; mask: 0x0000FE00; top line color index
1327 111
                $objStyle->getBorders()->getTop()->colorIndex = (0x0000FE00 & $borderLines) >> 9;
1328
1329
                // bit: 22-16; mask: 0x007F0000; left line color index
1330
                $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & $borderLines) >> 16;
1331 111
1332
                // bit: 29-23; mask: 0x3F800000; right line color index
1333 111
                $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & $borderLines) >> 23;
1334
            }
1335
1336 111
            // add cellStyleXf or cellXf and update mapping
1337
            if ($isCellStyleXf) {
1338
                // we only read one style XF record which is always the first
1339
                if ($this->xfIndex == 0) {
1340 111
                    $this->spreadsheet->addCellStyleXf($objStyle);
1341 111
                    $this->mapCellStyleXfIndex[$this->xfIndex] = 0;
1342
                }
1343 111
            } else {
1344 111
                // we read all cell XF records
1345 107
                $this->spreadsheet->addCellXf($objStyle);
1346
                $this->mapCellXfIndex[$this->xfIndex] = count($this->spreadsheet->getCellXfCollection()) - 1;
1347 107
            }
1348 111
1349
            // update XF index for when we read next record
1350 1
            ++$this->xfIndex;
1351 111
        }
1352 109
    }
1353 109
1354 109
    protected function readXfExt(): void
1355 109
    {
1356
        $length = self::getUInt2d($this->data, $this->pos + 2);
1357 109
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1358 111
1359
        // move stream pointer to next record
1360 111
        $this->pos += 4 + $length;
1361
1362 111
        if (!$this->readDataOnly) {
1363 2
            // offset: 0; size: 2; 0x087D = repeated header
1364
1365
            // offset: 2; size: 2
1366
1367
            // offset: 4; size: 8; not used
1368
1369 111
            // offset: 12; size: 2; record version
1370 111
1371
            // offset: 14; size: 2; index to XF record which this record modifies
1372 111
            $ixfe = self::getUInt2d($recordData, 14);
1373 111
1374 62
            // offset: 16; size: 2; not used
1375
1376 62
            // offset: 18; size: 2; number of extension properties that follow
1377 111
            //$cexts = self::getUInt2d($recordData, 18);
1378 15
1379
            // start reading the actual extension data
1380 15
            $offset = 20;
1381 111
            while ($offset < $length) {
1382 98
                // extension type
1383
                $extType = self::getUInt2d($recordData, $offset);
1384 98
1385 111
                // extension length
1386 15
                $cb = self::getUInt2d($recordData, $offset + 2);
1387
1388 15
                // extension data
1389 111
                $extData = substr($recordData, $offset + 4, $cb);
1390 15
1391
                switch ($extType) {
1392 15
                    case 4:        // fill start color
1393 111
                        $xclfType = self::getUInt2d($extData, 0); // color type
1394
                        $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
1395
1396 111
                        if ($xclfType == 2) {
1397 109
                            $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
1398
1399 109
                            // modify the relevant style property
1400 111
                            if (isset($this->mapCellXfIndex[$ixfe])) {
1401
                                $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill();
1402 3
                                $fill->getStartColor()->setRGB($rgb);
1403 111
                                $fill->startcolorIndex = null; // normal color index does not apply, discard
1404
                            }
1405 3
                        }
1406 111
1407
                        break;
1408 7
                    case 5:        // fill end color
1409 111
                        $xclfType = self::getUInt2d($extData, 0); // color type
1410 105
                        $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
1411
1412 105
                        if ($xclfType == 2) {
1413 111
                            $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
1414 110
1415
                            // modify the relevant style property
1416 110
                            if (isset($this->mapCellXfIndex[$ixfe])) {
1417 108
                                $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill();
1418
                                $fill->getEndColor()->setRGB($rgb);
1419
                                $fill->endcolorIndex = null; // normal color index does not apply, discard
1420 108
                            }
1421
                        }
1422
1423 108
                        break;
1424
                    case 7:        // border color top
1425
                        $xclfType = self::getUInt2d($extData, 0); // color type
1426 108
                        $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
1427
1428
                        if ($xclfType == 2) {
1429 108
                            $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
1430
1431 42
                            // modify the relevant style property
1432 108
                            if (isset($this->mapCellXfIndex[$ixfe])) {
1433
                                $top = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getTop();
1434 107
                                $top->getColor()->setRGB($rgb);
1435
                                $top->colorIndex = null; // normal color index does not apply, discard
1436
                            }
1437
                        }
1438
1439
                        break;
1440
                    case 8:        // border color bottom
1441
                        $xclfType = self::getUInt2d($extData, 0); // color type
1442 114
                        $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
1443
1444 114
                        if ($xclfType == 2) {
1445 4
                            $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
1446
1447
                            // modify the relevant style property
1448
                            if (isset($this->mapCellXfIndex[$ixfe])) {
1449
                                $bottom = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getBottom();
1450
                                $bottom->getColor()->setRGB($rgb);
1451
                                $bottom->colorIndex = null; // normal color index does not apply, discard
1452
                            }
1453
                        }
1454
1455
                        break;
1456
                    case 9:        // border color left
1457
                        $xclfType = self::getUInt2d($extData, 0); // color type
1458 110
                        $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
1459
1460
                        if ($xclfType == 2) {
1461
                            $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
1462
1463
                            // modify the relevant style property
1464
                            if (isset($this->mapCellXfIndex[$ixfe])) {
1465 110
                                $left = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getLeft();
1466
                                $left->getColor()->setRGB($rgb);
1467
                                $left->colorIndex = null; // normal color index does not apply, discard
1468 110
                            }
1469
                        }
1470
1471
                        break;
1472 110
                    case 10:        // border color right
1473
                        $xclfType = self::getUInt2d($extData, 0); // color type
1474 110
                        $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
1475
1476
                        if ($xclfType == 2) {
1477
                            $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
1478 110
1479
                            // modify the relevant style property
1480 110
                            if (isset($this->mapCellXfIndex[$ixfe])) {
1481
                                $right = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getRight();
1482
                                $right->getColor()->setRGB($rgb);
1483 110
                                $right->colorIndex = null; // normal color index does not apply, discard
1484
                            }
1485
                        }
1486
1487 110
                        break;
1488 110
                    case 11:        // border color diagonal
1489
                        $xclfType = self::getUInt2d($extData, 0); // color type
1490 110
                        $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
1491 107
1492 104
                        if ($xclfType == 2) {
1493
                            $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
1494 104
1495 107
                            // modify the relevant style property
1496 107
                            if (isset($this->mapCellXfIndex[$ixfe])) {
1497 107
                                $diagonal = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getDiagonal();
1498
                                $diagonal->getColor()->setRGB($rgb);
1499 107
                                $diagonal->colorIndex = null; // normal color index does not apply, discard
1500 106
                            }
1501
                        }
1502 1
1503 105
                        break;
1504 44
                    case 13:    // font color
1505 44
                        $xclfType = self::getUInt2d($extData, 0); // color type
1506 44
                        $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
1507 44
1508
                        if ($xclfType == 2) {
1509 44
                            $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
1510 105
1511
                            // modify the relevant style property
1512
                            if (isset($this->mapCellXfIndex[$ixfe])) {
1513
                                $font = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFont();
1514
                                $font->getColor()->setRGB($rgb);
1515 105
                                $font->colorIndex = null; // normal color index does not apply, discard
1516
                            }
1517
                        }
1518
1519
                        break;
1520
                }
1521 110
1522 110
                $offset += $cb;
1523
            }
1524 110
        }
1525 107
    }
1526 15
1527
    /**
1528 15
     * Read STYLE record.
1529 107
     */
1530
    protected function readStyle(): void
1531
    {
1532 107
        $length = self::getUInt2d($this->data, $this->pos + 2);
1533
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1534
1535 107
        // move stream pointer to next record
1536
        $this->pos += 4 + $length;
1537
1538 107
        if (!$this->readDataOnly) {
1539
            // offset: 0; size: 2; index to XF record and flag for built-in style
1540
            $ixfe = self::getUInt2d($recordData, 0);
1541 107
1542
            // bit: 11-0; mask 0x0FFF; index to XF record
1543
            //$xfIndex = (0x0FFF & $ixfe) >> 0;
1544 107
1545
            // bit: 15; mask 0x8000; 0 = user-defined style, 1 = built-in style
1546
            $isBuiltIn = (bool) ((0x8000 & $ixfe) >> 15);
1547 107
1548
            if ($isBuiltIn) {
1549
                // offset: 2; size: 1; identifier for built-in style
1550 107
                $builtInId = ord($recordData[2]);
1551
1552
                switch ($builtInId) {
1553 107
                    case 0x00:
1554
                        // currently, we are not using this for anything
1555 107
                        break;
1556 107
                    default:
1557
                        break;
1558 105
                }
1559 107
            }
1560
            // user-defined; not supported by PhpSpreadsheet
1561 105
        }
1562 107
    }
1563 2
1564
    /**
1565 2
     * Read PALETTE record.
1566 107
     */
1567 34
    protected function readPalette(): void
1568
    {
1569 34
        $length = self::getUInt2d($this->data, $this->pos + 2);
1570 107
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1571
1572 107
        // move stream pointer to next record
1573
        $this->pos += 4 + $length;
1574
1575
        if (!$this->readDataOnly) {
1576
            // offset: 0; size: 2; number of following colors
1577
            $nm = self::getUInt2d($recordData, 0);
1578
1579
            // list of RGB colors
1580 123
            for ($i = 0; $i < $nm; ++$i) {
1581
                $rgb = substr($recordData, 2 + 4 * $i, 4);
1582 123
                $this->palette[] = self::readRGB($rgb);
1583
            }
1584
        }
1585 123
    }
1586
1587
    /**
1588
     * SHEET.
1589
     *
1590
     * This record is  located in the  Workbook Globals
1591
     * Substream  and represents a sheet inside the workbook.
1592 3
     * One SHEET record is written for each sheet. It stores the
1593
     * sheet name and a stream offset to the BOF record of the
1594 3
     * respective Sheet Substream within the Workbook Stream.
1595 3
     *
1596
     * --    "OpenOffice.org's Documentation of the Microsoft
1597
     *         Excel File Format"
1598 3
     */
1599
    protected function readSheet(): void
1600 3
    {
1601
        $length = self::getUInt2d($this->data, $this->pos + 2);
1602
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1603
1604 3
        // offset: 0; size: 4; absolute stream position of the BOF record of the sheet
1605 3
        // NOTE: not encrypted
1606 2
        $rec_offset = self::getInt4d($this->data, $this->pos + 4);
1607 2
1608 2
        // move stream pointer to next record
1609 2
        $this->pos += 4 + $length;
1610 2
1611 2
        // offset: 4; size: 1; sheet state
1612 2
        $sheetState = match (ord($recordData[4])) {
1613 2
            0x00 => Worksheet::SHEETSTATE_VISIBLE,
1614
            0x01 => Worksheet::SHEETSTATE_HIDDEN,
1615 1
            0x02 => Worksheet::SHEETSTATE_VERYHIDDEN,
1616 1
            default => Worksheet::SHEETSTATE_VISIBLE,
1617
        };
1618
1619
        // offset: 5; size: 1; sheet type
1620
        $sheetType = ord($recordData[5]);
1621
1622
        // offset: 6; size: var; sheet name
1623
        $rec_name = null;
1624
        if ($this->version == self::XLS_BIFF8) {
1625
            $string = self::readUnicodeStringShort(substr($recordData, 6));
1626 1
            $rec_name = $string['value'];
1627
        } elseif ($this->version == self::XLS_BIFF7) {
1628 1
            $string = $this->readByteStringShort(substr($recordData, 6));
1629
            $rec_name = $string['value'];
1630 1
        }
1631
1632
        $this->sheets[] = [
1633
            'name' => $rec_name,
1634
            'offset' => $rec_offset,
1635
            'sheetState' => $sheetState,
1636
            'sheetType' => $sheetType,
1637 1
        ];
1638
    }
1639
1640
    /**
1641
     * Read EXTERNALBOOK record.
1642
     */
1643
    protected function readExternalBook(): void
1644
    {
1645
        $length = self::getUInt2d($this->data, $this->pos + 2);
1646 2
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1647
1648 2
        // move stream pointer to next record
1649 2
        $this->pos += 4 + $length;
1650
1651
        // offset within record data
1652 2
        $offset = 0;
1653
1654 2
        // there are 4 types of records
1655
        if (strlen($recordData) > 4) {
1656
            // external reference
1657
            // offset: 0; size: 2; number of sheet names ($nm)
1658
            $nm = self::getUInt2d($recordData, 0);
1659
            $offset += 2;
1660
1661
            // offset: 2; size: var; encoded URL without sheet name (Unicode string, 16-bit length)
1662
            $encodedUrlString = self::readUnicodeStringLong(substr($recordData, 2));
1663
            $offset += $encodedUrlString['size'];
1664 2
1665 2
            // offset: var; size: var; list of $nm sheet names (Unicode strings, 16-bit length)
1666
            $externalSheetNames = [];
1667 2
            for ($i = 0; $i < $nm; ++$i) {
1668 2
                $externalSheetNameString = self::readUnicodeStringLong(substr($recordData, $offset));
1669
                $externalSheetNames[] = $externalSheetNameString['value'];
1670 2
                $offset += $externalSheetNameString['size'];
1671 2
            }
1672
1673 2
            // store the record data
1674
            $this->externalBooks[] = [
1675
                'type' => 'external',
1676 2
                'encodedUrl' => $encodedUrlString['value'],
1677 2
                'externalSheetNames' => $externalSheetNames,
1678
            ];
1679
        } elseif (substr($recordData, 2, 2) == pack('CC', 0x01, 0x04)) {
1680
            // internal reference
1681
            // offset: 0; size: 2; number of sheet in this document
1682 2
            // offset: 2; size: 2; 0x01 0x04
1683 2
            $this->externalBooks[] = [
1684 2
                'type' => 'internal',
1685 2
            ];
1686 2
        } elseif (substr($recordData, 0, 4) == pack('vCC', 0x0001, 0x01, 0x3A)) {
1687 2
            // add-in function
1688
            // offset: 0; size: 2; 0x0001
1689
            $this->externalBooks[] = [
1690
                'type' => 'addInFunction',
1691
            ];
1692
        } elseif (substr($recordData, 0, 2) == pack('v', 0x0000)) {
1693 123
            // DDE links, OLE links
1694
            // offset: 0; size: 2; 0x0000
1695 123
            // offset: 2; size: var; encoded source document name
1696 123
            $this->externalBooks[] = [
1697
                'type' => 'DDEorOLE',
1698
            ];
1699 123
        }
1700
    }
1701
1702 123
    /**
1703
     * Read EXTERNNAME record.
1704
     */
1705
    protected function readExternName(): void
1706 123
    {
1707 123
        $length = self::getUInt2d($this->data, $this->pos + 2);
1708
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1709
1710 123
        // move stream pointer to next record
1711
        $this->pos += 4 + $length;
1712 123
1713
        // external sheet references provided for named cells
1714
        if ($this->version == self::XLS_BIFF8) {
1715
            // offset: 0; size: 2; options
1716 117
            //$options = self::getUInt2d($recordData, 0);
1717
1718
            // offset: 2; size: 2;
1719
1720
            // offset: 4; size: 2; not used
1721
1722
            // offset: 6; size: var
1723
            $nameString = self::readUnicodeStringShort(substr($recordData, 6));
1724
1725
            // offset: var; size: var; formula data
1726
            $offset = 6 + $nameString['size'];
1727
            $formula = $this->getFormulaFromStructure(substr($recordData, $offset));
1728
1729
            $this->externalNames[] = [
1730
                'name' => $nameString['value'],
1731
                'formula' => $formula,
1732
            ];
1733
        }
1734
    }
1735
1736
    /**
1737
     * Read EXTERNSHEET record.
1738
     */
1739
    protected function readExternSheet(): void
1740
    {
1741
        $length = self::getUInt2d($this->data, $this->pos + 2);
1742
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1743
1744
        // move stream pointer to next record
1745
        $this->pos += 4 + $length;
1746
1747
        // external sheet references provided for named cells
1748
        if ($this->version == self::XLS_BIFF8) {
1749
            // offset: 0; size: 2; number of following ref structures
1750
            $nm = self::getUInt2d($recordData, 0);
1751
            for ($i = 0; $i < $nm; ++$i) {
1752
                $this->ref[] = [
1753
                    // offset: 2 + 6 * $i; index to EXTERNALBOOK record
1754
                    'externalBookIndex' => self::getUInt2d($recordData, 2 + 6 * $i),
1755
                    // offset: 4 + 6 * $i; index to first sheet in EXTERNALBOOK record
1756
                    'firstSheetIndex' => self::getUInt2d($recordData, 4 + 6 * $i),
1757
                    // offset: 6 + 6 * $i; index to last sheet in EXTERNALBOOK record
1758
                    'lastSheetIndex' => self::getUInt2d($recordData, 6 + 6 * $i),
1759
                ];
1760
            }
1761
        }
1762
    }
1763
1764
    /**
1765
     * DEFINEDNAME.
1766
     *
1767
     * This record is part of a Link Table. It contains the name
1768
     * and the token array of an internal defined name. Token
1769
     * arrays of defined names contain tokens with aberrant
1770
     * token classes.
1771
     *
1772
     * --    "OpenOffice.org's Documentation of the Microsoft
1773
     *         Excel File Format"
1774
     */
1775
    protected function readDefinedName(): void
1776
    {
1777
        $length = self::getUInt2d($this->data, $this->pos + 2);
1778
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
1779
1780
        // move stream pointer to next record
1781
        $this->pos += 4 + $length;
1782
1783
        if ($this->version == self::XLS_BIFF8) {
1784
            // retrieves named cells
1785
1786
            // offset: 0; size: 2; option flags
1787
            $opts = self::getUInt2d($recordData, 0);
1788
1789
            // bit: 5; mask: 0x0020; 0 = user-defined name, 1 = built-in-name
1790
            $isBuiltInName = (0x0020 & $opts) >> 5;
1791
1792
            // offset: 2; size: 1; keyboard shortcut
1793
1794
            // offset: 3; size: 1; length of the name (character count)
1795
            $nlen = ord($recordData[3]);
1796
1797
            // offset: 4; size: 2; size of the formula data (it can happen that this is zero)
1798
            // note: there can also be additional data, this is not included in $flen
1799
            $flen = self::getUInt2d($recordData, 4);
1800
1801
            // offset: 8; size: 2; 0=Global name, otherwise index to sheet (1-based)
1802
            $scope = self::getUInt2d($recordData, 8);
1803
1804
            // offset: 14; size: var; Name (Unicode string without length field)
1805
            $string = self::readUnicodeString(substr($recordData, 14), $nlen);
1806
1807
            // offset: var; size: $flen; formula data
1808
            $offset = 14 + $string['size'];
1809
            $formulaStructure = pack('v', $flen) . substr($recordData, $offset);
1810
1811
            try {
1812
                $formula = $this->getFormulaFromStructure($formulaStructure);
1813
            } catch (PhpSpreadsheetException) {
1814
                $formula = '';
1815
                $isBuiltInName = 0;
1816
            }
1817
1818
            $this->definedname[] = [
1819
                'isBuiltInName' => $isBuiltInName,
1820
                'name' => $string['value'],
1821
                'formula' => $formula,
1822
                'scope' => $scope,
1823
            ];
1824
        }
1825
    }
1826
1827
    /**
1828
     * Read MSODRAWINGGROUP record.
1829
     */
1830
    protected function readMsoDrawingGroup(): void
1831
    {
1832
        //$length = self::getUInt2d($this->data, $this->pos + 2);
1833
1834
        // get spliced record data
1835
        $splicedRecordData = $this->getSplicedRecordData();
1836
        $recordData = $splicedRecordData['recordData'];
1837
1838
        $this->drawingGroupData .= $recordData;
1839
    }
1840
1841
    /**
1842
     * SST - Shared String Table.
1843
     *
1844
     * This record contains a list of all strings used anywhere
1845
     * in the workbook. Each string occurs only once. The
1846
     * workbook uses indexes into the list to reference the
1847
     * strings.
1848
     *
1849
     * --    "OpenOffice.org's Documentation of the Microsoft
1850
     *         Excel File Format"
1851
     */
1852
    protected function readSst(): void
1853
    {
1854
        // offset within (spliced) record data
1855
        $pos = 0;
1856
1857
        // Limit global SST position, further control for bad SST Length in BIFF8 data
1858
        $limitposSST = 0;
1859
1860
        // get spliced record data
1861
        $splicedRecordData = $this->getSplicedRecordData();
1862
1863
        $recordData = $splicedRecordData['recordData'];
1864
        $spliceOffsets = $splicedRecordData['spliceOffsets'];
1865
1866
        // offset: 0; size: 4; total number of strings in the workbook
1867
        $pos += 4;
1868
1869
        // offset: 4; size: 4; number of following strings ($nm)
1870
        $nm = self::getInt4d($recordData, 4);
1871
        $pos += 4;
1872
1873
        // look up limit position
1874
        foreach ($spliceOffsets as $spliceOffset) {
1875
            // it can happen that the string is empty, therefore we need
1876
            // <= and not just <
1877
            if ($pos <= $spliceOffset) {
1878
                $limitposSST = $spliceOffset;
1879
            }
1880
        }
1881
1882
        // loop through the Unicode strings (16-bit length)
1883
        for ($i = 0; $i < $nm && $pos < $limitposSST; ++$i) {
1884
            // number of characters in the Unicode string
1885
            $numChars = self::getUInt2d($recordData, $pos);
1886
            $pos += 2;
1887
1888
            // option flags
1889
            $optionFlags = ord($recordData[$pos]);
1890
            ++$pos;
1891
1892 120
            // bit: 0; mask: 0x01; 0 = compressed; 1 = uncompressed
1893
            $isCompressed = (($optionFlags & 0x01) == 0);
1894 120
1895 120
            // bit: 2; mask: 0x02; 0 = ordinary; 1 = Asian phonetic
1896
            $hasAsian = (($optionFlags & 0x04) != 0);
1897
1898 120
            // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text
1899
            $hasRichText = (($optionFlags & 0x08) != 0);
1900
1901 120
            $formattingRuns = 0;
1902
            if ($hasRichText) {
1903 120
                // number of Rich-Text formatting runs
1904
                $formattingRuns = self::getUInt2d($recordData, $pos);
1905
                $pos += 2;
1906
            }
1907
1908
            $extendedRunLength = 0;
1909
            if ($hasAsian) {
1910
                // size of Asian phonetic setting
1911
                $extendedRunLength = self::getInt4d($recordData, $pos);
1912
                $pos += 4;
1913
            }
1914
1915
            // expected byte length of character array if not split
1916
            $len = ($isCompressed) ? $numChars : $numChars * 2;
1917
1918 113
            // look up limit position - Check it again to be sure that no error occurs when parsing SST structure
1919
            $limitpos = null;
1920 113
            foreach ($spliceOffsets as $spliceOffset) {
1921 113
                // it can happen that the string is empty, therefore we need
1922
                // <= and not just <
1923
                if ($pos <= $spliceOffset) {
1924 113
                    $limitpos = $spliceOffset;
1925
1926
                    break;
1927 113
                }
1928 113
            }
1929 113
1930 3
            if ($pos + $len <= $limitpos) {
1931 3
                // character array is not split between records
1932
1933
                $retstr = substr($recordData, $pos, $len);
1934
                $pos += $len;
1935
            } else {
1936
                // character array is split between records
1937
1938 113
                // first part of character array
1939
                $retstr = substr($recordData, $pos, $limitpos - $pos);
1940 113
1941 113
                $bytesRead = $limitpos - $pos;
1942
1943
                // remaining characters in Unicode string
1944 113
                $charsLeft = $numChars - (($isCompressed) ? $bytesRead : ($bytesRead / 2));
1945
1946 113
                $pos = $limitpos;
1947 111
1948
                // keep reading the characters
1949
                while ($charsLeft > 0) {
1950 111
                    // look up next limit position, in case the string span more than one continue record
1951 111
                    foreach ($spliceOffsets as $spliceOffset) {
1952
                        if ($pos < $spliceOffset) {
1953
                            $limitpos = $spliceOffset;
1954
1955
                            break;
1956 111
                        }
1957 111
                    }
1958 51
1959
                    // repeated option flags
1960
                    // OpenOffice.org documentation 5.21
1961
                    $option = ord($recordData[$pos]);
1962
                    ++$pos;
1963 111
1964 111
                    if ($isCompressed && ($option == 0)) {
1965
                        // 1st fragment compressed
1966
                        // this fragment compressed
1967
                        $len = min($charsLeft, $limitpos - $pos);
1968
                        $retstr .= substr($recordData, $pos, $len);
1969 111
                        $charsLeft -= $len;
1970 111
                        $isCompressed = true;
1971
                    } elseif (!$isCompressed && ($option != 0)) {
1972
                        // 1st fragment uncompressed
1973 111
                        // this fragment uncompressed
1974 111
                        $len = min($charsLeft * 2, $limitpos - $pos);
1975 63
                        $retstr .= substr($recordData, $pos, $len);
1976
                        $charsLeft -= $len / 2;
1977
                        $isCompressed = false;
1978
                    } elseif (!$isCompressed && ($option == 0)) {
1979 111
                        // 1st fragment uncompressed
1980 111
                        // this fragment compressed
1981
                        $len = min($charsLeft, $limitpos - $pos);
1982
                        for ($j = 0; $j < $len; ++$j) {
1983 111
                            $retstr .= $recordData[$pos + $j]
1984 111
                                . chr(0);
1985
                        }
1986
                        $charsLeft -= $len;
1987
                        $isCompressed = false;
1988
                    } else {
1989
                        // 1st fragment compressed
1990 111
                        // this fragment uncompressed
1991 109
                        $newstr = '';
1992
                        $jMax = strlen($retstr);
1993 2
                        for ($j = 0; $j < $jMax; ++$j) {
1994
                            $newstr .= $retstr[$j] . chr(0);
1995 111
                        }
1996
                        $retstr = $newstr;
1997 111
                        $len = min($charsLeft * 2, $limitpos - $pos);
1998
                        $retstr .= substr($recordData, $pos, $len);
1999
                        $charsLeft -= $len / 2;
2000
                        $isCompressed = false;
2001
                    }
2002
2003
                    $pos += $len;
2004
                }
2005
            }
2006
2007
            // convert to UTF-8
2008
            $retstr = self::encodeUTF16($retstr, $isCompressed);
2009
2010
            // read additional Rich-Text information, if any
2011
            $fmtRuns = [];
2012
            if ($hasRichText) {
2013
                // list of formatting runs
2014
                for ($j = 0; $j < $formattingRuns; ++$j) {
2015 62
                    // first formatted character; zero-based
2016
                    $charPos = self::getUInt2d($recordData, $pos + $j * 4);
2017 62
2018 62
                    // index to font record
2019
                    $fontIndex = self::getUInt2d($recordData, $pos + 2 + $j * 4);
2020
2021 62
                    $fmtRuns[] = [
2022
                        'charPos' => $charPos,
2023 62
                        'fontIndex' => $fontIndex,
2024 60
                    ];
2025
                }
2026 60
                $pos += 4 * $formattingRuns;
2027 58
            }
2028
2029
            // read additional Asian phonetics information, if any
2030 2
            if ($hasAsian) {
2031
                // For Asian phonetic settings, we skip the extended string data
2032
                $pos += $extendedRunLength;
2033 60
            }
2034
2035 60
            // store the shared sting
2036 1
            $this->sst[] = [
2037
                'value' => $retstr,
2038 60
                'fmtRuns' => $fmtRuns,
2039
            ];
2040
        }
2041
2042
        // getSplicedRecordData() takes care of moving current position in data stream
2043
    }
2044
2045
    /**
2046
     * Read PRINTGRIDLINES record.
2047
     */
2048
    protected function readPrintGridlines(): void
2049
    {
2050
        $length = self::getUInt2d($this->data, $this->pos + 2);
2051
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2052
2053
        // move stream pointer to next record
2054
        $this->pos += 4 + $length;
2055
2056 114
        if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) {
2057
            // offset: 0; size: 2; 0 = do not print sheet grid lines; 1 = print sheet gridlines
2058 114
            $printGridlines = (bool) self::getUInt2d($recordData, 0);
2059 114
            $this->phpSheet->setPrintGridlines($printGridlines);
2060
        }
2061
    }
2062 114
2063
    /**
2064 114
     * Read DEFAULTROWHEIGHT record.
2065
     */
2066 114
    protected function readDefaultRowHeight(): void
2067
    {
2068 112
        $length = self::getUInt2d($this->data, $this->pos + 2);
2069 112
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2070
2071
        // move stream pointer to next record
2072
        $this->pos += 4 + $length;
2073 58
2074
        // offset: 0; size: 2; option flags
2075 112
        // offset: 2; size: 2; default height for unused rows, (twips 1/20 point)
2076 111
        $height = self::getUInt2d($recordData, 2);
2077
        $this->phpSheet->getDefaultRowDimension()->setRowHeight($height / 20);
2078
    }
2079
2080 112
    /**
2081 112
     * Read SHEETPR record.
2082
     */
2083 54
    protected function readSheetPr(): void
2084 112
    {
2085
        $length = self::getUInt2d($this->data, $this->pos + 2);
2086 112
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2087
2088
        // move stream pointer to next record
2089 4
        $this->pos += 4 + $length;
2090
2091 112
        // offset: 0; size: 2
2092
2093
        // bit: 6; mask: 0x0040; 0 = outline buttons above outline group
2094
        $isSummaryBelow = (0x0040 & self::getUInt2d($recordData, 0)) >> 6;
2095 112
        $this->phpSheet->setShowSummaryBelow((bool) $isSummaryBelow);
2096
2097 112
        // bit: 7; mask: 0x0080; 0 = outline buttons left of outline group
2098 112
        $isSummaryRight = (0x0080 & self::getUInt2d($recordData, 0)) >> 7;
2099
        $this->phpSheet->setShowSummaryRight((bool) $isSummaryRight);
2100
2101 112
        // bit: 8; mask: 0x100; 0 = scale printout in percent, 1 = fit printout to number of pages
2102 112
        // this corresponds to radio button setting in page setup dialog in Excel
2103
        $this->isFitToPages = (bool) ((0x0100 & self::getUInt2d($recordData, 0)) >> 8);
2104
    }
2105 112
2106
    /**
2107
     * Read HORIZONTALPAGEBREAKS record.
2108
     */
2109 112
    protected function readHorizontalPageBreaks(): void
2110 112
    {
2111
        $length = self::getUInt2d($this->data, $this->pos + 2);
2112
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2113 112
2114 112
        // move stream pointer to next record
2115
        $this->pos += 4 + $length;
2116
2117 112
        if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) {
2118 112
            // offset: 0; size: 2; number of the following row index structures
2119
            $nm = self::getUInt2d($recordData, 0);
2120 112
2121
            // offset: 2; size: 6 * $nm; list of $nm row index structures
2122 110
            for ($i = 0; $i < $nm; ++$i) {
2123 110
                $r = self::getUInt2d($recordData, 2 + 6 * $i);
2124 110
                $cf = self::getUInt2d($recordData, 2 + 6 * $i + 2);
2125 110
                //$cl = self::getUInt2d($recordData, 2 + 6 * $i + 4);
2126 2
2127
                // not sure why two column indexes are necessary?
2128 2
                $this->phpSheet->setBreak([$cf + 1, $r], Worksheet::BREAK_ROW);
2129 2
            }
2130
        }
2131 110
    }
2132
2133
    /**
2134
     * Read VERTICALPAGEBREAKS record.
2135 110
     */
2136 110
    protected function readVerticalPageBreaks(): void
2137
    {
2138
        $length = self::getUInt2d($this->data, $this->pos + 2);
2139 110
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2140
2141 110
        // move stream pointer to next record
2142 110
        $this->pos += 4 + $length;
2143
2144 110
        if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) {
2145 1
            // offset: 0; size: 2; number of the following column index structures
2146 1
            $nm = self::getUInt2d($recordData, 0);
2147
2148 1
            // offset: 2; size: 6 * $nm; list of $nm row index structures
2149
            for ($i = 0; $i < $nm; ++$i) {
2150
                $c = self::getUInt2d($recordData, 2 + 6 * $i);
2151
                $rf = self::getUInt2d($recordData, 2 + 6 * $i + 2);
2152
                //$rl = self::getUInt2d($recordData, 2 + 6 * $i + 4);
2153
2154
                // not sure why two row indexes are necessary?
2155 110
                $this->phpSheet->setBreak([$c + 1, ($rf > 0) ? $rf : 1], Worksheet::BREAK_COLUMN);
2156 110
            }
2157
        }
2158
    }
2159 110
2160 110
    /**
2161
     * Read HEADER record.
2162
     */
2163 110
    protected function readHeader(): void
2164 110
    {
2165
        $length = self::getUInt2d($this->data, $this->pos + 2);
2166
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2167 110
2168 110
        // move stream pointer to next record
2169
        $this->pos += 4 + $length;
2170
2171 110
        if (!$this->readDataOnly) {
2172
            // offset: 0; size: var
2173
            // realized that $recordData can be empty even when record exists
2174 110
            if ($recordData) {
2175
                if ($this->version == self::XLS_BIFF8) {
2176
                    $string = self::readUnicodeStringLong($recordData);
2177 110
                } else {
2178
                    $string = $this->readByteStringShort($recordData);
2179
                }
2180 110
2181
                $this->phpSheet->getHeaderFooter()->setOddHeader($string['value']);
2182 110
                $this->phpSheet->getHeaderFooter()->setEvenHeader($string['value']);
2183 110
            }
2184 110
        }
2185
    }
2186 1
2187
    /**
2188 1
     * Read FOOTER record.
2189 1
     */
2190
    protected function readFooter(): void
2191 1
    {
2192
        $length = self::getUInt2d($this->data, $this->pos + 2);
2193
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2194
2195
        // move stream pointer to next record
2196 110
        $this->pos += 4 + $length;
2197
2198
        if (!$this->readDataOnly) {
2199 110
            // offset: 0; size: var
2200
            // realized that $recordData can be empty even when record exists
2201
            if ($recordData) {
2202 110
                if ($this->version == self::XLS_BIFF8) {
2203
                    $string = self::readUnicodeStringLong($recordData);
2204
                } else {
2205 110
                    $string = $this->readByteStringShort($recordData);
2206 110
                }
2207
                $this->phpSheet->getHeaderFooter()->setOddFooter($string['value']);
2208
                $this->phpSheet->getHeaderFooter()->setEvenFooter($string['value']);
2209
            }
2210 110
        }
2211 110
    }
2212
2213
    /**
2214
     * Read HCENTER record.
2215 110
     */
2216
    protected function readHcenter(): void
2217
    {
2218 110
        $length = self::getUInt2d($this->data, $this->pos + 2);
2219
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2220
2221
        // move stream pointer to next record
2222
        $this->pos += 4 + $length;
2223 2
2224
        if (!$this->readDataOnly) {
2225
            // offset: 0; size: 2; 0 = print sheet left aligned, 1 = print sheet centered horizontally
2226 2
            $isHorizontalCentered = (bool) self::getUInt2d($recordData, 0);
2227
2228 2
            $this->phpSheet->getPageSetup()->setHorizontalCentered($isHorizontalCentered);
2229 2
        }
2230
    }
2231 2
2232 1
    /**
2233 1
     * Read VCENTER record.
2234
     */
2235 1
    protected function readVcenter(): void
2236
    {
2237
        $length = self::getUInt2d($this->data, $this->pos + 2);
2238
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2239
2240
        // move stream pointer to next record
2241
        $this->pos += 4 + $length;
2242
2243
        if (!$this->readDataOnly) {
2244
            // offset: 0; size: 2; 0 = print sheet aligned at top page border, 1 = print sheet vertically centered
2245
            $isVerticalCentered = (bool) self::getUInt2d($recordData, 0);
2246
2247 2
            $this->phpSheet->getPageSetup()->setVerticalCentered($isVerticalCentered);
2248
        }
2249
    }
2250 2
2251
    /**
2252
     * Read LEFTMARGIN record.
2253 2
     */
2254
    protected function readLeftMargin(): void
2255
    {
2256 2
        $length = self::getUInt2d($this->data, $this->pos + 2);
2257
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2258
2259 2
        // move stream pointer to next record
2260
        $this->pos += 4 + $length;
2261
2262 2
        if (!$this->readDataOnly) {
2263
            // offset: 0; size: 8
2264
            $this->phpSheet->getPageMargins()->setLeft(self::extractNumber($recordData));
2265 2
        }
2266
    }
2267
2268 2
    /**
2269
     * Read RIGHTMARGIN record.
2270
     */
2271 2
    protected function readRightMargin(): void
2272
    {
2273
        $length = self::getUInt2d($this->data, $this->pos + 2);
2274 2
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2275
2276
        // move stream pointer to next record
2277 2
        $this->pos += 4 + $length;
2278
2279
        if (!$this->readDataOnly) {
2280 2
            // offset: 0; size: 8
2281
            $this->phpSheet->getPageMargins()->setRight(self::extractNumber($recordData));
2282
        }
2283 2
    }
2284
2285
    /**
2286
     * Read TOPMARGIN record.
2287 112
     */
2288
    protected function readTopMargin(): void
2289 112
    {
2290 112
        $length = self::getUInt2d($this->data, $this->pos + 2);
2291 112
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2292
2293
        // move stream pointer to next record
2294
        $this->pos += 4 + $length;
2295 112
2296 112
        if (!$this->readDataOnly) {
2297
            // offset: 0; size: 8
2298
            $this->phpSheet->getPageMargins()->setTop(self::extractNumber($recordData));
2299
        }
2300 112
    }
2301
2302
    /**
2303
     * Read BOTTOMMARGIN record.
2304 49
     */
2305
    protected function readBottomMargin(): void
2306 49
    {
2307 49
        $length = self::getUInt2d($this->data, $this->pos + 2);
2308
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2309
2310 49
        // move stream pointer to next record
2311
        $this->pos += 4 + $length;
2312 49
2313
        if (!$this->readDataOnly) {
2314
            // offset: 0; size: 8
2315
            $this->phpSheet->getPageMargins()->setBottom(self::extractNumber($recordData));
2316
        }
2317
    }
2318
2319
    /**
2320
     * Read PAGESETUP record.
2321
     */
2322 47
    protected function readPageSetup(): void
2323
    {
2324
        $length = self::getUInt2d($this->data, $this->pos + 2);
2325
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2326
2327
        // move stream pointer to next record
2328
        $this->pos += 4 + $length;
2329
2330 47
        if (!$this->readDataOnly) {
2331 47
            // offset: 0; size: 2; paper size
2332
            $paperSize = self::getUInt2d($recordData, 0);
2333 47
2334
            // offset: 2; size: 2; scaling factor
2335
            $scale = self::getUInt2d($recordData, 2);
2336 47
2337
            // offset: 6; size: 2; fit worksheet width to this number of pages, 0 = use as many as needed
2338
            $fitToWidth = self::getUInt2d($recordData, 6);
2339 47
2340
            // offset: 8; size: 2; fit worksheet height to this number of pages, 0 = use as many as needed
2341
            $fitToHeight = self::getUInt2d($recordData, 8);
2342 47
2343 47
            // offset: 10; size: 2; option flags
2344 47
2345
            // bit: 0; mask: 0x0001; 0=down then over, 1=over then down
2346 47
            $isOverThenDown = (0x0001 & self::getUInt2d($recordData, 10));
2347 45
2348
            // bit: 1; mask: 0x0002; 0=landscape, 1=portrait
2349
            $isPortrait = (0x0002 & self::getUInt2d($recordData, 10)) >> 1;
2350 45
2351 5
            // bit: 2; mask: 0x0004; 1= paper size, scaling factor, paper orient. not init
2352 5
            // when this bit is set, do not use flags for those properties
2353 5
            $isNotInit = (0x0004 & self::getUInt2d($recordData, 10)) >> 2;
2354
2355
            if (!$isNotInit) {
2356
                $this->phpSheet->getPageSetup()->setPaperSize($paperSize);
2357 47
                $this->phpSheet->getPageSetup()->setPageOrder(((bool) $isOverThenDown) ? PageSetup::PAGEORDER_OVER_THEN_DOWN : PageSetup::PAGEORDER_DOWN_THEN_OVER);
2358 45
                $this->phpSheet->getPageSetup()->setOrientation(((bool) $isPortrait) ? PageSetup::ORIENTATION_PORTRAIT : PageSetup::ORIENTATION_LANDSCAPE);
2359 3
2360 3
                $this->phpSheet->getPageSetup()->setScale($scale, false);
2361
                $this->phpSheet->getPageSetup()->setFitToPage((bool) $this->isFitToPages);
2362 3
                $this->phpSheet->getPageSetup()->setFitToWidth($fitToWidth, false);
2363 3
                $this->phpSheet->getPageSetup()->setFitToHeight($fitToHeight, false);
2364
            }
2365
2366 3
            // offset: 16; size: 8; header margin (IEEE 754 floating-point value)
2367 3
            $marginHeader = self::extractNumber(substr($recordData, 16, 8));
2368 3
            $this->phpSheet->getPageMargins()->setHeader($marginHeader);
2369 3
2370
            // offset: 24; size: 8; footer margin (IEEE 754 floating-point value)
2371
            $marginFooter = self::extractNumber(substr($recordData, 24, 8));
2372
            $this->phpSheet->getPageMargins()->setFooter($marginFooter);
2373 3
        }
2374 45
    }
2375 45
2376 45
    /**
2377
     * PROTECT - Sheet protection (BIFF2 through BIFF8)
2378 45
     *   if this record is omitted, then it also means no sheet protection.
2379 45
     */
2380
    protected function readProtect(): void
2381
    {
2382 45
        $length = self::getUInt2d($this->data, $this->pos + 2);
2383 2
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2384 2
2385 2
        // move stream pointer to next record
2386
        $this->pos += 4 + $length;
2387
2388
        if ($this->readDataOnly) {
2389 45
            return;
2390 45
        }
2391 45
2392 45
        // offset: 0; size: 2;
2393
2394 45
        // bit 0, mask 0x01; 1 = sheet is protected
2395 45
        $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0;
2396
        $this->phpSheet->getProtection()->setSheet((bool) $bool);
2397
    }
2398 45
2399 3
    /**
2400 3
     * SCENPROTECT.
2401 3
     */
2402
    protected function readScenProtect(): void
2403
    {
2404
        $length = self::getUInt2d($this->data, $this->pos + 2);
2405 45
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2406 45
2407 45
        // move stream pointer to next record
2408 45
        $this->pos += 4 + $length;
2409
2410 45
        if ($this->readDataOnly) {
2411 45
            return;
2412
        }
2413
2414 45
        // offset: 0; size: 2;
2415 2
2416 2
        // bit: 0, mask 0x01; 1 = scenarios are protected
2417 2
        $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0;
2418
2419
        $this->phpSheet->getProtection()->setScenarios((bool) $bool);
2420
    }
2421 45
2422 45
    /**
2423 45
     * OBJECTPROTECT.
2424 45
     */
2425
    protected function readObjectProtect(): void
2426 45
    {
2427 45
        $length = self::getUInt2d($this->data, $this->pos + 2);
2428
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2429
2430 45
        // move stream pointer to next record
2431 2
        $this->pos += 4 + $length;
2432 2
2433 2
        if ($this->readDataOnly) {
2434
            return;
2435
        }
2436
2437 45
        // offset: 0; size: 2;
2438 45
2439
        // bit: 0, mask 0x01; 1 = objects are protected
2440
        $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0;
2441
2442
        $this->phpSheet->getProtection()->setObjects((bool) $bool);
2443
    }
2444
2445
    /**
2446
     * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8).
2447
     */
2448
    protected function readPassword(): void
2449
    {
2450
        $length = self::getUInt2d($this->data, $this->pos + 2);
2451
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2452
2453
        // move stream pointer to next record
2454 45
        $this->pos += 4 + $length;
2455 45
2456 45
        if (!$this->readDataOnly) {
2457
            // offset: 0; size: 2; 16-bit hash value of password
2458 45
            $password = strtoupper(dechex(self::getUInt2d($recordData, 0))); // the hashed password
2459 45
            $this->phpSheet->getProtection()->setPassword($password, true);
2460
        }
2461
    }
2462 45
2463 7
    /**
2464 7
     * Read DEFCOLWIDTH record.
2465 7
     */
2466
    protected function readDefColWidth(): void
2467
    {
2468
        $length = self::getUInt2d($this->data, $this->pos + 2);
2469 45
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2470
2471
        // move stream pointer to next record
2472 47
        $this->pos += 4 + $length;
2473
2474
        // offset: 0; size: 2; default column width
2475
        $width = self::getUInt2d($recordData, 0);
2476
        if ($width != 8) {
2477
            $this->phpSheet->getDefaultColumnDimension()->setWidth($width);
2478
        }
2479
    }
2480 114
2481
    /**
2482 114
     * Read COLINFO record.
2483 114
     */
2484
    protected function readColInfo(): void
2485
    {
2486 114
        $length = self::getUInt2d($this->data, $this->pos + 2);
2487
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2488 114
2489
        // move stream pointer to next record
2490 112
        $this->pos += 4 + $length;
2491
2492
        if (!$this->readDataOnly) {
2493
            // offset: 0; size: 2; index to first column in range
2494
            $firstColumnIndex = self::getUInt2d($recordData, 0);
2495
2496 112
            // offset: 2; size: 2; index to last column in range
2497
            $lastColumnIndex = self::getUInt2d($recordData, 2);
2498 112
2499
            // offset: 4; size: 2; width of the column in 1/256 of the width of the zero character
2500 112
            $width = self::getUInt2d($recordData, 4);
2501
2502
            // offset: 6; size: 2; index to XF record for default column formatting
2503 112
            $xfIndex = self::getUInt2d($recordData, 6);
2504
2505 112
            // offset: 8; size: 2; option flags
2506
            // bit: 0; mask: 0x0001; 1= columns are hidden
2507 53
            $isHidden = (0x0001 & self::getUInt2d($recordData, 8)) >> 0;
2508
2509
            // bit: 10-8; mask: 0x0700; outline level of the columns (0 = no outline)
2510
            $level = (0x0700 & self::getUInt2d($recordData, 8)) >> 8;
2511
2512
            // bit: 12; mask: 0x1000; 1 = collapsed
2513
            $isCollapsed = (bool) ((0x1000 & self::getUInt2d($recordData, 8)) >> 12);
2514
2515
            // offset: 10; size: 2; not used
2516
2517 74
            for ($i = $firstColumnIndex + 1; $i <= $lastColumnIndex + 1; ++$i) {
2518
                if ($lastColumnIndex == 255 || $lastColumnIndex == 256) {
2519 74
                    $this->phpSheet->getDefaultColumnDimension()->setWidth($width / 256);
2520 74
2521
                    break;
2522
                }
2523 74
                $this->phpSheet->getColumnDimensionByColumn($i)->setWidth($width / 256);
2524
                $this->phpSheet->getColumnDimensionByColumn($i)->setVisible(!$isHidden);
2525 74
                $this->phpSheet->getColumnDimensionByColumn($i)->setOutlineLevel($level);
2526
                $this->phpSheet->getColumnDimensionByColumn($i)->setCollapsed($isCollapsed);
2527 74
                if (isset($this->mapCellXfIndex[$xfIndex])) {
2528
                    $this->phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->mapCellXfIndex[$xfIndex]);
2529
                }
2530 74
            }
2531 74
        }
2532 74
    }
2533
2534
    /**
2535
     * ROW.
2536
     *
2537
     * This record contains the properties of a single row in a
2538
     * sheet. Rows and cells in a sheet are divided into blocks
2539
     * of 32 rows.
2540
     *
2541
     * --    "OpenOffice.org's Documentation of the Microsoft
2542
     *         Excel File Format"
2543
     */
2544
    protected function readRow(): void
2545
    {
2546
        $length = self::getUInt2d($this->data, $this->pos + 2);
2547
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2548
2549 123
        // move stream pointer to next record
2550
        $this->pos += 4 + $length;
2551 123
2552 123
        if (!$this->readDataOnly) {
2553
            // offset: 0; size: 2; index of this row
2554
            $r = self::getUInt2d($recordData, 0);
2555
2556 123
            // offset: 2; size: 2; index to column of the first cell which is described by a cell record
2557
2558
            // offset: 4; size: 2; index to column of the last cell which is described by a cell record, increased by 1
2559 123
2560
            // offset: 6; size: 2;
2561
2562 123
            // bit: 14-0; mask: 0x7FFF; height of the row, in twips = 1/20 of a point
2563 123
            $height = (0x7FFF & self::getUInt2d($recordData, 6)) >> 0;
2564 5
2565 1
            // bit: 15: mask: 0x8000; 0 = row has custom height; 1= row has default height
2566
            $useDefaultHeight = (0x8000 & self::getUInt2d($recordData, 6)) >> 15;
2567 123
2568
            if (!$useDefaultHeight) {
2569
                $this->phpSheet->getRowDimension($r + 1)->setRowHeight($height / 20);
2570 123
            }
2571
2572
            // offset: 8; size: 2; not used
2573 123
2574 123
            // offset: 10; size: 2; not used in BIFF5-BIFF8
2575 117
2576 117
            // offset: 12; size: 4; option flags and default row formatting
2577 6
2578 6
            // bit: 2-0: mask: 0x00000007; outline level of the row
2579 6
            $level = (0x00000007 & self::getInt4d($recordData, 12)) >> 0;
2580
            $this->phpSheet->getRowDimension($r + 1)->setOutlineLevel($level);
2581
2582 123
            // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed
2583 123
            $isCollapsed = (bool) ((0x00000010 & self::getInt4d($recordData, 12)) >> 4);
2584 123
            $this->phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed);
2585 123
2586 123
            // bit: 5; mask: 0x00000020; 1 = row is hidden
2587 123
            $isHidden = (0x00000020 & self::getInt4d($recordData, 12)) >> 5;
2588
            $this->phpSheet->getRowDimension($r + 1)->setVisible(!$isHidden);
2589
2590
            // bit: 7; mask: 0x00000080; 1 = row has explicit format
2591
            $hasExplicitFormat = (0x00000080 & self::getInt4d($recordData, 12)) >> 7;
2592
2593 87
            // bit: 27-16; mask: 0x0FFF0000; only applies when hasExplicitFormat = 1; index to XF record
2594
            $xfIndex = (0x0FFF0000 & self::getInt4d($recordData, 12)) >> 16;
2595 87
2596 87
            if ($hasExplicitFormat && isset($this->mapCellXfIndex[$xfIndex])) {
2597
                $this->phpSheet->getRowDimension($r + 1)->setXfIndex($this->mapCellXfIndex[$xfIndex]);
2598
            }
2599 87
        }
2600
    }
2601
2602 87
    /**
2603
     * Read RK record
2604
     * This record represents a cell that contains an RK value
2605 87
     * (encoded integer or floating-point value). If a
2606
     * floating-point value cannot be encoded to an RK value,
2607
     * a NUMBER record will be written. This record replaces the
2608
     * record INTEGER written in BIFF2.
2609
     *
2610
     * --    "OpenOffice.org's Documentation of the Microsoft
2611
     *         Excel File Format"
2612
     */
2613
    protected function readRk(): void
2614
    {
2615
        $length = self::getUInt2d($this->data, $this->pos + 2);
2616
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2617
2618
        // move stream pointer to next record
2619
        $this->pos += 4 + $length;
2620
2621
        // offset: 0; size: 2; index to row
2622
        $row = self::getUInt2d($recordData, 0);
2623
2624
        // offset: 2; size: 2; index to column
2625
        $column = self::getUInt2d($recordData, 2);
2626
        $columnString = Coordinate::stringFromColumnIndex($column + 1);
2627
2628
        // Read cell?
2629 87
        if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
2630
            // offset: 4; size: 2; index to XF record
2631
            $xfIndex = self::getUInt2d($recordData, 4);
2632
2633 87
            // offset: 6; size: 4; RK value
2634 87
            $rknum = self::getInt4d($recordData, 6);
2635 87
            $numValue = self::getIEEE754($rknum);
2636 1
2637
            $cell = $this->phpSheet->getCell($columnString . ($row + 1));
2638
            if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) {
2639 1
                // add style information
2640 1
                $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
2641 1
            }
2642
2643
            // add cell
2644
            $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC);
2645
        }
2646
    }
2647
2648
    /**
2649
     * Read LABELSST record
2650
     * This record represents a cell that contains a string. It
2651
     * replaces the LABEL record and RSTRING record used in
2652
     * BIFF2-BIFF5.
2653
     *
2654
     * --    "OpenOffice.org's Documentation of the Microsoft
2655 1
     *         Excel File Format"
2656
     */
2657 1
    protected function readLabelSst(): void
2658 1
    {
2659
        $length = self::getUInt2d($this->data, $this->pos + 2);
2660
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2661 1
2662
        // move stream pointer to next record
2663
        $this->pos += 4 + $length;
2664 1
2665
        // offset: 0; size: 2; index to row
2666
        $row = self::getUInt2d($recordData, 0);
2667
2668
        // offset: 2; size: 2; index to column
2669
        $column = self::getUInt2d($recordData, 2);
2670
        $columnString = Coordinate::stringFromColumnIndex($column + 1);
2671
2672
        $cell = null;
2673 1
        // Read cell?
2674
        if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
2675
            // offset: 4; size: 2; index to XF record
2676 1
            $xfIndex = self::getUInt2d($recordData, 4);
2677 1
2678
            // offset: 6; size: 4; index to SST record
2679 1
            $index = self::getInt4d($recordData, 6);
2680 1
2681 1
            // add cell
2682 1
            if (($fmtRuns = $this->sst[$index]['fmtRuns']) && !$this->readDataOnly) {
2683
                // then we should treat as rich text
2684
                $richText = new RichText();
2685
                $charPos = 0;
2686
                $sstCount = count($this->sst[$index]['fmtRuns']);
2687
                for ($i = 0; $i <= $sstCount; ++$i) {
2688
                    if (isset($fmtRuns[$i])) {
2689 88
                        $text = StringHelper::substring($this->sst[$index]['value'], $charPos, $fmtRuns[$i]['charPos'] - $charPos);
2690
                        $charPos = $fmtRuns[$i]['charPos'];
2691 88
                    } else {
2692 88
                        $text = StringHelper::substring($this->sst[$index]['value'], $charPos, StringHelper::countCharacters($this->sst[$index]['value']));
2693
                    }
2694
2695 88
                    if (StringHelper::countCharacters($text) > 0) {
2696
                        if ($i == 0) { // first text run, no style
2697
                            $richText->createText($text);
2698 88
                        } else {
2699
                            $textRun = $richText->createTextRun($text);
2700 87
                            if (isset($fmtRuns[$i - 1])) {
2701 87
                                if ($fmtRuns[$i - 1]['fontIndex'] < 4) {
2702 85
                                    $fontIndex = $fmtRuns[$i - 1]['fontIndex'];
2703
                                } else {
2704 85
                                    // this has to do with that index 4 is omitted in all BIFF versions for some stra          nge reason
2705
                                    // check the OpenOffice documentation of the FONT record
2706 85
                                    $fontIndex = $fmtRuns[$i - 1]['fontIndex'] - 1;
2707
                                }
2708 85
                                if (array_key_exists($fontIndex, $this->objFonts) === false) {
2709 85
                                    $fontIndex = count($this->objFonts) - 1;
2710
                                }
2711
                                $textRun->setFont(clone $this->objFonts[$fontIndex]);
2712
                            }
2713
                        }
2714
                    }
2715
                }
2716
                if ($this->readEmptyCells || trim($richText->getPlainText()) !== '') {
2717
                    $cell = $this->phpSheet->getCell($columnString . ($row + 1));
2718
                    $cell->setValueExplicit($richText, DataType::TYPE_STRING);
2719
                }
2720
            } else {
2721
                if ($this->readEmptyCells || trim($this->sst[$index]['value']) !== '') {
2722
                    $cell = $this->phpSheet->getCell($columnString . ($row + 1));
2723
                    $cell->setValueExplicit($this->sst[$index]['value'], DataType::TYPE_STRING);
2724
                }
2725 16
            }
2726
2727 16
            if (!$this->readDataOnly && $cell !== null && isset($this->mapCellXfIndex[$xfIndex])) {
2728 16
                // add style information
2729
                $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
2730
            }
2731 16
        }
2732
    }
2733 16
2734
    /**
2735
     * Read MULRK record
2736
     * This record represents a cell range containing RK value
2737 15
     * cells. All cells are located in the same row.
2738
     *
2739
     * --    "OpenOffice.org's Documentation of the Microsoft
2740 15
     *         Excel File Format"
2741
     */
2742
    protected function readMulRk(): void
2743
    {
2744
        $length = self::getUInt2d($this->data, $this->pos + 2);
2745 15
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2746
2747
        // move stream pointer to next record
2748
        $this->pos += 4 + $length;
2749 15
2750
        // offset: 0; size: 2; index to row
2751
        $row = self::getUInt2d($recordData, 0);
2752 15
2753
        // offset: 2; size: 2; index to first column
2754
        $colFirst = self::getUInt2d($recordData, 2);
2755 15
2756
        // offset: var; size: 2; index to last column
2757
        $colLast = self::getUInt2d($recordData, $length - 2);
2758 15
        $columns = $colLast - $colFirst + 1;
2759 15
2760
        // offset within record data
2761
        $offset = 4;
2762 15
2763 1
        for ($i = 1; $i <= $columns; ++$i) {
2764 1
            $columnString = Coordinate::stringFromColumnIndex($colFirst + $i);
2765 1
2766
            // Read cell?
2767
            if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
2768 15
                // offset: var; size: 2; index to XF record
2769 15
                $xfIndex = self::getUInt2d($recordData, $offset);
2770 15
2771 15
                // offset: var; size: 4; RK value
2772 15
                $numValue = self::getIEEE754(self::getInt4d($recordData, $offset + 2));
2773 15
                $cell = $this->phpSheet->getCell($columnString . ($row + 1));
2774
                if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) {
2775
                    // add style
2776
                    $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
2777
                }
2778
2779
                // add cell value
2780 18
                $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC);
2781
            }
2782
2783
            $offset += 6;
2784
        }
2785 18
    }
2786 18
2787
    /**
2788 18
     * Read NUMBER record
2789
     * This record represents a cell that contains a
2790
     * floating-point value.
2791
     *
2792
     * --    "OpenOffice.org's Documentation of the Microsoft
2793
     *         Excel File Format"
2794
     */
2795
    protected function readNumber(): void
2796
    {
2797
        $length = self::getUInt2d($this->data, $this->pos + 2);
2798
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2799
2800
        // move stream pointer to next record
2801
        $this->pos += 4 + $length;
2802 108
2803
        // offset: 0; size: 2; index to row
2804
        $row = self::getUInt2d($recordData, 0);
2805 108
2806
        // offset: 2; size 2; index to column
2807
        $column = self::getUInt2d($recordData, 2);
2808 108
        $columnString = Coordinate::stringFromColumnIndex($column + 1);
2809
2810
        // Read cell?
2811 108
        if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
2812
            // offset 4; size: 2; index to XF record
2813 108
            $xfIndex = self::getUInt2d($recordData, 4);
2814 108
2815
            $numValue = self::extractNumber(substr($recordData, 6, 8));
2816
2817 108
            $cell = $this->phpSheet->getCell($columnString . ($row + 1));
2818
            if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) {
2819
                // add cell style
2820 108
                $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
2821 108
            }
2822
2823
            // add cell value
2824 108
            $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC);
2825
        }
2826
    }
2827 108
2828 108
    /**
2829
     * Read FORMULA record + perhaps a following STRING record if formula result is a string
2830
     * This record contains the token array and the result of a
2831
     * formula cell.
2832
     *
2833 108
     * --    "OpenOffice.org's Documentation of the Microsoft
2834
     *         Excel File Format"
2835 63
     */
2836 63
    protected function readFormula(): void
2837
    {
2838
        $length = self::getUInt2d($this->data, $this->pos + 2);
2839 63
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2840 63
2841
        // move stream pointer to next record
2842
        $this->pos += 4 + $length;
2843 63
2844
        // offset: 0; size: 2; row index
2845
        $row = self::getUInt2d($recordData, 0);
2846 63
2847
        // offset: 2; size: 2; col index
2848
        $column = self::getUInt2d($recordData, 2);
2849 63
        $columnString = Coordinate::stringFromColumnIndex($column + 1);
2850
2851 63
        // offset: 20: size: variable; formula structure
2852 63
        $formulaStructure = substr($recordData, 20);
2853
2854 5
        // offset: 14: size: 2; option flags, recalculate always, recalculate on open etc.
2855 5
        $options = self::getUInt2d($recordData, 14);
2856
2857
        // bit: 0; mask: 0x0001; 1 = recalculate always
2858 63
        // bit: 1; mask: 0x0002; 1 = calculate on open
2859 63
        // bit: 2; mask: 0x0008; 1 = part of a shared formula
2860
        $isPartOfSharedFormula = (bool) (0x0008 & $options);
2861
2862
        // WARNING:
2863
        // We can apparently not rely on $isPartOfSharedFormula. Even when $isPartOfSharedFormula = true
2864
        // the formula data may be ordinary formula data, therefore we need to check
2865
        // explicitly for the tExp token (0x01)
2866 63
        $isPartOfSharedFormula = $isPartOfSharedFormula && ord($formulaStructure[2]) == 0x01;
2867
2868
        if ($isPartOfSharedFormula) {
2869 63
            // part of shared formula which means there will be a formula with a tExp token and nothing else
2870 63
            // get the base cell, grab tExp token
2871
            $baseRow = self::getUInt2d($formulaStructure, 3);
2872
            $baseCol = self::getUInt2d($formulaStructure, 5);
2873 63
            $this->baseCell = Coordinate::stringFromColumnIndex($baseCol + 1) . ($baseRow + 1);
2874 63
        }
2875
2876 63
        // Read cell?
2877
        if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
2878
            if ($isPartOfSharedFormula) {
2879
                // formula is added to this cell after the sheet has been read
2880 63
                $this->sharedFormulaParts[$columnString . ($row + 1)] = $this->baseCell;
2881
            }
2882
2883 63
            // offset: 16: size: 4; not used
2884 63
2885
            // offset: 4; size: 2; XF index
2886
            $xfIndex = self::getUInt2d($recordData, 4);
2887
2888
            // offset: 6; size: 8; result of the formula
2889 1
            if ((ord($recordData[6]) == 0) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255)) {
2890
                // String formula. Result follows in appended STRING record
2891 1
                $dataType = DataType::TYPE_STRING;
2892
2893
                // read possible SHAREDFMLA record
2894 1
                $code = self::getUInt2d($this->data, $this->pos);
2895
                if ($code == self::XLS_TYPE_SHAREDFMLA) {
2896 1
                    $this->readSharedFmla();
2897
                }
2898
2899 1
                // read STRING record
2900
                $value = $this->readString();
2901 1
            } elseif (
2902 1
                (ord($recordData[6]) == 1)
2903 1
                && (ord($recordData[12]) == 255)
2904
                && (ord($recordData[13]) == 255)
2905 1
            ) {
2906
                // Boolean formula. Result is in +2; 0=false, 1=true
2907
                $dataType = DataType::TYPE_BOOL;
2908
                $value = (bool) ord($recordData[8]);
2909
            } elseif (
2910
                (ord($recordData[6]) == 2)
2911 1
                && (ord($recordData[12]) == 255)
2912 1
                && (ord($recordData[13]) == 255)
2913
            ) {
2914 1
                // Error formula. Error code is in +2
2915
                $dataType = DataType::TYPE_ERROR;
2916
                $value = Xls\ErrorCode::lookup(ord($recordData[8]));
2917
            } elseif (
2918
                (ord($recordData[6]) == 3)
2919
                && (ord($recordData[12]) == 255)
2920
                && (ord($recordData[13]) == 255)
2921 1
            ) {
2922
                // Formula result is a null string
2923
                $dataType = DataType::TYPE_NULL;
2924 1
                $value = '';
2925 1
            } else {
2926 1
                // forumla result is a number, first 14 bytes like _NUMBER record
2927 1
                $dataType = DataType::TYPE_NUMERIC;
2928
                $value = self::extractNumber(substr($recordData, 6, 8));
2929
            }
2930
2931
            $cell = $this->phpSheet->getCell($columnString . ($row + 1));
2932
            if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) {
2933
                // add cell style
2934
                $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
2935
            }
2936
2937
            // store the formula
2938
            if (!$isPartOfSharedFormula) {
2939
                // not part of shared formula
2940
                // add cell value. If we can read formula, populate with formula, otherwise just used cached value
2941
                try {
2942
                    if ($this->version != self::XLS_BIFF8) {
2943
                        throw new Exception('Not BIFF8. Can only read BIFF8 formulas');
2944
                    }
2945
                    $formula = $this->getFormulaFromStructure($formulaStructure); // get formula in human language
2946
                    $cell->setValueExplicit('=' . $formula, DataType::TYPE_FORMULA);
2947
                } catch (PhpSpreadsheetException) {
2948
                    $cell->setValueExplicit($value, $dataType);
2949
                }
2950
            } else {
2951
                if ($this->version == self::XLS_BIFF8) {
2952
                    // do nothing at this point, formula id added later in the code
2953 1
                } else {
2954
                    $cell->setValueExplicit($value, $dataType);
2955
                }
2956
            }
2957
2958 63
            // store the cached calculated value
2959
            $cell->setCalculatedValue($value, $dataType === DataType::TYPE_NUMERIC);
2960
        }
2961 63
    }
2962 63
2963
    /**
2964 5
     * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader,
2965
     * which usually contains relative references.
2966 5
     * These will be used to construct the formula in each shared formula part after the sheet is read.
2967
     */
2968
    protected function readSharedFmla(): void
2969 5
    {
2970
        $length = self::getUInt2d($this->data, $this->pos + 2);
2971 5
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
2972 5
2973 5
        // move stream pointer to next record
2974 5
        $this->pos += 4 + $length;
2975
2976 5
        // offset: 0, size: 6; cell range address of the area used by the shared formula, not used for anything
2977
        //$cellRange = substr($recordData, 0, 6);
2978
        //$cellRange = Xls\Biff5::readBIFF5CellRangeAddressFixed($cellRange); // note: even BIFF8 uses BIFF5 syntax
2979
2980 63
        // offset: 6, size: 1; not used
2981
2982
        // offset: 7, size: 1; number of existing FORMULA records for this shared formula
2983
        //$no = ord($recordData[7]);
2984
2985
        // offset: 8, size: var; Binary token array of the shared formula
2986 63
        $formula = substr($recordData, 8);
2987 63
2988 63
        // at this point we only store the shared formula for later use
2989 63
        $this->sharedFormulas[$this->baseCell] = $formula;
2990
    }
2991
2992
    /**
2993
     * Read a STRING record from current stream position and advance the stream pointer to next record
2994
     * This record is used for storing result from FORMULA record when it is a string, and
2995
     * it occurs directly after the FORMULA record.
2996
     *
2997
     * @return string The string contents as UTF-8
2998 110
     */
2999
    protected function readString(): string
3000 110
    {
3001 110
        $length = self::getUInt2d($this->data, $this->pos + 2);
3002
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3003
3004 110
        // move stream pointer to next record
3005
        $this->pos += 4 + $length;
3006 110
3007
        if ($this->version == self::XLS_BIFF8) {
3008 106
            $string = self::readUnicodeStringLong($recordData);
3009 106
            $value = $string['value'];
3010
        } else {
3011
            $string = $this->readByteStringLong($recordData);
3012
            $value = $string['value'];
3013
        }
3014
3015
        return $value;
3016 61
    }
3017
3018 61
    /**
3019 61
     * Read BOOLERR record
3020
     * This record represents a Boolean value or error value
3021
     * cell.
3022 61
     *
3023
     * --    "OpenOffice.org's Documentation of the Microsoft
3024
     *         Excel File Format"
3025
     */
3026 61
    protected function readBoolErr(): void
3027 61
    {
3028
        $length = self::getUInt2d($this->data, $this->pos + 2);
3029
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3030
3031
        // move stream pointer to next record
3032
        $this->pos += 4 + $length;
3033 112
3034
        // offset: 0; size: 2; row index
3035 112
        $row = self::getUInt2d($recordData, 0);
3036 112
3037
        // offset: 2; size: 2; column index
3038
        $column = self::getUInt2d($recordData, 2);
3039 112
        $columnString = Coordinate::stringFromColumnIndex($column + 1);
3040
3041
        // Read cell?
3042
        if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
3043
            // offset: 4; size: 2; index to XF record
3044 112
            $xfIndex = self::getUInt2d($recordData, 4);
3045 112
3046
            // offset: 6; size: 1; the boolean value or error value
3047
            $boolErr = ord($recordData[6]);
3048 112
3049 112
            // offset: 7; size: 1; 0=boolean; 1=error
3050
            $isError = ord($recordData[7]);
3051
3052
            $cell = $this->phpSheet->getCell($columnString . ($row + 1));
3053 112
            switch ($isError) {
3054
                case 0: // boolean
3055
                    $value = (bool) $boolErr;
3056
3057
                    // add cell value
3058
                    $cell->setValueExplicit($value, DataType::TYPE_BOOL);
3059 5
3060
                    break;
3061 5
                case 1: // error type
3062 5
                    $value = Xls\ErrorCode::lookup($boolErr);
3063
3064
                    // add cell value
3065 5
                    $cell->setValueExplicit($value, DataType::TYPE_ERROR);
3066
3067 5
                    break;
3068
            }
3069 5
3070
            if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) {
3071
                // add cell style
3072 5
                $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
3073 3
            }
3074 3
        }
3075
    }
3076
3077
    /**
3078 3
     * Read MULBLANK record
3079
     * This record represents a cell range of empty cells. All
3080
     * cells are located in the same row.
3081
     *
3082
     * --    "OpenOffice.org's Documentation of the Microsoft
3083
     *         Excel File Format"
3084
     */
3085
    protected function readMulBlank(): void
3086 5
    {
3087
        $length = self::getUInt2d($this->data, $this->pos + 2);
3088 5
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3089 5
3090
        // move stream pointer to next record
3091
        $this->pos += 4 + $length;
3092 5
3093
        // offset: 0; size: 2; index to row
3094 5
        $row = self::getUInt2d($recordData, 0);
3095
3096 5
        // offset: 2; size: 2; index to first column
3097
        $fc = self::getUInt2d($recordData, 2);
3098
3099 5
        // offset: 4; size: 2 x nc; list of indexes to XF records
3100 3
        // add style information
3101 3
        if (!$this->readDataOnly && $this->readEmptyCells) {
3102
            for ($i = 0; $i < $length / 2 - 3; ++$i) {
3103
                $columnString = Coordinate::stringFromColumnIndex($fc + $i + 1);
3104
3105 3
                // Read cell?
3106
                if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
3107
                    $xfIndex = self::getUInt2d($recordData, 4 + 2 * $i);
3108
                    if (isset($this->mapCellXfIndex[$xfIndex])) {
3109
                        $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]);
3110
                    }
3111
                }
3112
            }
3113 110
        }
3114
3115 110
        // offset: 6; size 2; index to last column (not needed)
3116 110
    }
3117
3118
    /**
3119 110
     * Read LABEL record
3120
     * This record represents a cell that contains a string. In
3121 110
     * BIFF8 it is usually replaced by the LABELSST record.
3122
     * Excel still uses this record, if it copies unformatted
3123
     * text cells to the clipboard.
3124 108
     *
3125 65
     * --    "OpenOffice.org's Documentation of the Microsoft
3126 64
     *         Excel File Format"
3127
     */
3128 1
    protected function readLabel(): void
3129
    {
3130
        $length = self::getUInt2d($this->data, $this->pos + 2);
3131 65
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3132 65
3133
        // move stream pointer to next record
3134
        $this->pos += 4 + $length;
3135
3136
        // offset: 0; size: 2; index to row
3137
        $row = self::getUInt2d($recordData, 0);
3138
3139
        // offset: 2; size: 2; index to column
3140 110
        $column = self::getUInt2d($recordData, 2);
3141
        $columnString = Coordinate::stringFromColumnIndex($column + 1);
3142 110
3143 110
        // Read cell?
3144
        if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
3145
            // offset: 4; size: 2; XF index
3146 110
            $xfIndex = self::getUInt2d($recordData, 4);
3147
3148 110
            // add cell value
3149
            // todo: what if string is very long? continue record
3150
            if ($this->version == self::XLS_BIFF8) {
3151 108
                $string = self::readUnicodeStringLong(substr($recordData, 6));
3152 67
                $value = $string['value'];
3153 65
            } else {
3154
                $string = $this->readByteStringLong(substr($recordData, 6));
3155 2
                $value = $string['value'];
3156
            }
3157 67
            if ($this->readEmptyCells || trim($value) !== '') {
3158 67
                $cell = $this->phpSheet->getCell($columnString . ($row + 1));
3159
                $cell->setValueExplicit($value, DataType::TYPE_STRING);
3160
3161
                if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) {
3162
                    // add cell style
3163
                    $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
3164
                }
3165
            }
3166 110
        }
3167
    }
3168 110
3169 110
    /**
3170
     * Read BLANK record.
3171
     */
3172 110
    protected function readBlank(): void
3173
    {
3174 110
        $length = self::getUInt2d($this->data, $this->pos + 2);
3175
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3176 108
3177
        // move stream pointer to next record
3178 108
        $this->pos += 4 + $length;
3179
3180
        // offset: 0; size: 2; row index
3181
        $row = self::getUInt2d($recordData, 0);
3182
3183
        // offset: 2; size: 2; col index
3184
        $col = self::getUInt2d($recordData, 2);
3185 110
        $columnString = Coordinate::stringFromColumnIndex($col + 1);
3186
3187 110
        // Read cell?
3188 110
        if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
3189
            // offset: 4; size: 2; XF index
3190
            $xfIndex = self::getUInt2d($recordData, 4);
3191 110
3192
            // add style information
3193 110
            if (!$this->readDataOnly && $this->readEmptyCells && isset($this->mapCellXfIndex[$xfIndex])) {
3194
                $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]);
3195 108
            }
3196
        }
3197 108
    }
3198
3199
    /**
3200
     * Read MSODRAWING record.
3201
     */
3202
    protected function readMsoDrawing(): void
3203
    {
3204 105
        //$length = self::getUInt2d($this->data, $this->pos + 2);
3205
3206 105
        // get spliced record data
3207 105
        $splicedRecordData = $this->getSplicedRecordData();
3208
        $recordData = $splicedRecordData['recordData'];
3209
3210 105
        $this->drawingData .= $recordData;
3211
    }
3212 105
3213
    /**
3214 103
     * Read OBJ record.
3215
     */
3216
    protected function readObj(): void
3217
    {
3218
        $length = self::getUInt2d($this->data, $this->pos + 2);
3219
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3220
3221 105
        // move stream pointer to next record
3222
        $this->pos += 4 + $length;
3223 105
3224 105
        if ($this->readDataOnly || $this->version != self::XLS_BIFF8) {
3225
            return;
3226
        }
3227 105
3228
        // recordData consists of an array of subrecords looking like this:
3229 105
        //    ft: 2 bytes; ftCmo type (0x15)
3230
        //    cb: 2 bytes; size in bytes of ftCmo data
3231 103
        //    ot: 2 bytes; Object Type
3232
        //    id: 2 bytes; Object id number
3233
        //    grbit: 2 bytes; Option Flags
3234
        //    data: var; subrecord data
3235
3236
        // for now, we are just interested in the second subrecord containing the object type
3237
        $ftCmoType = self::getUInt2d($recordData, 0);
3238 105
        $cbCmoSize = self::getUInt2d($recordData, 2);
3239
        $otObjType = self::getUInt2d($recordData, 4);
3240 105
        $idObjID = self::getUInt2d($recordData, 6);
3241 105
        $grbitOpts = self::getUInt2d($recordData, 6);
3242
3243
        $this->objs[] = [
3244 105
            'ftCmoType' => $ftCmoType,
3245
            'cbCmoSize' => $cbCmoSize,
3246 105
            'otObjType' => $otObjType,
3247
            'idObjID' => $idObjID,
3248 103
            'grbitOpts' => $grbitOpts,
3249
        ];
3250
        $this->textObjRef = $idObjID;
3251
    }
3252
3253
    /**
3254
     * Read WINDOW2 record.
3255 105
     */
3256
    protected function readWindow2(): void
3257 105
    {
3258 105
        $length = self::getUInt2d($this->data, $this->pos + 2);
3259
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3260
3261 105
        // move stream pointer to next record
3262
        $this->pos += 4 + $length;
3263 105
3264
        // offset: 0; size: 2; option flags
3265 103
        $options = self::getUInt2d($recordData, 0);
3266
3267
        // offset: 2; size: 2; index to first visible row
3268
        //$firstVisibleRow = self::getUInt2d($recordData, 2);
3269
3270
        // offset: 4; size: 2; index to first visible colum
3271
        //$firstVisibleColumn = self::getUInt2d($recordData, 4);
3272 112
        $zoomscaleInPageBreakPreview = 0;
3273
        $zoomscaleInNormalView = 0;
3274 112
        if ($this->version === self::XLS_BIFF8) {
3275 112
            // offset:  8; size: 2; not used
3276
            // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%)
3277
            // offset: 12; size: 2; cached magnification factor in normal view (in percent); 0 = Default (100%)
3278 112
            // offset: 14; size: 4; not used
3279
            if (!isset($recordData[10])) {
3280 112
                $zoomscaleInPageBreakPreview = 0;
3281
            } else {
3282 110
                $zoomscaleInPageBreakPreview = self::getUInt2d($recordData, 10);
3283
            }
3284
3285 110
            if ($zoomscaleInPageBreakPreview === 0) {
3286
                $zoomscaleInPageBreakPreview = 60;
3287
            }
3288 110
3289
            if (!isset($recordData[12])) {
3290
                $zoomscaleInNormalView = 0;
3291 110
            } else {
3292
                $zoomscaleInNormalView = self::getUInt2d($recordData, 12);
3293
            }
3294
3295
            if ($zoomscaleInNormalView === 0) {
3296 110
                $zoomscaleInNormalView = 100;
3297
            }
3298
        }
3299 110
3300
        // bit: 1; mask: 0x0002; 0 = do not show gridlines, 1 = show gridlines
3301
        $showGridlines = (bool) ((0x0002 & $options) >> 1);
3302
        $this->phpSheet->setShowGridlines($showGridlines);
3303 110
3304
        // bit: 2; mask: 0x0004; 0 = do not show headers, 1 = show headers
3305 110
        $showRowColHeaders = (bool) ((0x0004 & $options) >> 2);
3306 102
        $this->phpSheet->setShowRowColHeaders($showRowColHeaders);
3307 102
3308 102
        // bit: 3; mask: 0x0008; 0 = panes are not frozen, 1 = panes are frozen
3309
        $this->frozen = (bool) ((0x0008 & $options) >> 3);
3310 102
3311 102
        // bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left
3312 102
        $this->phpSheet->setRightToLeft((bool) ((0x0040 & $options) >> 6));
3313 102
3314
        // bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active
3315
        $isActive = (bool) ((0x0400 & $options) >> 10);
3316
        if ($isActive) {
3317 110
            $this->spreadsheet->setActiveSheetIndex($this->spreadsheet->getIndex($this->phpSheet));
3318 110
            $this->activeSheetSet = true;
3319
        }
3320
3321 110
        // bit: 11; mask: 0x0800; 0 = normal view, 1 = page break view
3322 110
        $isPageBreakPreview = (bool) ((0x0800 & $options) >> 11);
3323
3324
        //FIXME: set $firstVisibleRow and $firstVisibleColumn
3325
3326
        if ($this->phpSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_PAGE_LAYOUT) {
3327
            //NOTE: this setting is inferior to page layout view(Excel2007-)
3328
            $view = $isPageBreakPreview ? SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW : SheetView::SHEETVIEW_NORMAL;
3329
            $this->phpSheet->getSheetView()->setView($view);
3330 7
            if ($this->version === self::XLS_BIFF8) {
3331
                $zoomScale = $isPageBreakPreview ? $zoomscaleInPageBreakPreview : $zoomscaleInNormalView;
3332 7
                $this->phpSheet->getSheetView()->setZoomScale($zoomScale);
3333 7
                $this->phpSheet->getSheetView()->setZoomScaleNormal($zoomscaleInNormalView);
3334
            }
3335
        }
3336 7
    }
3337
3338 7
    /**
3339
     * Read PLV Record(Created by Excel2007 or upper).
3340
     */
3341
    protected function readPageLayoutView(): void
3342
    {
3343
        $length = self::getUInt2d($this->data, $this->pos + 2);
3344
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3345 7
3346 7
        // move stream pointer to next record
3347
        $this->pos += 4 + $length;
3348
3349
        // offset: 0; size: 2; rt
3350
        //->ignore
3351
        //$rt = self::getUInt2d($recordData, 0);
3352
        // offset: 2; size: 2; grbitfr
3353
        //->ignore
3354
        //$grbitFrt = self::getUInt2d($recordData, 2);
3355
        // offset: 4; size: 8; reserved
3356
        //->ignore
3357
3358
        // offset: 12; size 2; zoom scale
3359
        $wScalePLV = self::getUInt2d($recordData, 12);
3360
        // offset: 14; size 2; grbit
3361
        $grbit = self::getUInt2d($recordData, 14);
3362
3363
        // decomprise grbit
3364
        $fPageLayoutView = $grbit & 0x01;
3365
        //$fRulerVisible = ($grbit >> 1) & 0x01; //no support
3366
        //$fWhitespaceHidden = ($grbit >> 3) & 0x01; //no support
3367
3368
        if ($fPageLayoutView === 1) {
3369
            $this->phpSheet->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_LAYOUT);
3370
            $this->phpSheet->getSheetView()->setZoomScale($wScalePLV); //set by Excel2007 only if SHEETVIEW_PAGE_LAYOUT
3371
        }
3372
        //otherwise, we cannot know whether SHEETVIEW_PAGE_LAYOUT or SHEETVIEW_PAGE_BREAK_PREVIEW.
3373
    }
3374
3375 2
    /**
3376
     * Read SCL record.
3377 2
     */
3378 2
    protected function readScl(): void
3379
    {
3380
        $length = self::getUInt2d($this->data, $this->pos + 2);
3381 2
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3382
3383 2
        // move stream pointer to next record
3384
        $this->pos += 4 + $length;
3385
3386
        // offset: 0; size: 2; numerator of the view magnification
3387
        $numerator = self::getUInt2d($recordData, 0);
3388
3389
        // offset: 2; size: 2; numerator of the view magnification
3390 2
        $denumerator = self::getUInt2d($recordData, 2);
3391
3392 2
        // set the zoom scale (in percent)
3393
        $this->phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator);
3394
    }
3395
3396
    /**
3397
     * Read PANE record.
3398 3
     */
3399
    protected function readPane(): void
3400 3
    {
3401 3
        $length = self::getUInt2d($this->data, $this->pos + 2);
3402
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3403
3404 3
        // move stream pointer to next record
3405
        $this->pos += 4 + $length;
3406 3
3407
        if (!$this->readDataOnly) {
3408 3
            // offset: 0; size: 2; position of vertical split
3409 3
            $px = self::getUInt2d($recordData, 0);
3410
3411
            // offset: 2; size: 2; position of horizontal split
3412
            $py = self::getUInt2d($recordData, 2);
3413
3414
            // offset: 4; size: 2; top most visible row in the bottom pane
3415
            $rwTop = self::getUInt2d($recordData, 4);
3416 111
3417
            // offset: 6; size: 2; first visible left column in the right pane
3418 111
            $colLeft = self::getUInt2d($recordData, 6);
3419 111
3420
            if ($this->frozen) {
3421
                // frozen panes
3422 111
                $cell = Coordinate::stringFromColumnIndex($px + 1) . ($py + 1);
3423
                $topLeftCell = Coordinate::stringFromColumnIndex($colLeft + 1) . ($rwTop + 1);
3424
                $this->phpSheet->freezePane($cell, $topLeftCell);
3425 111
            }
3426 111
            // unfrozen panes; split windows; not supported by PhpSpreadsheet core
3427 5
        }
3428
    }
3429
3430
    /**
3431
     * Read SELECTION record. There is one such record for each pane in the sheet.
3432
     */
3433
    protected function readSelection(): string
3434 101
    {
3435
        $length = self::getUInt2d($this->data, $this->pos + 2);
3436 101
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3437 101
        $selectedCells = '';
3438
3439
        // move stream pointer to next record
3440 101
        $this->pos += 4 + $length;
3441
3442 101
        if (!$this->readDataOnly) {
3443
            // offset: 0; size: 1; pane identifier
3444 99
            //$paneId = ord($recordData[0]);
3445
3446
            // offset: 1; size: 2; index to row of the active cell
3447 99
            //$r = self::getUInt2d($recordData, 1);
3448
3449
            // offset: 3; size: 2; index to column of the active cell
3450 99
            //$c = self::getUInt2d($recordData, 3);
3451
3452
            // offset: 5; size: 2; index into the following cell range list to the
3453 99
            //  entry that contains the active cell
3454
            //$index = self::getUInt2d($recordData, 5);
3455
3456
            // offset: 7; size: var; cell range address list containing all selected cell ranges
3457 99
            $data = substr($recordData, 7);
3458
            $cellRangeAddressList = Xls\Biff5::readBIFF5CellRangeAddressList($data); // note: also BIFF8 uses BIFF5 syntax
3459
3460 99
            $selectedCells = $cellRangeAddressList['cellRangeAddresses'][0];
3461
3462
            // first row '1' + last row '16384' indicates that full column is selected (apparently also in BIFF8!)
3463 99
            if (preg_match('/^([A-Z]+1\:[A-Z]+)16384$/', $selectedCells)) {
3464
                $selectedCells = (string) preg_replace('/^([A-Z]+1\:[A-Z]+)16384$/', '${1}1048576', $selectedCells);
3465
            }
3466
3467 99
            // first row '1' + last row '65536' indicates that full column is selected
3468 99
            if (preg_match('/^([A-Z]+1\:[A-Z]+)65536$/', $selectedCells)) {
3469 13
                $selectedCells = (string) preg_replace('/^([A-Z]+1\:[A-Z]+)65536$/', '${1}1048576', $selectedCells);
3470
            }
3471 13
3472
            // first column 'A' + last column 'IV' indicates that full row is selected
3473 91
            if (preg_match('/^(A\d+\:)IV(\d+)$/', $selectedCells)) {
3474 91
                $selectedCells = (string) preg_replace('/^(A\d+\:)IV(\d+)$/', '${1}XFD${2}', $selectedCells);
3475 91
            }
3476 91
3477 91
            $this->phpSheet->setSelectedCells($selectedCells);
3478 89
        }
3479
3480
        return $selectedCells;
3481
    }
3482
3483
    private function includeCellRangeFiltered(string $cellRangeAddress): bool
3484
    {
3485
        $includeCellRange = true;
3486
        if ($this->getReadFilter() !== null) {
3487
            $includeCellRange = false;
3488
            $rangeBoundaries = Coordinate::getRangeBoundaries($cellRangeAddress);
3489
            ++$rangeBoundaries[1][0];
3490
            for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; ++$row) {
3491
                for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; ++$column) {
3492
                    if ($this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) {
3493
                        $includeCellRange = true;
3494 69
3495
                        break 2;
3496 69
                    }
3497 69
                }
3498
            }
3499
        }
3500 69
3501
        return $includeCellRange;
3502 69
    }
3503
3504 67
    /**
3505
     * MERGEDCELLS.
3506
     *
3507
     * This record contains the addresses of merged cell ranges
3508
     * in the current sheet.
3509
     *
3510
     * --    "OpenOffice.org's Documentation of the Microsoft
3511
     *         Excel File Format"
3512
     */
3513 67
    protected function readMergedCells(): void
3514
    {
3515
        $length = self::getUInt2d($this->data, $this->pos + 2);
3516 67
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3517
3518 67
        // move stream pointer to next record
3519 65
        $this->pos += 4 + $length;
3520
3521
        if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) {
3522
            $cellRangeAddressList = Xls\Biff8::readBIFF8CellRangeAddressList($recordData);
3523
            foreach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) {
3524
                if (
3525
                    (str_contains($cellRangeAddress, ':'))
3526
                    && ($this->includeCellRangeFiltered($cellRangeAddress))
3527
                ) {
3528
                    $this->phpSheet->mergeCells($cellRangeAddress, Worksheet::MERGE_CELL_CONTENT_HIDE);
3529 67
                }
3530 67
            }
3531
        }
3532
    }
3533 67
3534 67
    /**
3535
     * Read HYPERLINK record.
3536
     */
3537 67
    protected function readHyperLink(): void
3538 67
    {
3539
        $length = self::getUInt2d($this->data, $this->pos + 2);
3540
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3541 67
3542
        // move stream pointer forward to next record
3543
        $this->pos += 4 + $length;
3544 67
3545
        if (!$this->readDataOnly) {
3546 67
            // offset: 0; size: 8; cell range address of all cells containing this hyperlink
3547 6
            try {
3548
                $cellRange = Xls\Biff8::readBIFF8CellRangeAddressFixed($recordData);
3549
            } catch (PhpSpreadsheetException) {
3550
                return;
3551
            }
3552
3553
            // offset: 8, size: 16; GUID of StdLink
3554
3555
            // offset: 24, size: 4; unknown value
3556
3557
            // offset: 28, size: 4; option flags
3558
            // bit: 0; mask: 0x00000001; 0 = no link or extant, 1 = file link or URL
3559
            $isFileLinkOrUrl = (0x00000001 & self::getUInt2d($recordData, 28)) >> 0;
3560
3561
            // bit: 1; mask: 0x00000002; 0 = relative path, 1 = absolute path or URL
3562
            //$isAbsPathOrUrl = (0x00000001 & self::getUInt2d($recordData, 28)) >> 1;
3563 35
3564
            // bit: 2 (and 4); mask: 0x00000014; 0 = no description
3565 35
            $hasDesc = (0x00000014 & self::getUInt2d($recordData, 28)) >> 2;
3566 35
3567
            // bit: 3; mask: 0x00000008; 0 = no text, 1 = has text
3568
            $hasText = (0x00000008 & self::getUInt2d($recordData, 28)) >> 3;
3569 35
3570
            // bit: 7; mask: 0x00000080; 0 = no target frame, 1 = has target frame
3571
            $hasFrame = (0x00000080 & self::getUInt2d($recordData, 28)) >> 7;
3572 35
3573
            // bit: 8; mask: 0x00000100; 0 = file link or URL, 1 = UNC path (inc. server name)
3574
            $isUNC = (0x00000100 & self::getUInt2d($recordData, 28)) >> 8;
3575 35
3576 35
            // offset within record data
3577
            $offset = 32;
3578
3579 35
            if ($hasDesc) {
3580
                // offset: 32; size: var; character count of description text
3581 35
                $dl = self::getInt4d($recordData, 32);
3582
                // offset: 36; size: var; character array of description text, no Unicode string header, always 16-bit characters, zero terminated
3583
                //$desc = self::encodeUTF16(substr($recordData, 36, 2 * ($dl - 1)), false);
3584 35
                $offset += 4 + 2 * $dl;
3585 35
            }
3586
            if ($hasFrame) {
3587 35
                $fl = self::getInt4d($recordData, $offset);
3588 35
                $offset += 4 + 2 * $fl;
3589
            }
3590 31
3591
            // detect type of hyperlink (there are 4 types)
3592
            $hyperlinkType = null;
3593
3594 35
            if ($isUNC) {
3595
                $hyperlinkType = 'UNC';
3596
            } elseif (!$isFileLinkOrUrl) {
3597
                $hyperlinkType = 'workbook';
3598
            } elseif (ord($recordData[$offset]) == 0x03) {
3599
                $hyperlinkType = 'local';
3600
            } elseif (ord($recordData[$offset]) == 0xE0) {
3601
                $hyperlinkType = 'URL';
3602
            }
3603
3604
            switch ($hyperlinkType) {
3605
                case 'URL':
3606
                    // section 5.58.2: Hyperlink containing a URL
3607 62
                    // e.g. http://example.org/index.php
3608
3609 62
                    // offset: var; size: 16; GUID of URL Moniker
3610 62
                    $offset += 16;
3611
                    // offset: var; size: 4; size (in bytes) of character array of the URL including trailing zero word
3612
                    $us = self::getInt4d($recordData, $offset);
3613 62
                    $offset += 4;
3614
                    // offset: var; size: $us; character array of the URL, no Unicode string header, always 16-bit characters, zero-terminated
3615
                    $url = self::encodeUTF16(substr($recordData, $offset, $us - 2), false);
3616 62
                    $nullOffset = strpos($url, chr(0x00));
3617
                    if ($nullOffset) {
3618
                        $url = substr($url, 0, $nullOffset);
3619 62
                    }
3620 62
                    $url .= $hasText ? '#' : '';
3621
                    $offset += $us;
3622 62
3623
                    break;
3624 62
                case 'local':
3625
                    // section 5.58.3: Hyperlink to local file
3626 62
                    // examples:
3627
                    //   mydoc.txt
3628
                    //   ../../somedoc.xls#Sheet!A1
3629 62
3630
                    // offset: var; size: 16; GUI of File Moniker
3631
                    $offset += 16;
3632 62
3633
                    // offset: var; size: 2; directory up-level count.
3634 5
                    $upLevelCount = self::getUInt2d($recordData, $offset);
3635 5
                    $offset += 2;
3636 5
3637 5
                    // offset: var; size: 4; character count of the shortened file path and name, including trailing zero word
3638 5
                    $sl = self::getInt4d($recordData, $offset);
3639 5
                    $offset += 4;
3640 5
3641
                    // offset: var; size: sl; character array of the shortened file path and name in 8.3-DOS-format (compressed Unicode string)
3642 5
                    $shortenedFilePath = substr($recordData, $offset, $sl);
3643
                    $shortenedFilePath = self::encodeUTF16($shortenedFilePath, true);
3644
                    $shortenedFilePath = substr($shortenedFilePath, 0, -1); // remove trailing zero
3645 5
3646 5
                    $offset += $sl;
3647 3
3648
                    // offset: var; size: 24; unknown sequence
3649 5
                    $offset += 24;
3650 5
3651 5
                    // extended file path
3652 4
                    // offset: var; size: 4; size of the following file link field including string lenth mark
3653
                    $sz = self::getInt4d($recordData, $offset);
3654
                    $offset += 4;
3655
3656 4
                    $extendedFilePath = '';
3657
                    // only present if $sz > 0
3658 5
                    if ($sz > 0) {
3659 1
                        // offset: var; size: 4; size of the character array of the extended file path and name
3660
                        $xl = self::getInt4d($recordData, $offset);
3661 5
                        $offset += 4;
3662
3663
                        // offset: var; size 2; unknown
3664
                        $offset += 2;
3665
3666 5
                        // offset: var; size $xl; character array of the extended file path and name.
3667 5
                        $extendedFilePath = substr($recordData, $offset, $xl);
3668 5
                        $extendedFilePath = self::encodeUTF16($extendedFilePath, false);
3669
                        $offset += $xl;
3670
                    }
3671 62
3672 62
                    // construct the path
3673 62
                    $url = str_repeat('..\\', $upLevelCount);
3674
                    $url .= ($sz > 0) ? $extendedFilePath : $shortenedFilePath; // use extended path if available
3675
                    $url .= $hasText ? '#' : '';
3676
3677 62
                    break;
3678
                case 'UNC':
3679 60
                    // section 5.58.4: Hyperlink to a File with UNC (Universal Naming Convention) Path
3680
                    // todo: implement
3681
                    return;
3682
                case 'workbook':
3683
                    // section 5.58.5: Hyperlink to the Current Workbook
3684
                    // e.g. Sheet2!B1:C2, stored in text mark field
3685
                    $url = 'sheet://';
3686
3687
                    break;
3688
                default:
3689
                    return;
3690
            }
3691
3692 22
            if ($hasText) {
3693
                // offset: var; size: 4; character count of text mark including trailing zero word
3694 22
                $tl = self::getInt4d($recordData, $offset);
3695 22
                $offset += 4;
3696
                // offset: var; size: var; character array of the text mark without the # sign, no Unicode header, always 16-bit characters, zero-terminated
3697
                $text = self::encodeUTF16(substr($recordData, $offset, 2 * ($tl - 1)), false);
3698 22
                $url .= $text;
3699
            }
3700
3701 22
            // apply the hyperlink to all the relevant cells
3702
            foreach (Coordinate::extractAllCellReferencesInRange($cellRange) as $coordinate) {
3703
                $this->phpSheet->getCell($coordinate)->getHyperLink()->setUrl($url);
3704 22
            }
3705
        }
3706
    }
3707 22
3708 22
    /**
3709
     * Read DATAVALIDATIONS record.
3710
     */
3711 22
    protected function readDataValidations(): void
3712
    {
3713 22
        $length = self::getUInt2d($this->data, $this->pos + 2);
3714 22
        //$recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3715
3716
        // move stream pointer forward to next record
3717 22
        $this->pos += 4 + $length;
3718
    }
3719 22
3720
    /**
3721
     * Read DATAVALIDATION record.
3722 22
     */
3723 22
    protected function readDataValidation(): void
3724 22
    {
3725
        (new Xls\DataValidationHelper())->readDataValidation2($this);
3726 20
    }
3727
3728
    /**
3729
     * Read SHEETLAYOUT record. Stores sheet tab color information.
3730 22
     */
3731
    protected function readSheetLayout(): void
3732
    {
3733 22
        $length = self::getUInt2d($this->data, $this->pos + 2);
3734
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3735
3736
        // move stream pointer to next record
3737
        $this->pos += 4 + $length;
3738
3739
        if (!$this->readDataOnly) {
3740
            // offset: 0; size: 2; repeated record identifier 0x0862
3741
3742
            // offset: 2; size: 10; not used
3743
3744
            // offset: 12; size: 4; size of record data
3745 55
            // Excel 2003 uses size of 0x14 (documented), Excel 2007 uses size of 0x28 (not documented?)
3746
            $sz = self::getInt4d($recordData, 12);
3747 55
3748 55
            switch ($sz) {
3749
                case 0x14:
3750
                    // offset: 16; size: 2; color index for sheet tab
3751 55
                    $colorIndex = self::getUInt2d($recordData, 16);
3752
                    $color = Xls\Color::map($colorIndex, $this->palette, $this->version);
3753
                    $this->phpSheet->getTabColor()->setRGB($color['rgb']);
3754 55
3755
                    break;
3756
                case 0x28:
3757 55
                    // TODO: Investigate structure for .xls SHEETLAYOUT record as saved by MS Office Excel 2007
3758 55
                    return;
3759
            }
3760
        }
3761 55
    }
3762
3763 55
    /**
3764
     * Read SHEETPROTECTION record (FEATHEADR).
3765 55
     */
3766
    protected function readSheetProtection(): void
3767 55
    {
3768 55
        $length = self::getUInt2d($this->data, $this->pos + 2);
3769
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3770 53
3771
        // move stream pointer to next record
3772
        $this->pos += 4 + $length;
3773
3774 55
        if ($this->readDataOnly) {
3775
            return;
3776
        }
3777
3778
        // offset: 0; size: 2; repeated record header
3779
3780
        // offset: 2; size: 2; FRT cell reference flag (=0 currently)
3781
3782
        // offset: 4; size: 8; Currently not used and set to 0
3783
3784
        // offset: 12; size: 2; Shared feature type index (2=Enhanced Protetion, 4=SmartTag)
3785
        $isf = self::getUInt2d($recordData, 12);
3786 37
        if ($isf != 2) {
3787
            return;
3788 37
        }
3789 37
3790
        // offset: 14; size: 1; =1 since this is a feat header
3791
3792 37
        // offset: 15; size: 4; size of rgbHdrSData
3793
3794
        // rgbHdrSData, assume "Enhanced Protection"
3795 37
        // offset: 19; size: 2; option flags
3796
        $options = self::getUInt2d($recordData, 19);
3797
3798 37
        // bit: 0; mask 0x0001; 1 = user may edit objects, 0 = users must not edit objects
3799 37
        // Note - do not negate $bool
3800
        $bool = (0x0001 & $options) >> 0;
3801
        $this->phpSheet->getProtection()->setObjects((bool) $bool);
3802 37
3803
        // bit: 1; mask 0x0002; edit scenarios
3804
        // Note - do not negate $bool
3805 37
        $bool = (0x0002 & $options) >> 1;
3806
        $this->phpSheet->getProtection()->setScenarios((bool) $bool);
3807
3808
        // bit: 2; mask 0x0004; format cells
3809
        $bool = (0x0004 & $options) >> 2;
3810 37
        $this->phpSheet->getProtection()->setFormatCells(!$bool);
3811
3812
        // bit: 3; mask 0x0008; format columns
3813
        $bool = (0x0008 & $options) >> 3;
3814
        $this->phpSheet->getProtection()->setFormatColumns(!$bool);
3815
3816 37
        // bit: 4; mask 0x0010; format rows
3817
        $bool = (0x0010 & $options) >> 4;
3818 37
        $this->phpSheet->getProtection()->setFormatRows(!$bool);
3819
3820
        // bit: 5; mask 0x0020; insert columns
3821 1
        $bool = (0x0020 & $options) >> 5;
3822 1
        $this->phpSheet->getProtection()->setInsertColumns(!$bool);
3823 1
3824
        // bit: 6; mask 0x0040; insert rows
3825
        $bool = (0x0040 & $options) >> 6;
3826
        $this->phpSheet->getProtection()->setInsertRows(!$bool);
3827 37
3828 37
        // bit: 7; mask 0x0080; insert hyperlinks
3829
        $bool = (0x0080 & $options) >> 7;
3830 1
        $this->phpSheet->getProtection()->setInsertHyperlinks(!$bool);
3831
3832
        // bit: 8; mask 0x0100; delete columns
3833
        $bool = (0x0100 & $options) >> 8;
3834
        $this->phpSheet->getProtection()->setDeleteColumns(!$bool);
3835
3836 37
        // bit: 9; mask 0x0200; delete rows
3837
        $bool = (0x0200 & $options) >> 9;
3838
        $this->phpSheet->getProtection()->setDeleteRows(!$bool);
3839 37
3840
        // bit: 10; mask 0x0400; select locked cells
3841 7
        // Note that this is opposite of most of above.
3842
        $bool = (0x0400 & $options) >> 10;
3843
        $this->phpSheet->getProtection()->setSelectLockedCells((bool) $bool);
3844 7
3845 7
        // bit: 11; mask 0x0800; sort cell range
3846
        $bool = (0x0800 & $options) >> 11;
3847
        $this->phpSheet->getProtection()->setSort(!$bool);
3848
3849
        // bit: 12; mask 0x1000; auto filter
3850 7
        $bool = (0x1000 & $options) >> 12;
3851
        $this->phpSheet->getProtection()->setAutoFilter(!$bool);
3852 34
3853 34
        // bit: 13; mask 0x2000; pivot tables
3854 34
        $bool = (0x2000 & $options) >> 13;
3855
        $this->phpSheet->getProtection()->setPivotTables(!$bool);
3856
3857 3
        // bit: 14; mask 0x4000; select unlocked cells
3858 3
        // Note that this is opposite of most of above.
3859
        $bool = (0x4000 & $options) >> 14;
3860 32
        $this->phpSheet->getProtection()->setSelectUnlockedCells((bool) $bool);
3861 32
3862 32
        // offset: 21; size: 2; not used
3863
    }
3864
3865 11
    /**
3866 11
     * Read RANGEPROTECTION record
3867
     * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification,
3868 32
     * where it is referred to as FEAT record.
3869 32
     */
3870 32
    protected function readRangeProtection(): void
3871
    {
3872
        $length = self::getUInt2d($this->data, $this->pos + 2);
3873 2
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3874 2
3875
        // move stream pointer to next record
3876
        $this->pos += 4 + $length;
3877 32
3878 32
        // local pointer in record data
3879
        $offset = 0;
3880
3881 37
        if (!$this->readDataOnly) {
3882 37
            $offset += 12;
3883
3884 35
            // offset: 12; size: 2; shared feature type, 2 = enhanced protection, 4 = smart tag
3885
            $isf = self::getUInt2d($recordData, 12);
3886
            if ($isf != 2) {
3887
                // we only read FEAT records of type 2
3888 37
                return;
3889
            }
3890
            $offset += 2;
3891
3892 37
            $offset += 5;
3893 1
3894
            // offset: 19; size: 2; count of ref ranges this feature is on
3895 36
            $cref = self::getUInt2d($recordData, 19);
3896 36
            $offset += 2;
3897 2
3898 2
            $offset += 6;
3899
3900
            // offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record)
3901 1
            $cellRanges = [];
3902
            for ($i = 0; $i < $cref; ++$i) {
3903
                try {
3904
                    $cellRange = Xls\Biff8::readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8));
3905
                } catch (PhpSpreadsheetException) {
3906
                    return;
3907
                }
3908
                $cellRanges[] = $cellRange;
3909 37
                $offset += 8;
3910
            }
3911
3912
            // offset: var; size: var; variable length of feature specific data
3913
            //$rgbFeat = substr($recordData, $offset);
3914
            $offset += 4;
3915
3916
            // offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit)
3917
            $wPassword = self::getInt4d($recordData, $offset);
3918 1
            $offset += 4;
3919
3920 1
            // Apply range protection to sheet
3921 1
            if ($cellRanges) {
3922
                $this->phpSheet->protectCells(implode(' ', $cellRanges), ($wPassword === 0) ? '' : strtoupper(dechex($wPassword)), true);
3923
            }
3924 1
        }
3925
    }
3926
3927
    /**
3928
     * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record
3929
     * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented.
3930
     * In this case, we must treat the CONTINUE record as a MSODRAWING record.
3931
     */
3932
    protected function readContinue(): void
3933
    {
3934
        $length = self::getUInt2d($this->data, $this->pos + 2);
3935
        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
3936 1
3937
        // check if we are reading drawing data
3938
        // this is in case a free CONTINUE record occurs in other circumstances we are unaware of
3939 1
        if ($this->drawingData == '') {
3940
            // move stream pointer to next record
3941
            $this->pos += 4 + $length;
3942
3943
            return;
3944
        }
3945
3946
        // check if record data is at least 4 bytes long, otherwise there is no chance this is MSODRAWING data
3947
        if ($length < 4) {
3948
            // move stream pointer to next record
3949 7
            $this->pos += 4 + $length;
3950
3951 7
            return;
3952 7
        }
3953
3954
        // dirty check to see if CONTINUE record could be a camouflaged MSODRAWING record
3955 7
        // look inside CONTINUE record to see if it looks like a part of an Escher stream
3956
        // we know that Escher stream may be split at least at
3957 7
        //        0xF003 MsofbtSpgrContainer
3958 7
        //        0xF004 MsofbtSpContainer
3959 7
        //        0xF00D MsofbtClientTextbox
3960
        $validSplitPoints = [0xF003, 0xF004, 0xF00D]; // add identifiers if we find more
3961
3962
        $splitPoint = self::getUInt2d($recordData, 2);
3963
        if (in_array($splitPoint, $validSplitPoints)) {
3964
            // get spliced record data (and move pointer to next record)
3965 7
            $splicedRecordData = $this->getSplicedRecordData();
3966
            $this->drawingData .= $splicedRecordData['recordData'];
3967
3968
            return;
3969
        }
3970
3971
        // move stream pointer to next record
3972
        $this->pos += 4 + $length;
3973
    }
3974
3975
    /**
3976 11
     * Reads a record from current position in data stream and continues reading data as long as CONTINUE
3977
     * records are found. Splices the record data pieces and returns the combined string as if record data
3978 11
     * is in one piece.
3979 11
     * Moves to next current position in data stream to start of next record different from a CONtINUE record.
3980
     */
3981
    private function getSplicedRecordData(): array
3982 11
    {
3983
        $data = '';
3984
        $spliceOffsets = [];
3985 11
3986
        $i = 0;
3987
        $spliceOffsets[0] = 0;
3988 11
3989 11
        do {
3990
            ++$i;
3991
3992 11
            // offset: 0; size: 2; identifier
3993
            //$identifier = self::getUInt2d($this->data, $this->pos);
3994 11
            // offset: 2; size: 2; length
3995
            $length = self::getUInt2d($this->data, $this->pos + 2);
3996
            $data .= $this->readRecordData($this->data, $this->pos + 4, $length);
3997 11
3998
            $spliceOffsets[$i] = $spliceOffsets[$i - 1] + $length;
3999
4000 11
            $this->pos += 4 + $length;
4001
            $nextIdentifier = self::getUInt2d($this->data, $this->pos);
4002 11
        } while ($nextIdentifier == self::XLS_TYPE_CONTINUE);
4003
4004 11
        return [
4005 11
            'recordData' => $data,
4006
            'spliceOffsets' => $spliceOffsets,
4007
        ];
4008 11
    }
4009
4010 11
    /**
4011
     * Convert formula structure into human readable Excel formula like 'A3+A5*5'.
4012
     *
4013
     * @param string $formulaStructure The complete binary data for the formula
4014
     * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
4015
     *
4016
     * @return string Human readable formula
4017
     */
4018
    protected function getFormulaFromStructure(string $formulaStructure, string $baseCell = 'A1'): string
4019
    {
4020 11
        // offset: 0; size: 2; size of the following formula data
4021
        $sz = self::getUInt2d($formulaStructure, 0);
4022 9
4023
        // offset: 2; size: sz
4024
        $formulaData = substr($formulaStructure, 2, $sz);
4025
4026
        // offset: 2 + sz; size: variable (optional)
4027
        if (strlen($formulaStructure) > 2 + $sz) {
4028
            $additionalData = substr($formulaStructure, 2 + $sz);
4029
        } else {
4030
            $additionalData = '';
4031
        }
4032
4033
        return $this->getFormulaFromData($formulaData, $additionalData, $baseCell);
4034
    }
4035 26
4036
    /**
4037 26
     * Take formula data and additional data for formula and return human readable formula.
4038 26
     *
4039
     * @param string $formulaData The binary data for the formula itself
4040
     * @param string $additionalData Additional binary data going with the formula
4041 26
     * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
4042
     *
4043
     * @return string Human readable formula
4044 26
     */
4045
    private function getFormulaFromData(string $formulaData, string $additionalData = '', string $baseCell = 'A1'): string
4046
    {
4047 26
        // start parsing the formula data
4048
        $tokens = [];
4049
4050
        while ($formulaData !== '' && $token = $this->getNextToken($formulaData, $baseCell)) {
4051 26
            $tokens[] = $token;
4052 24
            $formulaData = substr($formulaData, $token['size']);
4053 24
        }
4054
4055
        $formulaString = $this->createFormulaFromTokens($tokens, $additionalData);
4056 24
4057 24
        return $formulaString;
4058 24
    }
4059 24
4060
    /**
4061
     * Take array of tokens together with additional data for formula and return human readable formula.
4062
     *
4063
     * @param string $additionalData Additional binary data going with the formula
4064
     *
4065
     * @return string Human readable formula
4066
     */
4067
    private function createFormulaFromTokens(array $tokens, string $additionalData): string
4068
    {
4069
        // empty formula?
4070
        if (empty($tokens)) {
4071
            return '';
4072
        }
4073
4074
        $formulaStrings = [];
4075
        foreach ($tokens as $token) {
4076
            // initialize spaces
4077
            $space0 = $space0 ?? ''; // spaces before next token, not tParen
4078 4
            $space1 = $space1 ?? ''; // carriage returns before next token, not tParen
4079
            $space2 = $space2 ?? ''; // spaces before opening parenthesis
4080 4
            $space3 = $space3 ?? ''; // carriage returns before opening parenthesis
4081 4
            $space4 = $space4 ?? ''; // spaces before closing parenthesis
4082
            $space5 = $space5 ?? ''; // carriage returns before closing parenthesis
4083
4084 4
            switch ($token['name']) {
4085
                case 'tAdd': // addition
4086
                case 'tConcat': // addition
4087 4
                case 'tDiv': // division
4088
                case 'tEQ': // equality
4089
                case 'tGE': // greater than or equal
4090 4
                case 'tGT': // greater than
4091 4
                case 'tIsect': // intersection
4092
                case 'tLE': // less than or equal
4093
                case 'tList': // less than or equal
4094 4
                case 'tLT': // less than
4095
                case 'tMul': // multiplication
4096 4
                case 'tNE': // multiplication
4097
                case 'tPower': // power
4098
                case 'tRange': // range
4099
                case 'tSub': // subtraction
4100 4
                    $op2 = array_pop($formulaStrings);
4101 2
                    $op1 = array_pop($formulaStrings);
4102 2
                    $formulaStrings[] = "$op1$space1$space0{$token['data']}$op2";
4103
                    unset($space0, $space1);
4104 2
4105 2
                    break;
4106
                case 'tUplus': // unary plus
4107 4
                case 'tUminus': // unary minus
4108 4
                    $op = array_pop($formulaStrings);
4109 4
                    $formulaStrings[] = "$space1$space0{$token['data']}$op";
4110
                    unset($space0, $space1);
4111 4
4112
                    break;
4113 4
                case 'tPercent': // percent sign
4114
                    $op = array_pop($formulaStrings);
4115
                    $formulaStrings[] = "$op$space1$space0{$token['data']}";
4116
                    unset($space0, $space1);
4117
4118
                    break;
4119
                case 'tAttrVolatile': // indicates volatile function
4120
                case 'tAttrIf':
4121
                case 'tAttrSkip':
4122 25
                case 'tAttrChoose':
4123
                    // token is only important for Excel formula evaluator
4124 25
                    // do nothing
4125 25
                    break;
4126
                case 'tAttrSpace': // space / carriage return
4127
                    // space will be used when next token arrives, do not alter formulaString stack
4128 25
                    switch ($token['data']['spacetype']) {
4129
                        case 'type0':
4130
                            $space0 = str_repeat(' ', $token['data']['spacecount']);
4131 25
4132
                            break;
4133
                        case 'type1':
4134 25
                            $space1 = str_repeat("\n", $token['data']['spacecount']);
4135 25
4136
                            break;
4137
                        case 'type2':
4138 25
                            $space2 = str_repeat(' ', $token['data']['spacecount']);
4139
4140 25
                            break;
4141
                        case 'type3':
4142
                            $space3 = str_repeat("\n", $token['data']['spacecount']);
4143 25
4144 25
                            break;
4145
                        case 'type4':
4146
                            $space4 = str_repeat(' ', $token['data']['spacecount']);
4147
4148
                            break;
4149
                        case 'type5':
4150
                            $space5 = str_repeat("\n", $token['data']['spacecount']);
4151
4152 17
                            break;
4153
                    }
4154
4155
                    break;
4156
                case 'tAttrSum': // SUM function with one parameter
4157 17
                    $op = array_pop($formulaStrings);
4158 17
                    $formulaStrings[] = "{$space1}{$space0}SUM($op)";
4159
                    unset($space0, $space1);
4160 17
4161
                    break;
4162
                case 'tFunc': // function with fixed number of arguments
4163
                case 'tFuncV': // function with variable number of arguments
4164
                    if ($token['data']['function'] != '') {
4165
                        // normal function
4166 13
                        $ops = []; // array of operators
4167
                        for ($i = 0; $i < $token['data']['args']; ++$i) {
4168 13
                            $ops[] = array_pop($formulaStrings);
4169 13
                        }
4170
                        $ops = array_reverse($ops);
4171
                        $formulaStrings[] = "$space1$space0{$token['data']['function']}(" . implode(',', $ops) . ')';
4172 13
                        unset($space0, $space1);
4173
                    } else {
4174 13
                        // add-in function
4175 1
                        $ops = []; // array of operators
4176
                        for ($i = 0; $i < $token['data']['args'] - 1; ++$i) {
4177
                            $ops[] = array_pop($formulaStrings);
4178
                        }
4179
                        $ops = array_reverse($ops);
4180
                        $function = array_pop($formulaStrings);
4181
                        $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ')';
4182
                        unset($space0, $space1);
4183
                    }
4184
4185
                    break;
4186
                case 'tParen': // parenthesis
4187 12
                    $expression = array_pop($formulaStrings);
4188 12
                    $formulaStrings[] = "$space3$space2($expression$space5$space4)";
4189 12
                    unset($space2, $space3, $space4, $space5);
4190 12
4191 12
                    break;
4192
                case 'tArray': // array constant
4193 12
                    $constantArray = Xls\Biff8::readBIFF8ConstantArray($additionalData);
4194 12
                    $formulaStrings[] = $space1 . $space0 . $constantArray['value'];
4195 12
                    $additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data
4196 12
                    unset($space0, $space1);
4197 12
4198 12
                    break;
4199 12
                case 'tMemArea':
4200 12
                    // bite off chunk of additional data
4201
                    $cellRangeAddressList = Xls\Biff8::readBIFF8CellRangeAddressList($additionalData);
4202
                    $additionalData = substr($additionalData, $cellRangeAddressList['size']);
4203
                    $formulaStrings[] = "$space1$space0{$token['data']}";
4204
                    unset($space0, $space1);
4205
4206 113
                    break;
4207
                case 'tArea': // cell range address
4208 113
                case 'tBool': // boolean
4209 113
                case 'tErr': // error code
4210
                case 'tInt': // integer
4211
                case 'tMemErr':
4212 113
                case 'tMemFunc':
4213
                case 'tMissArg':
4214
                case 'tName':
4215 113
                case 'tNameX':
4216
                case 'tNum': // number
4217
                case 'tRef': // single cell reference
4218
                case 'tRef3d': // 3d cell reference
4219
                case 'tArea3d': // 3d cell range reference
4220
                case 'tRefN':
4221
                case 'tAreaN':
4222 113
                case 'tStr': // string
4223 113
                    $formulaStrings[] = "$space1$space0{$token['data']}";
4224 113
                    unset($space0, $space1);
4225
4226
                    break;
4227
            }
4228
        }
4229 111
        $formulaString = $formulaStrings[0];
4230
4231
        return $formulaString;
4232 111
    }
4233
4234
    /**
4235 111
     * Fetch next token from binary formula data.
4236 107
     *
4237
     * @param string $formulaData Formula data
4238
     * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
4239 111
     */
4240
    private function getNextToken(string $formulaData, string $baseCell = 'A1'): array
4241
    {
4242 111
        // offset: 0; size: 1; token id
4243
        $id = ord($formulaData[0]); // token id
4244
        $name = false; // initialize token name
4245 111
4246 49
        switch ($id) {
4247
            case 0x03:
4248
                $name = 'tAdd';
4249
                $size = 1;
4250
                $data = '+';
4251 113
4252 113
                break;
4253
            case 0x04:
4254
                $name = 'tSub';
4255 113
                $size = 1;
4256 113
                $data = '-';
4257
4258
                break;
4259 113
            case 0x05:
4260
                $name = 'tMul';
4261
                $size = 1;
4262 113
                $data = '*';
4263
4264
                break;
4265 113
            case 0x06:
4266 113
                $name = 'tDiv';
4267 109
                $size = 1;
4268 109
                $data = '/';
4269
4270
                break;
4271
            case 0x07:
4272 113
                $name = 'tPower';
4273
                $size = 1;
4274
                $data = '^';
4275
4276 113
                break;
4277
            case 0x08:
4278 113
                $name = 'tConcat';
4279 113
                $size = 1;
4280 113
                $data = '&';
4281 111
4282 111
                break;
4283 111
            case 0x09:
4284
                $name = 'tLT';
4285
                $size = 1;
4286
                $data = '<';
4287
4288
                break;
4289
            case 0x0A:
4290
                $name = 'tLE';
4291 100
                $size = 1;
4292
                $data = '<=';
4293 100
4294 100
                break;
4295
            case 0x0B:
4296
                $name = 'tEQ';
4297 100
                $size = 1;
4298
                $data = '=';
4299
4300
                break;
4301
            case 0x0C:
4302
                $name = 'tGE';
4303
                $size = 1;
4304
                $data = '>=';
4305
4306
                break;
4307
            case 0x0D:
4308
                $name = 'tGT';
4309 100
                $size = 1;
4310
                $data = '>';
4311 100
4312
                break;
4313
            case 0x0E:
4314 100
                $name = 'tNE';
4315
                $size = 1;
4316
                $data = '<>';
4317
4318 100
                break;
4319
            case 0x0F:
4320
                $name = 'tIsect';
4321
                $size = 1;
4322
                $data = ' ';
4323
4324
                break;
4325
            case 0x10:
4326
                $name = 'tList';
4327
                $size = 1;
4328 6
                $data = ',';
4329
4330 6
                break;
4331 6
            case 0x11:
4332
                $name = 'tRange';
4333
                $size = 1;
4334 6
                $data = ':';
4335
4336
                break;
4337 6
            case 0x12:
4338
                $name = 'tUplus';
4339
                $size = 1;
4340 6
                $data = '+';
4341
4342
                break;
4343 6
            case 0x13:
4344
                $name = 'tUminus';
4345
                $size = 1;
4346
                $data = '-';
4347
4348
                break;
4349 8
            case 0x14:
4350
                $name = 'tPercent';
4351 8
                $size = 1;
4352 8
                $data = '%';
4353
4354
                break;
4355 8
            case 0x15:    //    parenthesis
4356
                $name = 'tParen';
4357 8
                $size = 1;
4358
                $data = null;
4359 8
4360
                break;
4361
            case 0x16:    //    missing argument
4362 8
                $name = 'tMissArg';
4363
                $size = 1;
4364
                $data = '';
4365 8
4366
                break;
4367
            case 0x17:    //    string
4368 8
                $name = 'tStr';
4369
                // offset: 1; size: var; Unicode string, 8-bit string length
4370 8
                $string = self::readUnicodeStringShort(substr($formulaData, 1));
4371
                $size = 1 + $string['size'];
4372 8
                $data = self::UTF8toExcelDoubleQuoted($string['value']);
4373 8
4374 8
                break;
4375
            case 0x19:    //    Special attribute
4376
                // offset: 1; size: 1; attribute type flags:
4377
                switch (ord($formulaData[1])) {
4378
                    case 0x01:
4379
                        $name = 'tAttrVolatile';
4380
                        $size = 4;
4381
                        $data = null;
4382
4383 110
                        break;
4384
                    case 0x02:
4385 110
                        $name = 'tAttrIf';
4386 110
                        $size = 4;
4387 110
                        $data = null;
4388
4389
                        break;
4390 110
                    case 0x04:
4391
                        $name = 'tAttrChoose';
4392 110
                        // offset: 2; size: 2; number of choices in the CHOOSE function ($nc, number of parameters decreased by 1)
4393
                        $nc = self::getUInt2d($formulaData, 2);
4394
                        // offset: 4; size: 2 * $nc
4395
                        // offset: 4 + 2 * $nc; size: 2
4396
                        $size = 2 * $nc + 6;
4397
                        $data = null;
4398
4399
                        break;
4400
                    case 0x08:
4401
                        $name = 'tAttrSkip';
4402
                        $size = 4;
4403
                        $data = null;
4404
4405
                        break;
4406
                    case 0x10:
4407 108
                        $name = 'tAttrSum';
4408 108
                        $size = 4;
4409
                        $data = null;
4410 108
4411
                        break;
4412
                    case 0x40:
4413 108
                    case 0x41:
4414
                        $name = 'tAttrSpace';
4415
                        $size = 4;
4416
                        // offset: 2; size: 2; space type and position
4417
                        $spacetype = match (ord($formulaData[2])) {
4418 108
                            0x00 => 'type0',
4419
                            0x01 => 'type1',
4420
                            0x02 => 'type2',
4421
                            0x03 => 'type3',
4422
                            0x04 => 'type4',
4423 108
                            0x05 => 'type5',
4424 2
                            default => throw new Exception('Unrecognized space type in tAttrSpace token'),
4425
                        };
4426
                        // offset: 3; size: 1; number of inserted spaces/carriage returns
4427 108
                        $spacecount = ord($formulaData[3]);
4428
4429
                        $data = ['spacetype' => $spacetype, 'spacecount' => $spacecount];
4430 110
4431
                        break;
4432
                    default:
4433 17
                        throw new Exception('Unrecognized attribute flag in tAttr token');
4434
                }
4435 17
4436 17
                break;
4437 17
            case 0x1C:    //    error code
4438 17
                // offset: 1; size: 1; error code
4439 17
                $name = 'tErr';
4440 17
                $size = 2;
4441 17
                $data = Xls\ErrorCode::lookup(ord($formulaData[1]));
4442 17
4443 17
                break;
4444
            case 0x1D:    //    boolean
4445 17
                // offset: 1; size: 1; 0 = false, 1 = true;
4446
                $name = 'tBool';
4447
                $size = 2;
4448
                $data = ord($formulaData[1]) ? 'TRUE' : 'FALSE';
4449
4450
                break;
4451 17
            case 0x1E:    //    integer
4452
                // offset: 1; size: 2; unsigned 16-bit integer
4453
                $name = 'tInt';
4454
                $size = 3;
4455
                $data = self::getUInt2d($formulaData, 1);
4456
4457
                break;
4458
            case 0x1F:    //    number
4459
                // offset: 1; size: 8;
4460
                $name = 'tNum';
4461
                $size = 9;
4462
                $data = self::extractNumber(substr($formulaData, 1));
4463 19
                $data = str_replace(',', '.', (string) $data); // in case non-English locale
4464
4465 19
                break;
4466 19
            case 0x20:    //    array constant
4467
            case 0x40:
4468
            case 0x60:
4469 19
                // offset: 1; size: 7; not used
4470
                $name = 'tArray';
4471 19
                $size = 8;
4472 17
                $data = null;
4473 17
4474
                break;
4475 17
            case 0x21:    //    function with fixed number of arguments
4476 17
            case 0x41:
4477
            case 0x61:
4478 17
                $name = 'tFunc';
4479
                $size = 3;
4480
                // offset: 1; size: 2; index to built-in sheet function
4481
                $mapping = Xls\Mappings::TFUNC_MAPPINGS[self::getUInt2d($formulaData, 1)] ?? null;
4482
                if ($mapping === null) {
4483
                    throw new Exception('Unrecognized function in formula');
4484
                }
4485
                $data = ['function' => $mapping[0], 'args' => $mapping[1]];
4486
4487 6
                break;
4488
            case 0x22:    //    function with variable number of arguments
4489 6
            case 0x42:
4490 6
            case 0x62:
4491
                $name = 'tFuncV';
4492
                $size = 4;
4493 6
                // offset: 1; size: 1; number of arguments
4494
                $args = ord($formulaData[1]);
4495 6
                // offset: 2: size: 2; index to built-in sheet function
4496
                $index = self::getUInt2d($formulaData, 2);
4497
                $function = Xls\Mappings::TFUNCV_MAPPINGS[$index] ?? null;
4498 6
                if ($function === null) {
4499
                    throw new Exception('Unrecognized function in formula');
4500
                }
4501
                $data = ['function' => $function, 'args' => $args];
4502
4503
                break;
4504
            case 0x23:    //    index to defined name
4505
            case 0x43:
4506
            case 0x63:
4507
                $name = 'tName';
4508
                $size = 5;
4509 6
                // offset: 1; size: 2; one-based index to definedname record
4510
                $definedNameIndex = self::getUInt2d($formulaData, 1) - 1;
4511
                // offset: 2; size: 2; not used
4512
                $data = $this->definedname[$definedNameIndex]['name'] ?? '';
4513
4514
                break;
4515 6
            case 0x24:    //    single cell reference e.g. A5
4516
            case 0x44:
4517
            case 0x64:
4518 6
                $name = 'tRef';
4519
                $size = 5;
4520
                $data = Xls\Biff8::readBIFF8CellAddress(substr($formulaData, 1, 4));
4521 6
4522
                break;
4523
            case 0x25:    //    cell range reference to cells in the same sheet (2d)
4524 6
            case 0x45:
4525
            case 0x65:
4526
                $name = 'tArea';
4527 6
                $size = 9;
4528
                $data = Xls\Biff8::readBIFF8CellRangeAddress(substr($formulaData, 1, 8));
4529 6
4530
                break;
4531 3
            case 0x26:    //    Constant reference sub-expression
4532
            case 0x46:
4533
            case 0x66:
4534 3
                $name = 'tMemArea';
4535
                // offset: 1; size: 4; not used
4536 6
                // offset: 5; size: 2; size of the following subexpression
4537
                $subSize = self::getUInt2d($formulaData, 5);
4538
                $size = 7 + $subSize;
4539
                $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize));
4540
4541
                break;
4542 6
            case 0x27:    //    Deleted constant reference sub-expression
4543
            case 0x47:
4544 6
            case 0x67:
4545
                $name = 'tMemErr';
4546 6
                // offset: 1; size: 4; not used
4547 3
                // offset: 5; size: 2; size of the following subexpression
4548 6
                $subSize = self::getUInt2d($formulaData, 5);
4549
                $size = 7 + $subSize;
4550 6
                $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize));
4551 6
4552
                break;
4553
            case 0x29:    //    Variable reference sub-expression
4554
            case 0x49:
4555 6
            case 0x69:
4556
                $name = 'tMemFunc';
4557
                // offset: 1; size: 2; size of the following sub-expression
4558
                $subSize = self::getUInt2d($formulaData, 1);
4559
                $size = 3 + $subSize;
4560 6
                $data = $this->getFormulaFromData(substr($formulaData, 3, $subSize));
4561
4562 6
                break;
4563 6
            case 0x2C: // Relative 2d cell reference reference, used in shared formulas and some other places
4564
            case 0x4C:
4565 6
            case 0x6C:
4566 6
                $name = 'tRefN';
4567 6
                $size = 5;
4568 3
                $data = Xls\Biff8::readBIFF8CellAddressB(substr($formulaData, 1, 4), $baseCell);
4569
4570 6
                break;
4571 6
            case 0x2D:    //    Relative 2d range reference
4572
            case 0x4D:
4573 6
            case 0x6D:
4574 3
                $name = 'tAreaN';
4575
                $size = 9;
4576
                $data = Xls\Biff8::readBIFF8CellRangeAddressB(substr($formulaData, 1, 8), $baseCell);
4577
4578
                break;
4579
            case 0x39:    //    External name
4580
            case 0x59:
4581
            case 0x79:
4582
                $name = 'tNameX';
4583
                $size = 7;
4584
                // offset: 1; size: 2; index to REF entry in EXTERNSHEET record
4585
                // offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record
4586
                $index = self::getUInt2d($formulaData, 3);
4587
                // assume index is to EXTERNNAME record
4588
                $data = $this->externalNames[$index - 1]['name'] ?? '';
4589
4590
                // offset: 5; size: 2; not used
4591
                break;
4592
            case 0x3A:    //    3d reference to cell
4593
            case 0x5A:
4594
            case 0x7A:
4595
                $name = 'tRef3d';
4596
                $size = 7;
4597
4598
                try {
4599
                    // offset: 1; size: 2; index to REF entry
4600
                    $sheetRange = $this->readSheetRangeByRefIndex(self::getUInt2d($formulaData, 1));
4601
                    // offset: 3; size: 4; cell address
4602
                    $cellAddress = Xls\Biff8::readBIFF8CellAddress(substr($formulaData, 3, 4));
4603
4604
                    $data = "$sheetRange!$cellAddress";
4605
                } catch (PhpSpreadsheetException) {
4606
                    // deleted sheet reference
4607
                    $data = '#REF!';
4608
                }
4609
4610
                break;
4611
            case 0x3B:    //    3d reference to cell range
4612
            case 0x5B:
4613
            case 0x7B:
4614
                $name = 'tArea3d';
4615
                $size = 11;
4616
4617
                try {
4618
                    // offset: 1; size: 2; index to REF entry
4619
                    $sheetRange = $this->readSheetRangeByRefIndex(self::getUInt2d($formulaData, 1));
4620
                    // offset: 3; size: 8; cell address
4621
                    $cellRangeAddress = Xls\Biff8::readBIFF8CellRangeAddress(substr($formulaData, 3, 8));
4622
4623
                    $data = "$sheetRange!$cellRangeAddress";
4624
                } catch (PhpSpreadsheetException) {
4625
                    // deleted sheet reference
4626
                    $data = '#REF!';
4627
                }
4628 3
4629
                break;
4630
                // Unknown cases    // don't know how to deal with
4631
            default:
4632 3
                throw new Exception('Unrecognized token ' . sprintf('%02X', $id) . ' in formula');
4633
        }
4634
4635 3
        return [
4636
            'id' => $id,
4637 3
            'name' => $name,
4638
            'size' => $size,
4639
            'data' => $data,
4640
        ];
4641
    }
4642 6
4643
    /**
4644 3
     * Get a sheet range like Sheet1:Sheet3 from REF index
4645 3
     * Note: If there is only one sheet in the range, one gets e.g Sheet1
4646
     * It can also happen that the REF structure uses the -1 (FFFF) code to indicate deleted sheets,
4647 3
     * in which case an Exception is thrown.
4648 3
     */
4649
    protected function readSheetRangeByRefIndex(int $index): string|false
4650
    {
4651
        if (isset($this->ref[$index])) {
4652 6
            $type = $this->externalBooks[$this->ref[$index]['externalBookIndex']]['type'];
4653 6
4654
            switch ($type) {
4655
                case 'internal':
4656
                    // check if we have a deleted 3d reference
4657
                    if ($this->ref[$index]['firstSheetIndex'] == 0xFFFF || $this->ref[$index]['lastSheetIndex'] == 0xFFFF) {
4658
                        throw new Exception('Deleted sheet reference');
4659
                    }
4660
4661 3
                    // we have normal sheet range (collapsed or uncollapsed)
4662
                    $firstSheetName = $this->sheets[$this->ref[$index]['firstSheetIndex']]['name'];
4663 3
                    $lastSheetName = $this->sheets[$this->ref[$index]['lastSheetIndex']]['name'];
4664
4665
                    if ($firstSheetName == $lastSheetName) {
4666
                        // collapsed sheet range
4667 3
                        $sheetRange = $firstSheetName;
4668
                    } else {
4669
                        $sheetRange = "$firstSheetName:$lastSheetName";
4670
                    }
4671
4672
                    // escape the single-quotes
4673 3
                    $sheetRange = str_replace("'", "''", $sheetRange);
4674
4675 3
                    // if there are special characters, we need to enclose the range in single-quotes
4676 3
                    // todo: check if we have identified the whole set of special characters
4677
                    // it seems that the following characters are not accepted for sheet names
4678
                    // and we may assume that they are not present: []*/:\?
4679 3
                    if (preg_match("/[ !\"@#£$%&{()}<>=+'|^,;-]/u", $sheetRange)) {
4680
                        $sheetRange = "'$sheetRange'";
4681 3
                    }
4682
4683
                    return $sheetRange;
4684
                default:
4685
                    // TODO: external sheet support
4686 3
                    throw new Exception('Xls reader only supports internal sheets in formulas');
4687
            }
4688
        }
4689 3
4690 3
        return false;
4691
    }
4692
4693 3
    /**
4694 3
     * Read byte string (8-bit string length)
4695
     * OpenOffice documentation: 2.5.2.
4696
     */
4697
    protected function readByteStringShort(string $subData): array
4698
    {
4699
        // offset: 0; size: 1; length of the string (character count)
4700
        $ln = ord($subData[0]);
4701 3
4702
        // offset: 1: size: var; character array (8-bit characters)
4703
        $value = $this->decodeCodepage(substr($subData, 1, $ln));
4704 3
4705
        return [
4706
            'value' => $value,
4707 3
            'size' => 1 + $ln, // size in bytes of data structure
4708
        ];
4709
    }
4710 3
4711
    /**
4712
     * Read byte string (16-bit string length)
4713 3
     * OpenOffice documentation: 2.5.2.
4714 3
     */
4715
    protected function readByteStringLong(string $subData): array
4716 3
    {
4717
        // offset: 0; size: 2; length of the string (character count)
4718
        $ln = self::getUInt2d($subData, 0);
4719
4720
        // offset: 2: size: var; character array (8-bit characters)
4721 3
        $value = $this->decodeCodepage(substr($subData, 2));
4722 3
4723 3
        //return $string;
4724 3
        return [
4725
            'value' => $value,
4726
            'size' => 2 + $ln, // size in bytes of data structure
4727 3
        ];
4728 3
    }
4729 3
4730
    protected function parseRichText(string $is): RichText
4731
    {
4732 3
        $value = new RichText();
4733 3
        $value->createText($is);
4734 3
4735
        return $value;
4736
    }
4737 3
4738 3
    /**
4739 3
     * Phpstan 1.4.4 complains that this property is never read.
4740
     * So, we might be able to get rid of it altogether.
4741
     * For now, however, this function makes it readable,
4742 3
     * which satisfies Phpstan.
4743 3
     *
4744
     * @codeCoverageIgnore
4745
     */
4746 3
    public function getMapCellStyleXfIndex(): array
4747
    {
4748
        return $this->mapCellStyleXfIndex;
4749 3
    }
4750 3
4751
    /**
4752
     * Parse conditional formatting blocks.
4753 3
     *
4754
     * @see https://www.openoffice.org/sc/excelfileformat.pdf Search for CFHEADER followed by CFRULE
4755
     */
4756 3
    protected function readCFHeader(): array
4757 3
    {
4758
        return (new Xls\ConditionalFormatting())->readCFHeader2($this);
4759
    }
4760
4761
    protected function readCFRule(array $cellRangeAddresses): void
4762 3
    {
4763
        (new Xls\ConditionalFormatting())->readCFRule2($cellRangeAddresses, $this);
4764
    }
4765 3
4766 3
    public function getVersion(): int
4767
    {
4768
        return $this->version;
4769 3
    }
4770
}
4771