Workbook::writeStyle()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 0
loc 12
ccs 9
cts 9
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
4
5
use Composer\Pcre\Preg;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
8
use PhpOffice\PhpSpreadsheet\DefinedName;
9
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
10
use PhpOffice\PhpSpreadsheet\Shared\Date;
11
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
12
use PhpOffice\PhpSpreadsheet\Spreadsheet;
13
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
14
use PhpOffice\PhpSpreadsheet\Style\Style;
15
16
// Original file header of PEAR::Spreadsheet_Excel_Writer_Workbook (used as the base for this class):
17
// -----------------------------------------------------------------------------------------
18
// /*
19
// *  Module written/ported by Xavier Noguer <[email protected]>
20
// *
21
// *  The majority of this is _NOT_ my code.  I simply ported it from the
22
// *  PERL Spreadsheet::WriteExcel module.
23
// *
24
// *  The author of the Spreadsheet::WriteExcel module is John McNamara
25
// *  <[email protected]>
26
// *
27
// *  I _DO_ maintain this code, and John McNamara has nothing to do with the
28
// *  porting of this code to PHP.  Any questions directly related to this
29
// *  class library should be directed to me.
30
// *
31
// *  License Information:
32
// *
33
// *    Spreadsheet_Excel_Writer:  A library for generating Excel Spreadsheets
34
// *    Copyright (c) 2002-2003 Xavier Noguer [email protected]
35
// *
36
// *    This library is free software; you can redistribute it and/or
37
// *    modify it under the terms of the GNU Lesser General Public
38
// *    License as published by the Free Software Foundation; either
39
// *    version 2.1 of the License, or (at your option) any later version.
40
// *
41
// *    This library is distributed in the hope that it will be useful,
42
// *    but WITHOUT ANY WARRANTY; without even the implied warranty of
43
// *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
44
// *    Lesser General Public License for more details.
45
// *
46
// *    You should have received a copy of the GNU Lesser General Public
47
// *    License along with this library; if not, write to the Free Software
48
// *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
49
// */
50
class Workbook extends BIFFwriter
51
{
52
    /**
53
     * Formula parser.
54
     */
55
    private Parser $parser;
56
57
    /*
58
     * The BIFF file size for the workbook. Not currently used.
59
     *
60
     * @see calcSheetOffsets()
61
     */
62
    //private int $biffSize;
63
64
    /**
65
     * XF Writers.
66
     *
67
     * @var Xf[]
68
     */
69
    private array $xfWriters = [];
70
71
    /**
72
     * Array containing the colour palette.
73
     *
74
     * @var array<int, array{int, int, int, int}>
75
     */
76
    private array $palette;
77
78
    /**
79
     * The codepage indicates the text encoding used for strings.
80
     */
81
    private int $codepage;
82
83
    /**
84
     * The country code used for localization.
85
     */
86
    private int $countryCode;
87
88
    /**
89
     * Workbook.
90
     */
91
    private Spreadsheet $spreadsheet;
92
93
    /**
94
     * Fonts writers.
95
     *
96
     * @var Font[]
97
     */
98
    private array $fontWriters = [];
99
100
    /**
101
     * Added fonts. Maps from font's hash => index in workbook.
102
     *
103
     * @var int[]
104
     */
105
    private array $addedFonts = [];
106
107
    /**
108
     * Shared number formats.
109
     *
110
     * @var NumberFormat[]
111
     */
112
    private array $numberFormats = [];
113
114
    /**
115
     * Added number formats. Maps from numberFormat's hash => index in workbook.
116
     *
117
     * @var int[]
118
     */
119
    private array $addedNumberFormats = [];
120
121
    /**
122
     * Sizes of the binary worksheet streams.
123
     *
124
     * @var int[]
125
     */
126
    private array $worksheetSizes = [];
127
128
    /**
129
     * Offsets of the binary worksheet streams relative to the start of the global workbook stream.
130
     *
131
     * @var int[]
132
     */
133
    private array $worksheetOffsets = [];
134
135
    /**
136
     * Total number of shared strings in workbook.
137
     */
138
    private int $stringTotal;
139
140
    /**
141
     * Number of unique shared strings in workbook.
142
     */
143
    private int $stringUnique;
144
145
    /**
146
     * Array of unique shared strings in workbook.
147
     *
148
     * @var array<string, int>
149
     */
150
    private array $stringTable;
151
152
    /**
153
     * Color cache.
154
     *
155
     * @var int[]
156
     */
157
    private array $colors;
158
159
    /**
160
     * Escher object corresponding to MSODRAWINGGROUP.
161
     */
162
    private ?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher = null;
163
164
    /**
165
     * Class constructor.
166
     *
167
     * @param Spreadsheet $spreadsheet The Workbook
168
     * @param int $str_total Total number of strings
169
     * @param int $str_unique Total number of unique strings
170
     * @param array<string, int> $str_table String Table
171
     * @param int[] $colors Colour Table
172
     * @param Parser $parser The formula parser created for the Workbook
173
     */
174 120
    public function __construct(Spreadsheet $spreadsheet, int &$str_total, int &$str_unique, array &$str_table, array &$colors, Parser $parser)
175
    {
176
        // It needs to call its parent's constructor explicitly
177 120
        parent::__construct();
178
179 120
        $this->parser = $parser;
180
        //$this->biffSize = 0;
181 120
        $this->palette = [];
182 120
        $this->countryCode = -1;
183
184 120
        $this->stringTotal = &$str_total;
185 120
        $this->stringUnique = &$str_unique;
186 120
        $this->stringTable = &$str_table;
187 120
        $this->colors = &$colors;
188 120
        $this->setPaletteXl97();
189
190 120
        $this->spreadsheet = $spreadsheet;
191
192 120
        $this->codepage = 0x04B0;
193
194
        // Add empty sheets and Build color cache
195 120
        $countSheets = $spreadsheet->getSheetCount();
196 120
        for ($i = 0; $i < $countSheets; ++$i) {
197 120
            $phpSheet = $spreadsheet->getSheet($i);
198
199 120
            $this->parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser
200
201 120
            $supbook_index = 0x00;
202 120
            $ref = pack('vvv', $supbook_index, $i, $i);
203 120
            $this->parser->references[] = $ref; // Register reference with parser
204
205
            // Sheet tab colors?
206 120
            if ($phpSheet->isTabColorSet()) {
207 6
                $this->addColor($phpSheet->getTabColor()->getRGB());
208
            }
209
        }
210
    }
211
212
    /**
213
     * Add a new XF writer.
214
     *
215
     * @param bool $isStyleXf Is it a style XF?
216
     *
217
     * @return int Index to XF record
218
     */
219 119
    public function addXfWriter(Style $style, bool $isStyleXf = false): int
220
    {
221 119
        $xfWriter = new Xf($style);
222 119
        $xfWriter->setIsStyleXf($isStyleXf);
223
224
        // Add the font if not already added
225 119
        $fontIndex = $this->addFont($style->getFont());
226
227
        // Assign the font index to the xf record
228 119
        $xfWriter->setFontIndex($fontIndex);
229
230
        // Background colors, best to treat these after the font so black will come after white in custom palette
231 119
        if ($style->getFill()->getStartColor()->getRGB()) {
232 119
            $xfWriter->setFgColor(
233 119
                $this->addColor(
234 119
                    $style->getFill()->getStartColor()->getRGB()
235 119
                )
236 119
            );
237
        }
238 119
        if ($style->getFill()->getEndColor()->getRGB()) {
239 119
            $xfWriter->setBgColor(
240 119
                $this->addColor(
241 119
                    $style->getFill()->getEndColor()->getRGB()
242 119
                )
243 119
            );
244
        }
245 119
        $xfWriter->setBottomColor($this->addColor($style->getBorders()->getBottom()->getColor()->getRGB()));
246 119
        $xfWriter->setTopColor($this->addColor($style->getBorders()->getTop()->getColor()->getRGB()));
247 119
        $xfWriter->setRightColor($this->addColor($style->getBorders()->getRight()->getColor()->getRGB()));
248 119
        $xfWriter->setLeftColor($this->addColor($style->getBorders()->getLeft()->getColor()->getRGB()));
249 119
        $xfWriter->setDiagColor($this->addColor($style->getBorders()->getDiagonal()->getColor()->getRGB()));
250
251
        // Add the number format if it is not a built-in one and not already added
252 119
        if ($style->getNumberFormat()->getBuiltInFormatCode() === false) {
253 23
            $numberFormatHashCode = $style->getNumberFormat()->getHashCode();
254
255 23
            if (isset($this->addedNumberFormats[$numberFormatHashCode])) {
256 10
                $numberFormatIndex = $this->addedNumberFormats[$numberFormatHashCode];
257
            } else {
258 23
                $numberFormatIndex = 164 + count($this->numberFormats);
259 23
                $this->numberFormats[$numberFormatIndex] = $style->getNumberFormat();
260 23
                $this->addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex;
261
            }
262
        } else {
263 119
            $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode();
264
        }
265
266
        // Assign the number format index to xf record
267 119
        $xfWriter->setNumberFormatIndex($numberFormatIndex);
268
269 119
        $this->xfWriters[] = $xfWriter;
270
271 119
        return count($this->xfWriters) - 1;
272
    }
273
274
    /**
275
     * Add a font to added fonts.
276
     *
277
     * @return int Index to FONT record
278
     */
279 119
    public function addFont(\PhpOffice\PhpSpreadsheet\Style\Font $font): int
280
    {
281 119
        $fontHashCode = $font->getHashCode();
282 119
        if (isset($this->addedFonts[$fontHashCode])) {
283 119
            $fontIndex = $this->addedFonts[$fontHashCode];
284
        } else {
285 119
            $countFonts = count($this->fontWriters);
286 119
            $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1;
287
288 119
            $fontWriter = new Font($font);
289 119
            $fontWriter->setColorIndex($this->addColor($font->getColor()->getRGB()));
290 119
            $this->fontWriters[] = $fontWriter;
291
292 119
            $this->addedFonts[$fontHashCode] = $fontIndex;
293
        }
294
295 119
        return $fontIndex;
296
    }
297
298
    /**
299
     * Alter color palette adding a custom color.
300
     *
301
     * @param string $rgb E.g. 'FF00AA'
302
     *
303
     * @return int Color index
304
     */
305 120
    public function addColor(string $rgb, int $default = 0): int
306
    {
307 120
        if (!isset($this->colors[$rgb])) {
308 120
            $color
309 120
                = [
310 120
                    (int) hexdec(substr($rgb, 0, 2)),
311 120
                    (int) hexdec(substr($rgb, 2, 2)),
312 120
                    (int) hexdec(substr($rgb, 4)),
313 120
                    0,
314 120
                ];
315 120
            $colorIndex = array_search($color, $this->palette);
316 120
            if ($colorIndex) {
317 120
                $this->colors[$rgb] = $colorIndex;
318
            } else {
319 18
                if (count($this->colors) === 0) {
320 7
                    $lastColor = 7;
321
                } else {
322 18
                    $lastColor = end($this->colors);
323
                }
324 18
                if ($lastColor < 57) {
325
                    // then we add a custom color altering the palette
326 18
                    $colorIndex = $lastColor + 1;
327 18
                    $this->palette[$colorIndex] = $color;
328 18
                    $this->colors[$rgb] = $colorIndex;
329
                } else {
330
                    // no room for more custom colors, just map to black
331 1
                    $colorIndex = $default;
332
                }
333
            }
334
        } else {
335
            // fetch already added custom color
336 120
            $colorIndex = $this->colors[$rgb];
337
        }
338
339 120
        return $colorIndex;
340
    }
341
342
    /**
343
     * Sets the colour palette to the Excel 97+ default.
344
     */
345 120
    private function setPaletteXl97(): void
346
    {
347 120
        $this->palette = [
348 120
            0x08 => [0x00, 0x00, 0x00, 0x00],
349 120
            0x09 => [0xFF, 0xFF, 0xFF, 0x00],
350 120
            0x0A => [0xFF, 0x00, 0x00, 0x00],
351 120
            0x0B => [0x00, 0xFF, 0x00, 0x00],
352 120
            0x0C => [0x00, 0x00, 0xFF, 0x00],
353 120
            0x0D => [0xFF, 0xFF, 0x00, 0x00],
354 120
            0x0E => [0xFF, 0x00, 0xFF, 0x00],
355 120
            0x0F => [0x00, 0xFF, 0xFF, 0x00],
356 120
            0x10 => [0x80, 0x00, 0x00, 0x00],
357 120
            0x11 => [0x00, 0x80, 0x00, 0x00],
358 120
            0x12 => [0x00, 0x00, 0x80, 0x00],
359 120
            0x13 => [0x80, 0x80, 0x00, 0x00],
360 120
            0x14 => [0x80, 0x00, 0x80, 0x00],
361 120
            0x15 => [0x00, 0x80, 0x80, 0x00],
362 120
            0x16 => [0xC0, 0xC0, 0xC0, 0x00],
363 120
            0x17 => [0x80, 0x80, 0x80, 0x00],
364 120
            0x18 => [0x99, 0x99, 0xFF, 0x00],
365 120
            0x19 => [0x99, 0x33, 0x66, 0x00],
366 120
            0x1A => [0xFF, 0xFF, 0xCC, 0x00],
367 120
            0x1B => [0xCC, 0xFF, 0xFF, 0x00],
368 120
            0x1C => [0x66, 0x00, 0x66, 0x00],
369 120
            0x1D => [0xFF, 0x80, 0x80, 0x00],
370 120
            0x1E => [0x00, 0x66, 0xCC, 0x00],
371 120
            0x1F => [0xCC, 0xCC, 0xFF, 0x00],
372 120
            0x20 => [0x00, 0x00, 0x80, 0x00],
373 120
            0x21 => [0xFF, 0x00, 0xFF, 0x00],
374 120
            0x22 => [0xFF, 0xFF, 0x00, 0x00],
375 120
            0x23 => [0x00, 0xFF, 0xFF, 0x00],
376 120
            0x24 => [0x80, 0x00, 0x80, 0x00],
377 120
            0x25 => [0x80, 0x00, 0x00, 0x00],
378 120
            0x26 => [0x00, 0x80, 0x80, 0x00],
379 120
            0x27 => [0x00, 0x00, 0xFF, 0x00],
380 120
            0x28 => [0x00, 0xCC, 0xFF, 0x00],
381 120
            0x29 => [0xCC, 0xFF, 0xFF, 0x00],
382 120
            0x2A => [0xCC, 0xFF, 0xCC, 0x00],
383 120
            0x2B => [0xFF, 0xFF, 0x99, 0x00],
384 120
            0x2C => [0x99, 0xCC, 0xFF, 0x00],
385 120
            0x2D => [0xFF, 0x99, 0xCC, 0x00],
386 120
            0x2E => [0xCC, 0x99, 0xFF, 0x00],
387 120
            0x2F => [0xFF, 0xCC, 0x99, 0x00],
388 120
            0x30 => [0x33, 0x66, 0xFF, 0x00],
389 120
            0x31 => [0x33, 0xCC, 0xCC, 0x00],
390 120
            0x32 => [0x99, 0xCC, 0x00, 0x00],
391 120
            0x33 => [0xFF, 0xCC, 0x00, 0x00],
392 120
            0x34 => [0xFF, 0x99, 0x00, 0x00],
393 120
            0x35 => [0xFF, 0x66, 0x00, 0x00],
394 120
            0x36 => [0x66, 0x66, 0x99, 0x00],
395 120
            0x37 => [0x96, 0x96, 0x96, 0x00],
396 120
            0x38 => [0x00, 0x33, 0x66, 0x00],
397 120
            0x39 => [0x33, 0x99, 0x66, 0x00],
398 120
            0x3A => [0x00, 0x33, 0x00, 0x00],
399 120
            0x3B => [0x33, 0x33, 0x00, 0x00],
400 120
            0x3C => [0x99, 0x33, 0x00, 0x00],
401 120
            0x3D => [0x99, 0x33, 0x66, 0x00],
402 120
            0x3E => [0x33, 0x33, 0x99, 0x00],
403 120
            0x3F => [0x33, 0x33, 0x33, 0x00],
404 120
        ];
405
    }
406
407
    /**
408
     * Assemble worksheets into a workbook and send the BIFF data to an OLE
409
     * storage.
410
     *
411
     * @param int[] $worksheetSizes The sizes in bytes of the binary worksheet streams
412
     *
413
     * @return string Binary data for workbook stream
414
     */
415 118
    public function writeWorkbook(array $worksheetSizes): string
416
    {
417 118
        $this->worksheetSizes = $worksheetSizes;
418
419
        // Calculate the number of selected worksheet tabs and call the finalization
420
        // methods for each worksheet
421 118
        $total_worksheets = $this->spreadsheet->getSheetCount();
422
423
        // Add part 1 of the Workbook globals, what goes before the SHEET records
424 118
        $this->storeBof(0x0005);
425 118
        $this->writeCodepage();
426 118
        $this->writeWindow1();
427
428 118
        $this->writeDateMode();
429 118
        $this->writeAllFonts();
430 118
        $this->writeAllNumberFormats();
431 118
        $this->writeAllXfs();
432 118
        $this->writeAllStyles();
433 118
        $this->writePalette();
434
435
        // Prepare part 3 of the workbook global stream, what goes after the SHEET records
436 118
        $part3 = '';
437 118
        if ($this->countryCode !== -1) {
438
            $part3 .= $this->writeCountry();
439
        }
440 118
        $part3 .= $this->writeRecalcId();
441
442 118
        $part3 .= $this->writeSupbookInternal();
443
        /* TODO: store external SUPBOOK records and XCT and CRN records
444
        in case of external references for BIFF8 */
445 118
        $part3 .= $this->writeExternalsheetBiff8();
446 118
        $part3 .= $this->writeAllDefinedNamesBiff8();
447 118
        $part3 .= $this->writeMsoDrawingGroup();
448 118
        $part3 .= $this->writeSharedStringsTable();
449
450 118
        $part3 .= $this->writeEof();
451
452
        // Add part 2 of the Workbook globals, the SHEET records
453 118
        $this->calcSheetOffsets();
454 118
        for ($i = 0; $i < $total_worksheets; ++$i) {
455 118
            $this->writeBoundSheet($this->spreadsheet->getSheet($i), $this->worksheetOffsets[$i]);
456
        }
457
458
        // Add part 3 of the Workbook globals
459 118
        $this->_data .= $part3;
460
461 118
        return $this->_data;
462
    }
463
464
    /**
465
     * Calculate offsets for Worksheet BOF records.
466
     */
467 118
    private function calcSheetOffsets(): void
468
    {
469 118
        $boundsheet_length = 10; // fixed length for a BOUNDSHEET record
470
471
        // size of Workbook globals part 1 + 3
472 118
        $offset = $this->_datasize;
473
474
        // add size of Workbook globals part 2, the length of the SHEET records
475 118
        $total_worksheets = count($this->spreadsheet->getAllSheets());
476 118
        foreach ($this->spreadsheet->getWorksheetIterator() as $sheet) {
477 118
            $offset += $boundsheet_length + strlen(StringHelper::UTF8toBIFF8UnicodeShort($sheet->getTitle()));
478
        }
479
480
        // add the sizes of each of the Sheet substreams, respectively
481 118
        for ($i = 0; $i < $total_worksheets; ++$i) {
482 118
            $this->worksheetOffsets[$i] = $offset;
483 118
            $offset += $this->worksheetSizes[$i];
484
        }
485
        //$this->biffSize = $offset;
486
    }
487
488
    /**
489
     * Store the Excel FONT records.
490
     */
491 118
    private function writeAllFonts(): void
492
    {
493 118
        foreach ($this->fontWriters as $fontWriter) {
494 118
            $this->append($fontWriter->writeFont());
495
        }
496
    }
497
498
    /**
499
     * Store user defined numerical formats i.e. FORMAT records.
500
     */
501 118
    private function writeAllNumberFormats(): void
502
    {
503 118
        foreach ($this->numberFormats as $numberFormatIndex => $numberFormat) {
504 23
            $this->writeNumberFormat((string) $numberFormat->getFormatCode(), $numberFormatIndex);
505
        }
506
    }
507
508
    /**
509
     * Write all XF records.
510
     */
511 118
    private function writeAllXfs(): void
512
    {
513 118
        foreach ($this->xfWriters as $xfWriter) {
514 118
            $this->append($xfWriter->writeXf());
515
        }
516
    }
517
518
    /**
519
     * Write all STYLE records.
520
     */
521 118
    private function writeAllStyles(): void
522
    {
523 118
        $this->writeStyle();
524
    }
525
526 9
    private function parseDefinedNameValue(DefinedName $definedName): string
527
    {
528 9
        $definedRange = $definedName->getValue();
529 9
        $splitCount = Preg::matchAllWithOffsets(
530 9
            '/' . Calculation::CALCULATION_REGEXP_CELLREF . '/mui',
531 9
            $definedRange,
532 9
            $splitRanges
533 9
        );
534
535 9
        $lengths = array_map([StringHelper::class, 'strlenAllowNull'], array_column($splitRanges[0], 0));
536 9
        $offsets = array_column($splitRanges[0], 1);
537
538 9
        $worksheets = $splitRanges[2];
539 9
        $columns = $splitRanges[6];
540 9
        $rows = $splitRanges[7];
541
542 9
        while ($splitCount > 0) {
543 9
            --$splitCount;
544 9
            $length = $lengths[$splitCount];
545 9
            $offset = $offsets[$splitCount];
546 9
            $worksheet = $worksheets[$splitCount][0];
547 9
            $column = $columns[$splitCount][0];
548 9
            $row = $rows[$splitCount][0];
549
550 9
            $newRange = '';
551 9
            if (empty($worksheet)) {
552 8
                if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) {
553
                    // We should have a worksheet
554 5
                    $worksheet = $definedName->getWorksheet() ? $definedName->getWorksheet()->getTitle() : null;
555
                }
556
            } else {
557 4
                $worksheet = str_replace("''", "'", trim($worksheet, "'"));
558
            }
559 9
            if (!empty($worksheet)) {
560 9
                $newRange = "'" . str_replace("'", "''", $worksheet) . "'!";
561
            }
562
563 9
            if (!empty($column)) {
564 9
                $newRange .= "\${$column}";
565
            }
566 9
            if (!empty($row)) {
567 9
                $newRange .= "\${$row}";
568
            }
569
570 9
            $definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length);
571
        }
572
573 9
        return $definedRange;
574
    }
575
576
    /**
577
     * Writes all the DEFINEDNAME records (BIFF8).
578
     * So far this is only used for repeating rows/columns (print titles) and print areas.
579
     */
580 118
    private function writeAllDefinedNamesBiff8(): string
581
    {
582 118
        $chunk = '';
583
584
        // Named ranges
585 118
        $definedNames = $this->spreadsheet->getDefinedNames();
586 118
        if (count($definedNames) > 0) {
587
            // Loop named ranges
588 9
            foreach ($definedNames as $definedName) {
589 9
                $range = $this->parseDefinedNameValue($definedName);
590
591
                // parse formula
592
                try {
593 9
                    $this->parser->parse($range);
594 9
                    $formulaData = $this->parser->toReversePolish();
595
596
                    // make sure tRef3d is of type tRef3dR (0x3A)
597 8
                    if (isset($formulaData[0]) && ($formulaData[0] == "\x7A" || $formulaData[0] == "\x5A")) {
598 7
                        $formulaData = "\x3A" . substr($formulaData, 1);
599
                    }
600
601 8
                    if ($definedName->getLocalOnly()) {
602
                        // local scope
603 1
                        $scopeWs = $definedName->getScope();
604 1
                        $scope = ($scopeWs === null) ? 0 : ($this->spreadsheet->getIndex($scopeWs) + 1);
605
                    } else {
606
                        // global scope
607 8
                        $scope = 0;
608
                    }
609 8
                    $chunk .= $this->writeData($this->writeDefinedNameBiff8($definedName->getName(), $formulaData, $scope, false));
610 1
                } catch (PhpSpreadsheetException) {
611
                    // do nothing
612
                }
613
            }
614
        }
615
616
        // total number of sheets
617 118
        $total_worksheets = $this->spreadsheet->getSheetCount();
618
619
        // write the print titles (repeating rows, columns), if any
620 118
        for ($i = 0; $i < $total_worksheets; ++$i) {
621 118
            $sheetSetup = $this->spreadsheet->getSheet($i)->getPageSetup();
622
            // simultaneous repeatColumns repeatRows
623 118
            if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
624
                $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
625
                $colmin = Coordinate::columnIndexFromString($repeat[0]) - 1;
626
                $colmax = Coordinate::columnIndexFromString($repeat[1]) - 1;
627
628
                $repeat = $sheetSetup->getRowsToRepeatAtTop();
629
                $rowmin = $repeat[0] - 1;
630
                $rowmax = $repeat[1] - 1;
631
632
                // construct formula data manually
633
                $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc
634
                $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d
635
                $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d
636
                $formulaData .= pack('C', 0x10); // tList
637
638
                // store the DEFINEDNAME record
639
                $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
640 118
            } elseif ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
641
                // (exclusive) either repeatColumns or repeatRows.
642
                // Columns to repeat
643 2
                if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
644
                    $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
645
                    $colmin = Coordinate::columnIndexFromString($repeat[0]) - 1;
646
                    $colmax = Coordinate::columnIndexFromString($repeat[1]) - 1;
647
                } else {
648 2
                    $colmin = 0;
649 2
                    $colmax = 255;
650
                }
651
                // Rows to repeat
652 2
                if ($sheetSetup->isRowsToRepeatAtTopSet()) {
653 2
                    $repeat = $sheetSetup->getRowsToRepeatAtTop();
654 2
                    $rowmin = $repeat[0] - 1;
655 2
                    $rowmax = $repeat[1] - 1;
656
                } else {
657
                    $rowmin = 0;
658
                    $rowmax = 65535;
659
                }
660
661
                // construct formula data manually because parser does not recognize absolute 3d cell references
662 2
                $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax);
663
664
                // store the DEFINEDNAME record
665 2
                $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
666
            }
667
        }
668
669
        // write the print areas, if any
670 118
        for ($i = 0; $i < $total_worksheets; ++$i) {
671 118
            $sheetSetup = $this->spreadsheet->getSheet($i)->getPageSetup();
672 118
            if ($sheetSetup->isPrintAreaSet()) {
673
                // Print area, e.g. A3:J6,H1:X20
674 4
                $printArea = Coordinate::splitRange($sheetSetup->getPrintArea());
675 4
                $countPrintArea = count($printArea);
676
677 4
                $formulaData = '';
678 4
                for ($j = 0; $j < $countPrintArea; ++$j) {
679 4
                    $printAreaRect = $printArea[$j]; // e.g. A3:J6
680 4
                    $printAreaRect[0] = Coordinate::indexesFromString($printAreaRect[0]);
681
                    /** @var string */
682 4
                    $printAreaRect1 = $printAreaRect[1];
683 4
                    $printAreaRect[1] = Coordinate::indexesFromString($printAreaRect1);
684
685 4
                    $print_rowmin = $printAreaRect[0][1] - 1;
686 4
                    $print_rowmax = $printAreaRect[1][1] - 1;
687 4
                    $print_colmin = $printAreaRect[0][0] - 1;
688 4
                    $print_colmax = $printAreaRect[1][0] - 1;
689
690
                    // construct formula data manually because parser does not recognize absolute 3d cell references
691 4
                    $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax);
692
693 4
                    if ($j > 0) {
694 1
                        $formulaData .= pack('C', 0x10); // list operator token ','
695
                    }
696
                }
697
698
                // store the DEFINEDNAME record
699 4
                $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true));
700
            }
701
        }
702
703
        // write autofilters, if any
704 118
        for ($i = 0; $i < $total_worksheets; ++$i) {
705 118
            $sheetAutoFilter = $this->spreadsheet->getSheet($i)->getAutoFilter();
706 118
            $autoFilterRange = $sheetAutoFilter->getRange();
707 118
            if (!empty($autoFilterRange)) {
708 3
                $rangeBounds = Coordinate::rangeBoundaries($autoFilterRange);
709
710
                //Autofilter built in name
711 3
                $name = pack('C', 0x0D);
712
713 3
                $chunk .= $this->writeData($this->writeShortNameBiff8($name, $i + 1, $rangeBounds, true));
714
            }
715
        }
716
717 118
        return $chunk;
718
    }
719
720
    /**
721
     * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data.
722
     *
723
     * @param string $name The name in UTF-8
724
     * @param string $formulaData The binary formula data
725
     * @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global
726
     * @param bool $isBuiltIn Built-in name?
727
     *
728
     * @return string Complete binary record data
729
     */
730 12
    private function writeDefinedNameBiff8(string $name, string $formulaData, int $sheetIndex = 0, bool $isBuiltIn = false): string
731
    {
732 12
        $record = 0x0018;
733
734
        // option flags
735 12
        $options = $isBuiltIn ? 0x20 : 0x00;
736
737
        // length of the name, character count
738 12
        $nlen = StringHelper::countCharacters($name);
739
740
        // name with stripped length field
741 12
        $name = substr(StringHelper::UTF8toBIFF8UnicodeLong($name), 2);
742
743
        // size of the formula (in bytes)
744 12
        $sz = strlen($formulaData);
745
746
        // combine the parts
747 12
        $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0)
748 12
            . $name . $formulaData;
749 12
        $length = strlen($data);
750
751 12
        $header = pack('vv', $record, $length);
752
753 12
        return $header . $data;
754
    }
755
756
    /**
757
     * Write a short NAME record.
758
     *
759
     * @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global
760
     * @param int[][] $rangeBounds range boundaries
761
     *
762
     * @return string Complete binary record data
763
     * */
764 3
    private function writeShortNameBiff8(string $name, int $sheetIndex, array $rangeBounds, bool $isHidden = false): string
765
    {
766 3
        $record = 0x0018;
767
768
        // option flags
769 3
        $options = ($isHidden ? 0x21 : 0x00);
770
771 3
        $extra = pack(
772 3
            'Cvvvvv',
773 3
            0x3B,
774 3
            $sheetIndex - 1,
775 3
            $rangeBounds[0][1] - 1,
776 3
            $rangeBounds[1][1] - 1,
777 3
            $rangeBounds[0][0] - 1,
778 3
            $rangeBounds[1][0] - 1
779 3
        );
780
781
        // size of the formula (in bytes)
782 3
        $sz = strlen($extra);
783
784
        // combine the parts
785 3
        $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0)
786 3
            . $name . $extra;
787 3
        $length = strlen($data);
788
789 3
        $header = pack('vv', $record, $length);
790
791 3
        return $header . $data;
792
    }
793
794
    /**
795
     * Stores the CODEPAGE biff record.
796
     */
797 118
    private function writeCodepage(): void
798
    {
799 118
        $record = 0x0042; // Record identifier
800 118
        $length = 0x0002; // Number of bytes to follow
801 118
        $cv = $this->codepage; // The code page
802
803 118
        $header = pack('vv', $record, $length);
804 118
        $data = pack('v', $cv);
805
806 118
        $this->append($header . $data);
807
    }
808
809
    /**
810
     * Write Excel BIFF WINDOW1 record.
811
     */
812 118
    private function writeWindow1(): void
813
    {
814 118
        $record = 0x003D; // Record identifier
815 118
        $length = 0x0012; // Number of bytes to follow
816
817 118
        $xWn = 0x0000; // Horizontal position of window
818 118
        $yWn = 0x0000; // Vertical position of window
819 118
        $dxWn = 0x25BC; // Width of window
820 118
        $dyWn = 0x1572; // Height of window
821
822 118
        $grbit = 0x0038; // Option flags
823
824
        // not supported by PhpSpreadsheet, so there is only one selected sheet, the active
825 118
        $ctabsel = 1; // Number of workbook tabs selected
826
827 118
        $wTabRatio = 0x0258; // Tab to scrollbar ratio
828
829
        // not supported by PhpSpreadsheet, set to 0
830 118
        $itabFirst = 0; // 1st displayed worksheet
831 118
        $itabCur = $this->spreadsheet->getActiveSheetIndex(); // Active worksheet
832
833 118
        $header = pack('vv', $record, $length);
834 118
        $data = pack('vvvvvvvvv', $xWn, $yWn, $dxWn, $dyWn, $grbit, $itabCur, $itabFirst, $ctabsel, $wTabRatio);
835 118
        $this->append($header . $data);
836
    }
837
838
    /**
839
     * Writes Excel BIFF BOUNDSHEET record.
840
     *
841
     * @param int $offset Location of worksheet BOF
842
     */
843 118
    private function writeBoundSheet(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet, int $offset): void
844
    {
845 118
        $sheetname = $sheet->getTitle();
846 118
        $record = 0x0085; // Record identifier
847 118
        $ss = match ($sheet->getSheetState()) {
848 118
            \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VISIBLE => 0x00,
849 1
            \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN => 0x01,
850 1
            \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VERYHIDDEN => 0x02,
851
            default => 0x00,
852 118
        };
853
854
        // sheet type
855 118
        $st = 0x00;
856
857
        //$grbit = 0x0000; // Visibility and sheet type
858
859 118
        $data = pack('VCC', $offset, $ss, $st);
860 118
        $data .= StringHelper::UTF8toBIFF8UnicodeShort($sheetname);
861
862 118
        $length = strlen($data);
863 118
        $header = pack('vv', $record, $length);
864 118
        $this->append($header . $data);
865
    }
866
867
    /**
868
     * Write Internal SUPBOOK record.
869
     */
870 118
    private function writeSupbookInternal(): string
871
    {
872 118
        $record = 0x01AE; // Record identifier
873 118
        $length = 0x0004; // Bytes to follow
874
875 118
        $header = pack('vv', $record, $length);
876 118
        $data = pack('vv', $this->spreadsheet->getSheetCount(), 0x0401);
877
878 118
        return $this->writeData($header . $data);
879
    }
880
881
    /**
882
     * Writes the Excel BIFF EXTERNSHEET record. These references are used by
883
     * formulas.
884
     */
885 118
    private function writeExternalsheetBiff8(): string
886
    {
887 118
        $totalReferences = count($this->parser->references);
888 118
        $record = 0x0017; // Record identifier
889 118
        $length = 2 + 6 * $totalReferences; // Number of bytes to follow
890
891
        //$supbook_index = 0; // FIXME: only using internal SUPBOOK record
892 118
        $header = pack('vv', $record, $length);
893 118
        $data = pack('v', $totalReferences);
894 118
        for ($i = 0; $i < $totalReferences; ++$i) {
895 118
            $data .= $this->parser->references[$i];
896
        }
897
898 118
        return $this->writeData($header . $data);
899
    }
900
901
    /**
902
     * Write Excel BIFF STYLE records.
903
     */
904 118
    private function writeStyle(): void
905
    {
906 118
        $record = 0x0293; // Record identifier
907 118
        $length = 0x0004; // Bytes to follow
908
909 118
        $ixfe = 0x8000; // Index to cell style XF
910 118
        $BuiltIn = 0x00; // Built-in style
911 118
        $iLevel = 0xFF; // Outline style level
912
913 118
        $header = pack('vv', $record, $length);
914 118
        $data = pack('vCC', $ixfe, $BuiltIn, $iLevel);
915 118
        $this->append($header . $data);
916
    }
917
918
    /**
919
     * Writes Excel FORMAT record for non "built-in" numerical formats.
920
     *
921
     * @param string $format Custom format string
922
     * @param int $ifmt Format index code
923
     */
924 23
    private function writeNumberFormat(string $format, int $ifmt): void
925
    {
926 23
        $record = 0x041E; // Record identifier
927
928 23
        $numberFormatString = StringHelper::UTF8toBIFF8UnicodeLong($format);
929 23
        $length = 2 + strlen($numberFormatString); // Number of bytes to follow
930
931 23
        $header = pack('vv', $record, $length);
932 23
        $data = pack('v', $ifmt) . $numberFormatString;
933 23
        $this->append($header . $data);
934
    }
935
936
    /**
937
     * Write DATEMODE record to indicate the date system in use (1904 or 1900).
938
     */
939 118
    private function writeDateMode(): void
940
    {
941 118
        $record = 0x0022; // Record identifier
942 118
        $length = 0x0002; // Bytes to follow
943
944 118
        $f1904 = ($this->spreadsheet->getExcelCalendar() === Date::CALENDAR_MAC_1904)
945
            ? 1  // Flag for 1904 date system
946 118
            : 0; // Flag for 1900 date system
947
948 118
        $header = pack('vv', $record, $length);
949 118
        $data = pack('v', $f1904);
950 118
        $this->append($header . $data);
951
    }
952
953
    /**
954
     * Stores the COUNTRY record for localization.
955
     */
956
    private function writeCountry(): string
957
    {
958
        $record = 0x008C; // Record identifier
959
        $length = 4; // Number of bytes to follow
960
961
        $header = pack('vv', $record, $length);
962
        // using the same country code always for simplicity
963
        $data = pack('vv', $this->countryCode, $this->countryCode);
964
965
        return $this->writeData($header . $data);
966
    }
967
968
    /**
969
     * Write the RECALCID record.
970
     */
971 118
    private function writeRecalcId(): string
972
    {
973 118
        $record = 0x01C1; // Record identifier
974 118
        $length = 8; // Number of bytes to follow
975
976 118
        $header = pack('vv', $record, $length);
977
978
        // by inspection of real Excel files, MS Office Excel 2007 writes this
979 118
        $data = pack('VV', 0x000001C1, 0x00001E667);
980
981 118
        return $this->writeData($header . $data);
982
    }
983
984
    /**
985
     * Stores the PALETTE biff record.
986
     */
987 118
    private function writePalette(): void
988
    {
989 118
        $aref = $this->palette;
990
991 118
        $record = 0x0092; // Record identifier
992 118
        $length = 2 + 4 * count($aref); // Number of bytes to follow
993 118
        $ccv = count($aref); // Number of RGB values to follow
994 118
        $data = ''; // The RGB data
995
996
        // Pack the RGB data
997 118
        foreach ($aref as $color) {
998 118
            foreach ($color as $byte) {
999 118
                $data .= pack('C', $byte);
1000
            }
1001
        }
1002
1003 118
        $header = pack('vvv', $record, $length, $ccv);
1004 118
        $this->append($header . $data);
1005
    }
1006
1007
    /**
1008
     * Handling of the SST continue blocks is complicated by the need to include an
1009
     * additional continuation byte depending on whether the string is split between
1010
     * blocks or whether it starts at the beginning of the block. (There are also
1011
     * additional complications that will arise later when/if Rich Strings are
1012
     * supported).
1013
     *
1014
     * The Excel documentation says that the SST record should be followed by an
1015
     * EXTSST record. The EXTSST record is a hash table that is used to optimise
1016
     * access to SST. However, despite the documentation it doesn't seem to be
1017
     * required so we will ignore it.
1018
     *
1019
     * @return string Binary data
1020
     */
1021 118
    private function writeSharedStringsTable(): string
1022
    {
1023
        // maximum size of record data (excluding record header)
1024 118
        $continue_limit = 8224;
1025
1026
        // initialize array of record data blocks
1027 118
        $recordDatas = [];
1028
1029
        // start SST record data block with total number of strings, total number of unique strings
1030 118
        $recordData = pack('VV', $this->stringTotal, $this->stringUnique);
1031
1032
        // loop through all (unique) strings in shared strings table
1033 118
        foreach (array_keys($this->stringTable) as $string) {
1034
            // here $string is a BIFF8 encoded string
1035
1036
            // length = character count
1037 78
            $headerinfo = unpack('vlength/Cencoding', $string);
1038
1039
            // currently, this is always 1 = uncompressed
1040 78
            $encoding = $headerinfo['encoding'] ?? 1;
1041
1042
            // initialize finished writing current $string
1043 78
            $finished = false;
1044
1045 78
            while ($finished === false) {
1046
                // normally, there will be only one cycle, but if string cannot immediately be written as is
1047
                // there will be need for more than one cylcle, if string longer than one record data block, there
1048
                // may be need for even more cycles
1049
1050 78
                if (strlen($recordData) + strlen($string) <= $continue_limit) {
1051
                    // then we can write the string (or remainder of string) without any problems
1052 78
                    $recordData .= $string;
1053
1054 78
                    if (strlen($recordData) + strlen($string) == $continue_limit) {
1055
                        // we close the record data block, and initialize a new one
1056
                        $recordDatas[] = $recordData;
1057
                        $recordData = '';
1058
                    }
1059
1060
                    // we are finished writing this string
1061 78
                    $finished = true;
1062
                } else {
1063
                    // special treatment writing the string (or remainder of the string)
1064
                    // If the string is very long it may need to be written in more than one CONTINUE record.
1065
1066
                    // check how many bytes more there is room for in the current record
1067 1
                    $space_remaining = $continue_limit - strlen($recordData);
1068
1069
                    // minimum space needed
1070
                    // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character
1071
                    // compressed:   2 byte string length length field + 1 byte option flags + 1 byte character
1072 1
                    $min_space_needed = ($encoding == 1) ? 5 : 4;
1073
1074
                    // We have two cases
1075
                    // 1. space remaining is less than minimum space needed
1076
                    //        here we must waste the space remaining and move to next record data block
1077
                    // 2. space remaining is greater than or equal to minimum space needed
1078
                    //        here we write as much as we can in the current block, then move to next record data block
1079
1080 1
                    if ($space_remaining < $min_space_needed) {
1081
                        // 1. space remaining is less than minimum space needed.
1082
                        // we close the block, store the block data
1083
                        $recordDatas[] = $recordData;
1084
1085
                        // and start new record data block where we start writing the string
1086
                        $recordData = '';
1087
                    } else {
1088
                        // 2. space remaining is greater than or equal to minimum space needed.
1089
                        // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below
1090 1
                        $effective_space_remaining = $space_remaining;
1091
1092
                        // for uncompressed strings, sometimes effective space remaining is reduced by 1
1093 1
                        if ($encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1) {
1094 1
                            --$effective_space_remaining;
1095
                        }
1096
1097
                        // one block fininshed, store the block data
1098 1
                        $recordData .= substr($string, 0, $effective_space_remaining);
1099
1100 1
                        $string = substr($string, $effective_space_remaining); // for next cycle in while loop
1101 1
                        $recordDatas[] = $recordData;
1102
1103
                        // start new record data block with the repeated option flags
1104 1
                        $recordData = pack('C', $encoding);
1105
                    }
1106
                }
1107
            }
1108
        }
1109
1110
        // Store the last record data block unless it is empty
1111
        // if there was no need for any continue records, this will be the for SST record data block itself
1112 118
        if ($recordData !== '') {
1113 118
            $recordDatas[] = $recordData;
1114
        }
1115
1116
        // combine into one chunk with all the blocks SST, CONTINUE,...
1117 118
        $chunk = '';
1118 118
        foreach ($recordDatas as $i => $recordData) {
1119
            // first block should have the SST record header, remaing should have CONTINUE header
1120 118
            $record = ($i == 0) ? 0x00FC : 0x003C;
1121
1122 118
            $header = pack('vv', $record, strlen($recordData));
1123 118
            $data = $header . $recordData;
1124
1125 118
            $chunk .= $this->writeData($data);
1126
        }
1127
1128 118
        return $chunk;
1129
    }
1130
1131
    /**
1132
     * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records.
1133
     */
1134 118
    private function writeMsoDrawingGroup(): string
1135
    {
1136
        // write the Escher stream if necessary
1137 118
        if (isset($this->escher)) {
1138 15
            $writer = new Escher($this->escher);
1139 15
            $data = $writer->close();
1140
1141 15
            $record = 0x00EB;
1142 15
            $length = strlen($data);
1143 15
            $header = pack('vv', $record, $length);
1144
1145 15
            return $this->writeData($header . $data);
1146
        }
1147
1148 103
        return '';
1149
    }
1150
1151
    /**
1152
     * Get Escher object.
1153
     */
1154
    public function getEscher(): ?\PhpOffice\PhpSpreadsheet\Shared\Escher
1155
    {
1156
        return $this->escher;
1157
    }
1158
1159
    /**
1160
     * Set Escher object.
1161
     */
1162 15
    public function setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher): void
1163
    {
1164 15
        $this->escher = $escher;
1165
    }
1166
}
1167