Test Failed
Push — main ( c8394f...8477f1 )
by Rafael
66:21
created

Worksheet::writeDataValidity()   F

Complexity

Conditions 32
Paths > 20000

Size

Total Lines 206
Code Lines 129

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 32
eloc 129
nc 622082
nop 0
dl 0
loc 206
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
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\RichText\RichText;
10
use PhpOffice\PhpSpreadsheet\RichText\Run;
11
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
12
use PhpOffice\PhpSpreadsheet\Shared\Xls;
13
use PhpOffice\PhpSpreadsheet\Style\Alignment;
14
use PhpOffice\PhpSpreadsheet\Style\Border;
15
use PhpOffice\PhpSpreadsheet\Style\Color;
16
use PhpOffice\PhpSpreadsheet\Style\Conditional;
17
use PhpOffice\PhpSpreadsheet\Style\Fill;
18
use PhpOffice\PhpSpreadsheet\Style\Protection;
19
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
20
use PhpOffice\PhpSpreadsheet\Worksheet\SheetView;
21
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
22
23
// Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (used as the base for this class):
24
// -----------------------------------------------------------------------------------------
25
// /*
26
// *  Module written/ported by Xavier Noguer <[email protected]>
27
// *
28
// *  The majority of this is _NOT_ my code.  I simply ported it from the
29
// *  PERL Spreadsheet::WriteExcel module.
30
// *
31
// *  The author of the Spreadsheet::WriteExcel module is John McNamara
32
// *  <[email protected]>
33
// *
34
// *  I _DO_ maintain this code, and John McNamara has nothing to do with the
35
// *  porting of this code to PHP.  Any questions directly related to this
36
// *  class library should be directed to me.
37
// *
38
// *  License Information:
39
// *
40
// *    Spreadsheet_Excel_Writer:  A library for generating Excel Spreadsheets
41
// *    Copyright (c) 2002-2003 Xavier Noguer [email protected]
42
// *
43
// *    This library is free software; you can redistribute it and/or
44
// *    modify it under the terms of the GNU Lesser General Public
45
// *    License as published by the Free Software Foundation; either
46
// *    version 2.1 of the License, or (at your option) any later version.
47
// *
48
// *    This library is distributed in the hope that it will be useful,
49
// *    but WITHOUT ANY WARRANTY; without even the implied warranty of
50
// *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
51
// *    Lesser General Public License for more details.
52
// *
53
// *    You should have received a copy of the GNU Lesser General Public
54
// *    License along with this library; if not, write to the Free Software
55
// *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
56
// */
57
class Worksheet extends BIFFwriter
58
{
59
    /**
60
     * Formula parser.
61
     *
62
     * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Parser
63
     */
64
    private $parser;
65
66
    /**
67
     * Maximum number of characters for a string (LABEL record in BIFF5).
68
     *
69
     * @var int
70
     */
71
    private $xlsStringMaxLength;
72
73
    /**
74
     * Array containing format information for columns.
75
     *
76
     * @var array
77
     */
78
    private $columnInfo;
79
80
    /**
81
     * Array containing the selected area for the worksheet.
82
     *
83
     * @var array
84
     */
85
    private $selection;
86
87
    /**
88
     * The active pane for the worksheet.
89
     *
90
     * @var int
91
     */
92
    private $activePane;
93
94
    /**
95
     * Whether to use outline.
96
     *
97
     * @var int
98
     */
99
    private $outlineOn;
100
101
    /**
102
     * Auto outline styles.
103
     *
104
     * @var bool
105
     */
106
    private $outlineStyle;
107
108
    /**
109
     * Whether to have outline summary below.
110
     *
111
     * @var bool
112
     */
113
    private $outlineBelow;
114
115
    /**
116
     * Whether to have outline summary at the right.
117
     *
118
     * @var bool
119
     */
120
    private $outlineRight;
121
122
    /**
123
     * Reference to the total number of strings in the workbook.
124
     *
125
     * @var int
126
     */
127
    private $stringTotal;
128
129
    /**
130
     * Reference to the number of unique strings in the workbook.
131
     *
132
     * @var int
133
     */
134
    private $stringUnique;
135
136
    /**
137
     * Reference to the array containing all the unique strings in the workbook.
138
     *
139
     * @var array
140
     */
141
    private $stringTable;
142
143
    /**
144
     * Color cache.
145
     */
146
    private $colors;
147
148
    /**
149
     * Index of first used row (at least 0).
150
     *
151
     * @var int
152
     */
153
    private $firstRowIndex;
154
155
    /**
156
     * Index of last used row. (no used rows means -1).
157
     *
158
     * @var int
159
     */
160
    private $lastRowIndex;
161
162
    /**
163
     * Index of first used column (at least 0).
164
     *
165
     * @var int
166
     */
167
    private $firstColumnIndex;
168
169
    /**
170
     * Index of last used column (no used columns means -1).
171
     *
172
     * @var int
173
     */
174
    private $lastColumnIndex;
175
176
    /**
177
     * Sheet object.
178
     *
179
     * @var \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
180
     */
181
    public $phpSheet;
182
183
    /**
184
     * Count cell style Xfs.
185
     *
186
     * @var int
187
     */
188
    private $countCellStyleXfs;
189
190
    /**
191
     * Escher object corresponding to MSODRAWING.
192
     *
193
     * @var \PhpOffice\PhpSpreadsheet\Shared\Escher
194
     */
195
    private $escher;
196
197
    /**
198
     * Array of font hashes associated to FONT records index.
199
     *
200
     * @var array
201
     */
202
    public $fontHashIndex;
203
204
    /**
205
     * @var bool
206
     */
207
    private $preCalculateFormulas;
208
209
    /**
210
     * @var int
211
     */
212
    private $printHeaders;
213
214
    /**
215
     * Constructor.
216
     *
217
     * @param int $str_total Total number of strings
218
     * @param int $str_unique Total number of unique strings
219
     * @param array &$str_table String Table
220
     * @param array &$colors Colour Table
221
     * @param Parser $parser The formula parser created for the Workbook
222
     * @param bool $preCalculateFormulas Flag indicating whether formulas should be calculated or just written
223
     * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet The worksheet to write
224
     */
225
    public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, Parser $parser, $preCalculateFormulas, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet)
226
    {
227
        // It needs to call its parent's constructor explicitly
228
        parent::__construct();
229
230
        $this->preCalculateFormulas = $preCalculateFormulas;
231
        $this->stringTotal = &$str_total;
232
        $this->stringUnique = &$str_unique;
233
        $this->stringTable = &$str_table;
234
        $this->colors = &$colors;
235
        $this->parser = $parser;
236
237
        $this->phpSheet = $phpSheet;
238
239
        $this->xlsStringMaxLength = 255;
240
        $this->columnInfo = [];
241
        $this->selection = [0, 0, 0, 0];
242
        $this->activePane = 3;
243
244
        $this->printHeaders = 0;
245
246
        $this->outlineStyle = 0;
247
        $this->outlineBelow = 1;
248
        $this->outlineRight = 1;
249
        $this->outlineOn = 1;
250
251
        $this->fontHashIndex = [];
252
253
        // calculate values for DIMENSIONS record
254
        $minR = 1;
255
        $minC = 'A';
256
257
        $maxR = $this->phpSheet->getHighestRow();
258
        $maxC = $this->phpSheet->getHighestColumn();
259
260
        // Determine lowest and highest column and row
261
        $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR;
262
263
        $this->firstColumnIndex = Coordinate::columnIndexFromString($minC);
264
        $this->lastColumnIndex = Coordinate::columnIndexFromString($maxC);
265
266
//        if ($this->firstColumnIndex > 255) $this->firstColumnIndex = 255;
267
        if ($this->lastColumnIndex > 255) {
268
            $this->lastColumnIndex = 255;
269
        }
270
271
        $this->countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection());
272
    }
273
274
    /**
275
     * Add data to the beginning of the workbook (note the reverse order)
276
     * and to the end of the workbook.
277
     *
278
     * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::storeWorkbook()
279
     */
280
    public function close()
281
    {
282
        $phpSheet = $this->phpSheet;
283
284
        // Storing selected cells and active sheet because it changes while parsing cells with formulas.
285
        $selectedCells = $this->phpSheet->getSelectedCells();
286
        $activeSheetIndex = $this->phpSheet->getParent()->getActiveSheetIndex();
287
288
        // Write BOF record
289
        $this->storeBof(0x0010);
290
291
        // Write PRINTHEADERS
292
        $this->writePrintHeaders();
293
294
        // Write PRINTGRIDLINES
295
        $this->writePrintGridlines();
296
297
        // Write GRIDSET
298
        $this->writeGridset();
299
300
        // Calculate column widths
301
        $phpSheet->calculateColumnWidths();
302
303
        // Column dimensions
304
        if (($defaultWidth = $phpSheet->getDefaultColumnDimension()->getWidth()) < 0) {
305
            $defaultWidth = \PhpOffice\PhpSpreadsheet\Shared\Font::getDefaultColumnWidthByFont($phpSheet->getParent()->getDefaultStyle()->getFont());
306
        }
307
308
        $columnDimensions = $phpSheet->getColumnDimensions();
309
        $maxCol = $this->lastColumnIndex - 1;
310
        for ($i = 0; $i <= $maxCol; ++$i) {
311
            $hidden = 0;
312
            $level = 0;
313
            $xfIndex = 15; // there are 15 cell style Xfs
314
315
            $width = $defaultWidth;
316
317
            $columnLetter = Coordinate::stringFromColumnIndex($i + 1);
318
            if (isset($columnDimensions[$columnLetter])) {
319
                $columnDimension = $columnDimensions[$columnLetter];
320
                if ($columnDimension->getWidth() >= 0) {
321
                    $width = $columnDimension->getWidth();
322
                }
323
                $hidden = $columnDimension->getVisible() ? 0 : 1;
324
                $level = $columnDimension->getOutlineLevel();
325
                $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
326
            }
327
328
            // Components of columnInfo:
329
            // $firstcol first column on the range
330
            // $lastcol  last column on the range
331
            // $width    width to set
332
            // $xfIndex  The optional cell style Xf index to apply to the columns
333
            // $hidden   The optional hidden atribute
334
            // $level    The optional outline level
335
            $this->columnInfo[] = [$i, $i, $width, $xfIndex, $hidden, $level];
336
        }
337
338
        // Write GUTS
339
        $this->writeGuts();
340
341
        // Write DEFAULTROWHEIGHT
342
        $this->writeDefaultRowHeight();
343
        // Write WSBOOL
344
        $this->writeWsbool();
345
        // Write horizontal and vertical page breaks
346
        $this->writeBreaks();
347
        // Write page header
348
        $this->writeHeader();
349
        // Write page footer
350
        $this->writeFooter();
351
        // Write page horizontal centering
352
        $this->writeHcenter();
353
        // Write page vertical centering
354
        $this->writeVcenter();
355
        // Write left margin
356
        $this->writeMarginLeft();
357
        // Write right margin
358
        $this->writeMarginRight();
359
        // Write top margin
360
        $this->writeMarginTop();
361
        // Write bottom margin
362
        $this->writeMarginBottom();
363
        // Write page setup
364
        $this->writeSetup();
365
        // Write sheet protection
366
        $this->writeProtect();
367
        // Write SCENPROTECT
368
        $this->writeScenProtect();
369
        // Write OBJECTPROTECT
370
        $this->writeObjectProtect();
371
        // Write sheet password
372
        $this->writePassword();
373
        // Write DEFCOLWIDTH record
374
        $this->writeDefcol();
375
376
        // Write the COLINFO records if they exist
377
        if (!empty($this->columnInfo)) {
378
            $colcount = count($this->columnInfo);
379
            for ($i = 0; $i < $colcount; ++$i) {
380
                $this->writeColinfo($this->columnInfo[$i]);
381
            }
382
        }
383
        $autoFilterRange = $phpSheet->getAutoFilter()->getRange();
384
        if (!empty($autoFilterRange)) {
385
            // Write AUTOFILTERINFO
386
            $this->writeAutoFilterInfo();
387
        }
388
389
        // Write sheet dimensions
390
        $this->writeDimensions();
391
392
        // Row dimensions
393
        foreach ($phpSheet->getRowDimensions() as $rowDimension) {
394
            $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
395
            $this->writeRow($rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel());
396
        }
397
398
        // Write Cells
399
        foreach ($phpSheet->getCoordinates() as $coordinate) {
400
            $cell = $phpSheet->getCell($coordinate);
401
            $row = $cell->getRow() - 1;
402
            $column = Coordinate::columnIndexFromString($cell->getColumn()) - 1;
403
404
            // Don't break Excel break the code!
405
            if ($row > 65535 || $column > 255) {
406
                throw new WriterException('Rows or columns overflow! Excel5 has limit to 65535 rows and 255 columns. Use XLSX instead.');
407
            }
408
409
            // Write cell value
410
            $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
411
412
            $cVal = $cell->getValue();
413
            if ($cVal instanceof RichText) {
414
                $arrcRun = [];
415
                $str_len = StringHelper::countCharacters($cVal->getPlainText(), 'UTF-8');
416
                $str_pos = 0;
417
                $elements = $cVal->getRichTextElements();
418
                foreach ($elements as $element) {
419
                    // FONT Index
420
                    if ($element instanceof Run) {
421
                        $str_fontidx = $this->fontHashIndex[$element->getFont()->getHashCode()];
422
                    } else {
423
                        $str_fontidx = 0;
424
                    }
425
                    $arrcRun[] = ['strlen' => $str_pos, 'fontidx' => $str_fontidx];
426
                    // Position FROM
427
                    $str_pos += StringHelper::countCharacters($element->getText(), 'UTF-8');
428
                }
429
                $this->writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun);
430
            } else {
431
                switch ($cell->getDatatype()) {
432
                    case DataType::TYPE_STRING:
433
                    case DataType::TYPE_NULL:
434
                        if ($cVal === '' || $cVal === null) {
435
                            $this->writeBlank($row, $column, $xfIndex);
436
                        } else {
437
                            $this->writeString($row, $column, $cVal, $xfIndex);
438
                        }
439
440
                        break;
441
                    case DataType::TYPE_NUMERIC:
442
                        $this->writeNumber($row, $column, $cVal, $xfIndex);
443
444
                        break;
445
                    case DataType::TYPE_FORMULA:
446
                        $calculatedValue = $this->preCalculateFormulas ?
447
                            $cell->getCalculatedValue() : null;
448
                        if (self::WRITE_FORMULA_EXCEPTION == $this->writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue)) {
449
                            if ($calculatedValue === null) {
450
                                $calculatedValue = $cell->getCalculatedValue();
451
                            }
452
                            $calctype = gettype($calculatedValue);
453
                            switch ($calctype) {
454
                                case 'integer':
455
                                case 'double':
456
                                    $this->writeNumber($row, $column, $calculatedValue, $xfIndex);
457
458
                                    break;
459
                                case 'string':
460
                                    $this->writeString($row, $column, $calculatedValue, $xfIndex);
461
462
                                    break;
463
                                case 'boolean':
464
                                    $this->writeBoolErr($row, $column, $calculatedValue, 0, $xfIndex);
465
466
                                    break;
467
                                default:
468
                                    $this->writeString($row, $column, $cVal, $xfIndex);
469
                            }
470
                        }
471
472
                        break;
473
                    case DataType::TYPE_BOOL:
474
                        $this->writeBoolErr($row, $column, $cVal, 0, $xfIndex);
475
476
                        break;
477
                    case DataType::TYPE_ERROR:
478
                        $this->writeBoolErr($row, $column, self::mapErrorCode($cVal), 1, $xfIndex);
479
480
                        break;
481
                }
482
            }
483
        }
484
485
        // Append
486
        $this->writeMsoDrawing();
487
488
        // Restoring active sheet.
489
        $this->phpSheet->getParent()->setActiveSheetIndex($activeSheetIndex);
490
491
        // Write WINDOW2 record
492
        $this->writeWindow2();
493
494
        // Write PLV record
495
        $this->writePageLayoutView();
496
497
        // Write ZOOM record
498
        $this->writeZoom();
499
        if ($phpSheet->getFreezePane()) {
500
            $this->writePanes();
501
        }
502
503
        // Restoring selected cells.
504
        $this->phpSheet->setSelectedCells($selectedCells);
505
506
        // Write SELECTION record
507
        $this->writeSelection();
508
509
        // Write MergedCellsTable Record
510
        $this->writeMergedCells();
511
512
        // Hyperlinks
513
        foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
514
            [$column, $row] = Coordinate::coordinateFromString($coordinate);
515
516
            $url = $hyperlink->getUrl();
517
518
            if (strpos($url, 'sheet://') !== false) {
519
                // internal to current workbook
520
                $url = str_replace('sheet://', 'internal:', $url);
521
            } elseif (preg_match('/^(http:|https:|ftp:|mailto:)/', $url)) {
522
                // URL
523
            } else {
524
                // external (local file)
525
                $url = 'external:' . $url;
526
            }
527
528
            $this->writeUrl($row - 1, Coordinate::columnIndexFromString($column) - 1, $url);
529
        }
530
531
        $this->writeDataValidity();
532
        $this->writeSheetLayout();
533
534
        // Write SHEETPROTECTION record
535
        $this->writeSheetProtection();
536
        $this->writeRangeProtection();
537
538
        $arrConditionalStyles = $phpSheet->getConditionalStylesCollection();
539
        if (!empty($arrConditionalStyles)) {
540
            $arrConditional = [];
541
            // @todo CFRule & CFHeader
542
            // Write CFHEADER record
543
            $this->writeCFHeader();
544
            // Write ConditionalFormattingTable records
545
            foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) {
546
                foreach ($conditionalStyles as $conditional) {
547
                    if (
548
                        $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION
549
                        || $conditional->getConditionType() == Conditional::CONDITION_CELLIS
550
                    ) {
551
                        if (!isset($arrConditional[$conditional->getHashCode()])) {
552
                            // This hash code has been handled
553
                            $arrConditional[$conditional->getHashCode()] = true;
554
555
                            // Write CFRULE record
556
                            $this->writeCFRule($conditional);
557
                        }
558
                    }
559
                }
560
            }
561
        }
562
563
        $this->storeEof();
564
    }
565
566
    /**
567
     * Write a cell range address in BIFF8
568
     * always fixed range
569
     * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format.
570
     *
571
     * @param string $range E.g. 'A1' or 'A1:B6'
572
     *
573
     * @return string Binary data
574
     */
575
    private function writeBIFF8CellRangeAddressFixed($range)
576
    {
577
        $explodes = explode(':', $range);
578
579
        // extract first cell, e.g. 'A1'
580
        $firstCell = $explodes[0];
581
582
        // extract last cell, e.g. 'B6'
583
        if (count($explodes) == 1) {
584
            $lastCell = $firstCell;
585
        } else {
586
            $lastCell = $explodes[1];
587
        }
588
589
        $firstCellCoordinates = Coordinate::coordinateFromString($firstCell); // e.g. [0, 1]
590
        $lastCellCoordinates = Coordinate::coordinateFromString($lastCell); // e.g. [1, 6]
591
592
        return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, Coordinate::columnIndexFromString($firstCellCoordinates[0]) - 1, Coordinate::columnIndexFromString($lastCellCoordinates[0]) - 1);
593
    }
594
595
    /**
596
     * Retrieves data from memory in one chunk, or from disk in $buffer
597
     * sized chunks.
598
     *
599
     * @return string The data
600
     */
601
    public function getData()
602
    {
603
        $buffer = 4096;
604
605
        // Return data stored in memory
606
        if (isset($this->_data)) {
607
            $tmp = $this->_data;
608
            unset($this->_data);
609
610
            return $tmp;
611
        }
612
        // No data to return
613
        return false;
614
    }
615
616
    /**
617
     * Set the option to print the row and column headers on the printed page.
618
     *
619
     * @param int $print Whether to print the headers or not. Defaults to 1 (print).
620
     */
621
    public function printRowColHeaders($print = 1)
622
    {
623
        $this->printHeaders = $print;
624
    }
625
626
    /**
627
     * This method sets the properties for outlining and grouping. The defaults
628
     * correspond to Excel's defaults.
629
     *
630
     * @param bool $visible
631
     * @param bool $symbols_below
632
     * @param bool $symbols_right
633
     * @param bool $auto_style
634
     */
635
    public function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
636
    {
637
        $this->outlineOn = $visible;
638
        $this->outlineBelow = $symbols_below;
639
        $this->outlineRight = $symbols_right;
640
        $this->outlineStyle = $auto_style;
641
642
        // Ensure this is a boolean vale for Window2
643
        if ($this->outlineOn) {
644
            $this->outlineOn = 1;
645
        }
646
    }
647
648
    /**
649
     * Write a double to the specified row and column (zero indexed).
650
     * An integer can be written as a double. Excel will display an
651
     * integer. $format is optional.
652
     *
653
     * Returns  0 : normal termination
654
     *         -2 : row or column out of range
655
     *
656
     * @param int $row Zero indexed row
657
     * @param int $col Zero indexed column
658
     * @param float $num The number to write
659
     * @param mixed $xfIndex The optional XF format
660
     *
661
     * @return int
662
     */
663
    private function writeNumber($row, $col, $num, $xfIndex)
664
    {
665
        $record = 0x0203; // Record identifier
666
        $length = 0x000E; // Number of bytes to follow
667
668
        $header = pack('vv', $record, $length);
669
        $data = pack('vvv', $row, $col, $xfIndex);
670
        $xl_double = pack('d', $num);
671
        if (self::getByteOrder()) { // if it's Big Endian
672
            $xl_double = strrev($xl_double);
673
        }
674
675
        $this->append($header . $data . $xl_double);
676
677
        return 0;
678
    }
679
680
    /**
681
     * Write a LABELSST record or a LABEL record. Which one depends on BIFF version.
682
     *
683
     * @param int $row Row index (0-based)
684
     * @param int $col Column index (0-based)
685
     * @param string $str The string
686
     * @param int $xfIndex Index to XF record
687
     */
688
    private function writeString($row, $col, $str, $xfIndex)
689
    {
690
        $this->writeLabelSst($row, $col, $str, $xfIndex);
691
    }
692
693
    /**
694
     * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
695
     * It differs from writeString by the writing of rich text strings.
696
     *
697
     * @param int $row Row index (0-based)
698
     * @param int $col Column index (0-based)
699
     * @param string $str The string
700
     * @param int $xfIndex The XF format index for the cell
701
     * @param array $arrcRun Index to Font record and characters beginning
702
     */
703
    private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun)
704
    {
705
        $record = 0x00FD; // Record identifier
706
        $length = 0x000A; // Bytes to follow
707
        $str = StringHelper::UTF8toBIFF8UnicodeShort($str, $arrcRun);
708
709
        // check if string is already present
710
        if (!isset($this->stringTable[$str])) {
711
            $this->stringTable[$str] = $this->stringUnique++;
712
        }
713
        ++$this->stringTotal;
714
715
        $header = pack('vv', $record, $length);
716
        $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]);
717
        $this->append($header . $data);
718
    }
719
720
    /**
721
     * Write a string to the specified row and column (zero indexed).
722
     * This is the BIFF8 version (no 255 chars limit).
723
     * $format is optional.
724
     *
725
     * @param int $row Zero indexed row
726
     * @param int $col Zero indexed column
727
     * @param string $str The string to write
728
     * @param mixed $xfIndex The XF format index for the cell
729
     */
730
    private function writeLabelSst($row, $col, $str, $xfIndex)
731
    {
732
        $record = 0x00FD; // Record identifier
733
        $length = 0x000A; // Bytes to follow
734
735
        $str = StringHelper::UTF8toBIFF8UnicodeLong($str);
736
737
        // check if string is already present
738
        if (!isset($this->stringTable[$str])) {
739
            $this->stringTable[$str] = $this->stringUnique++;
740
        }
741
        ++$this->stringTotal;
742
743
        $header = pack('vv', $record, $length);
744
        $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]);
745
        $this->append($header . $data);
746
    }
747
748
    /**
749
     * Write a blank cell to the specified row and column (zero indexed).
750
     * A blank cell is used to specify formatting without adding a string
751
     * or a number.
752
     *
753
     * A blank cell without a format serves no purpose. Therefore, we don't write
754
     * a BLANK record unless a format is specified.
755
     *
756
     * Returns  0 : normal termination (including no format)
757
     *         -1 : insufficient number of arguments
758
     *         -2 : row or column out of range
759
     *
760
     * @param int $row Zero indexed row
761
     * @param int $col Zero indexed column
762
     * @param mixed $xfIndex The XF format index
763
     *
764
     * @return int
765
     */
766
    public function writeBlank($row, $col, $xfIndex)
767
    {
768
        $record = 0x0201; // Record identifier
769
        $length = 0x0006; // Number of bytes to follow
770
771
        $header = pack('vv', $record, $length);
772
        $data = pack('vvv', $row, $col, $xfIndex);
773
        $this->append($header . $data);
774
775
        return 0;
776
    }
777
778
    /**
779
     * Write a boolean or an error type to the specified row and column (zero indexed).
780
     *
781
     * @param int $row Row index (0-based)
782
     * @param int $col Column index (0-based)
783
     * @param int $value
784
     * @param bool $isError Error or Boolean?
785
     * @param int $xfIndex
786
     *
787
     * @return int
788
     */
789
    private function writeBoolErr($row, $col, $value, $isError, $xfIndex)
790
    {
791
        $record = 0x0205;
792
        $length = 8;
793
794
        $header = pack('vv', $record, $length);
795
        $data = pack('vvvCC', $row, $col, $xfIndex, $value, $isError);
796
        $this->append($header . $data);
797
798
        return 0;
799
    }
800
801
    const WRITE_FORMULA_NORMAL = 0;
802
    const WRITE_FORMULA_ERRORS = -1;
803
    const WRITE_FORMULA_RANGE = -2;
804
    const WRITE_FORMULA_EXCEPTION = -3;
805
806
    /**
807
     * Write a formula to the specified row and column (zero indexed).
808
     * The textual representation of the formula is passed to the parser in
809
     * Parser.php which returns a packed binary string.
810
     *
811
     * Returns  0 : WRITE_FORMULA_NORMAL  normal termination
812
     *         -1 : WRITE_FORMULA_ERRORS formula errors (bad formula)
813
     *         -2 : WRITE_FORMULA_RANGE  row or column out of range
814
     *         -3 : WRITE_FORMULA_EXCEPTION parse raised exception, probably due to definedname
815
     *
816
     * @param int $row Zero indexed row
817
     * @param int $col Zero indexed column
818
     * @param string $formula The formula text string
819
     * @param mixed $xfIndex The XF format index
820
     * @param mixed $calculatedValue Calculated value
821
     *
822
     * @return int
823
     */
824
    private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue)
825
    {
826
        $record = 0x0006; // Record identifier
827
828
        // Initialize possible additional value for STRING record that should be written after the FORMULA record?
829
        $stringValue = null;
830
831
        // calculated value
832
        if (isset($calculatedValue)) {
833
            // Since we can't yet get the data type of the calculated value,
834
            // we use best effort to determine data type
835
            if (is_bool($calculatedValue)) {
836
                // Boolean value
837
                $num = pack('CCCvCv', 0x01, 0x00, (int) $calculatedValue, 0x00, 0x00, 0xFFFF);
838
            } elseif (is_int($calculatedValue) || is_float($calculatedValue)) {
839
                // Numeric value
840
                $num = pack('d', $calculatedValue);
841
            } elseif (is_string($calculatedValue)) {
842
                $errorCodes = DataType::getErrorCodes();
843
                if (isset($errorCodes[$calculatedValue])) {
844
                    // Error value
845
                    $num = pack('CCCvCv', 0x02, 0x00, self::mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF);
846
                } elseif ($calculatedValue === '') {
847
                    // Empty string (and BIFF8)
848
                    $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
849
                } else {
850
                    // Non-empty string value (or empty string BIFF5)
851
                    $stringValue = $calculatedValue;
852
                    $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
853
                }
854
            } else {
855
                // We are really not supposed to reach here
856
                $num = pack('d', 0x00);
857
            }
858
        } else {
859
            $num = pack('d', 0x00);
860
        }
861
862
        $grbit = 0x03; // Option flags
863
        $unknown = 0x0000; // Must be zero
864
865
        // Strip the '=' or '@' sign at the beginning of the formula string
866
        if ($formula[0] == '=') {
867
            $formula = substr($formula, 1);
868
        } else {
869
            // Error handling
870
            $this->writeString($row, $col, 'Unrecognised character for formula', 0);
871
872
            return self::WRITE_FORMULA_ERRORS;
873
        }
874
875
        // Parse the formula using the parser in Parser.php
876
        try {
877
            $error = $this->parser->parse($formula);
878
            $formula = $this->parser->toReversePolish();
879
880
            $formlen = strlen($formula); // Length of the binary string
881
            $length = 0x16 + $formlen; // Length of the record data
882
883
            $header = pack('vv', $record, $length);
884
885
            $data = pack('vvv', $row, $col, $xfIndex)
886
                        . $num
887
                        . pack('vVv', $grbit, $unknown, $formlen);
888
            $this->append($header . $data . $formula);
889
890
            // Append also a STRING record if necessary
891
            if ($stringValue !== null) {
892
                $this->writeStringRecord($stringValue);
893
            }
894
895
            return self::WRITE_FORMULA_NORMAL;
896
        } catch (PhpSpreadsheetException $e) {
897
            return self::WRITE_FORMULA_EXCEPTION;
898
        }
899
    }
900
901
    /**
902
     * Write a STRING record. This.
903
     *
904
     * @param string $stringValue
905
     */
906
    private function writeStringRecord($stringValue)
907
    {
908
        $record = 0x0207; // Record identifier
909
        $data = StringHelper::UTF8toBIFF8UnicodeLong($stringValue);
910
911
        $length = strlen($data);
912
        $header = pack('vv', $record, $length);
913
914
        $this->append($header . $data);
915
    }
916
917
    /**
918
     * Write a hyperlink.
919
     * This is comprised of two elements: the visible label and
920
     * the invisible link. The visible label is the same as the link unless an
921
     * alternative string is specified. The label is written using the
922
     * writeString() method. Therefore the 255 characters string limit applies.
923
     * $string and $format are optional.
924
     *
925
     * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
926
     * directory url.
927
     *
928
     * Returns  0 : normal termination
929
     *         -2 : row or column out of range
930
     *         -3 : long string truncated to 255 chars
931
     *
932
     * @param int $row Row
933
     * @param int $col Column
934
     * @param string $url URL string
935
     *
936
     * @return int
937
     */
938
    private function writeUrl($row, $col, $url)
939
    {
940
        // Add start row and col to arg list
941
        return $this->writeUrlRange($row, $col, $row, $col, $url);
942
    }
943
944
    /**
945
     * This is the more general form of writeUrl(). It allows a hyperlink to be
946
     * written to a range of cells. This function also decides the type of hyperlink
947
     * to be written. These are either, Web (http, ftp, mailto), Internal
948
     * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
949
     *
950
     * @see writeUrl()
951
     *
952
     * @param int $row1 Start row
953
     * @param int $col1 Start column
954
     * @param int $row2 End row
955
     * @param int $col2 End column
956
     * @param string $url URL string
957
     *
958
     * @return int
959
     */
960
    public function writeUrlRange($row1, $col1, $row2, $col2, $url)
961
    {
962
        // Check for internal/external sheet links or default to web link
963
        if (preg_match('[^internal:]', $url)) {
964
            return $this->writeUrlInternal($row1, $col1, $row2, $col2, $url);
965
        }
966
        if (preg_match('[^external:]', $url)) {
967
            return $this->writeUrlExternal($row1, $col1, $row2, $col2, $url);
968
        }
969
970
        return $this->writeUrlWeb($row1, $col1, $row2, $col2, $url);
971
    }
972
973
    /**
974
     * Used to write http, ftp and mailto hyperlinks.
975
     * The link type ($options) is 0x03 is the same as absolute dir ref without
976
     * sheet. However it is differentiated by the $unknown2 data stream.
977
     *
978
     * @see writeUrl()
979
     *
980
     * @param int $row1 Start row
981
     * @param int $col1 Start column
982
     * @param int $row2 End row
983
     * @param int $col2 End column
984
     * @param string $url URL string
985
     *
986
     * @return int
987
     */
988
    public function writeUrlWeb($row1, $col1, $row2, $col2, $url)
989
    {
990
        $record = 0x01B8; // Record identifier
991
        $length = 0x00000; // Bytes to follow
992
993
        // Pack the undocumented parts of the hyperlink stream
994
        $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000');
995
        $unknown2 = pack('H*', 'E0C9EA79F9BACE118C8200AA004BA90B');
996
997
        // Pack the option flags
998
        $options = pack('V', 0x03);
999
1000
        // Convert URL to a null terminated wchar string
1001
        $url = implode("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
1002
        $url = $url . "\0\0\0";
1003
1004
        // Pack the length of the URL
1005
        $url_len = pack('V', strlen($url));
1006
1007
        // Calculate the data length
1008
        $length = 0x34 + strlen($url);
1009
1010
        // Pack the header data
1011
        $header = pack('vv', $record, $length);
1012
        $data = pack('vvvv', $row1, $row2, $col1, $col2);
1013
1014
        // Write the packed data
1015
        $this->append($header . $data . $unknown1 . $options . $unknown2 . $url_len . $url);
1016
1017
        return 0;
1018
    }
1019
1020
    /**
1021
     * Used to write internal reference hyperlinks such as "Sheet1!A1".
1022
     *
1023
     * @see writeUrl()
1024
     *
1025
     * @param int $row1 Start row
1026
     * @param int $col1 Start column
1027
     * @param int $row2 End row
1028
     * @param int $col2 End column
1029
     * @param string $url URL string
1030
     *
1031
     * @return int
1032
     */
1033
    public function writeUrlInternal($row1, $col1, $row2, $col2, $url)
1034
    {
1035
        $record = 0x01B8; // Record identifier
1036
        $length = 0x00000; // Bytes to follow
1037
1038
        // Strip URL type
1039
        $url = preg_replace('/^internal:/', '', $url);
1040
1041
        // Pack the undocumented parts of the hyperlink stream
1042
        $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000');
1043
1044
        // Pack the option flags
1045
        $options = pack('V', 0x08);
1046
1047
        // Convert the URL type and to a null terminated wchar string
1048
        $url .= "\0";
1049
1050
        // character count
1051
        $url_len = StringHelper::countCharacters($url);
1052
        $url_len = pack('V', $url_len);
1053
1054
        $url = StringHelper::convertEncoding($url, 'UTF-16LE', 'UTF-8');
1055
1056
        // Calculate the data length
1057
        $length = 0x24 + strlen($url);
1058
1059
        // Pack the header data
1060
        $header = pack('vv', $record, $length);
1061
        $data = pack('vvvv', $row1, $row2, $col1, $col2);
1062
1063
        // Write the packed data
1064
        $this->append($header . $data . $unknown1 . $options . $url_len . $url);
1065
1066
        return 0;
1067
    }
1068
1069
    /**
1070
     * Write links to external directory names such as 'c:\foo.xls',
1071
     * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
1072
     *
1073
     * Note: Excel writes some relative links with the $dir_long string. We ignore
1074
     * these cases for the sake of simpler code.
1075
     *
1076
     * @see writeUrl()
1077
     *
1078
     * @param int $row1 Start row
1079
     * @param int $col1 Start column
1080
     * @param int $row2 End row
1081
     * @param int $col2 End column
1082
     * @param string $url URL string
1083
     *
1084
     * @return int
1085
     */
1086
    public function writeUrlExternal($row1, $col1, $row2, $col2, $url)
1087
    {
1088
        // Network drives are different. We will handle them separately
1089
        // MS/Novell network drives and shares start with \\
1090
        if (preg_match('[^external:\\\\]', $url)) {
1091
            return; //($this->writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
1092
        }
1093
1094
        $record = 0x01B8; // Record identifier
1095
        $length = 0x00000; // Bytes to follow
1096
1097
        // Strip URL type and change Unix dir separator to Dos style (if needed)
1098
        //
1099
        $url = preg_replace('/^external:/', '', $url);
1100
        $url = preg_replace('/\//', '\\', $url);
1101
1102
        // Determine if the link is relative or absolute:
1103
        //   relative if link contains no dir separator, "somefile.xls"
1104
        //   relative if link starts with up-dir, "..\..\somefile.xls"
1105
        //   otherwise, absolute
1106
1107
        $absolute = 0x00; // relative path
1108
        if (preg_match('/^[A-Z]:/', $url)) {
1109
            $absolute = 0x02; // absolute path on Windows, e.g. C:\...
1110
        }
1111
        $link_type = 0x01 | $absolute;
1112
1113
        // Determine if the link contains a sheet reference and change some of the
1114
        // parameters accordingly.
1115
        // Split the dir name and sheet name (if it exists)
1116
        $dir_long = $url;
1117
        if (preg_match('/\\#/', $url)) {
1118
            $link_type |= 0x08;
1119
        }
1120
1121
        // Pack the link type
1122
        $link_type = pack('V', $link_type);
1123
1124
        // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
1125
        $up_count = preg_match_all('/\\.\\.\\\\/', $dir_long, $useless);
1126
        $up_count = pack('v', $up_count);
1127
1128
        // Store the short dos dir name (null terminated)
1129
        $dir_short = preg_replace('/\\.\\.\\\\/', '', $dir_long) . "\0";
1130
1131
        // Store the long dir name as a wchar string (non-null terminated)
1132
        $dir_long = $dir_long . "\0";
1133
1134
        // Pack the lengths of the dir strings
1135
        $dir_short_len = pack('V', strlen($dir_short));
1136
        $dir_long_len = pack('V', strlen($dir_long));
1137
        $stream_len = pack('V', 0); //strlen($dir_long) + 0x06);
1138
1139
        // Pack the undocumented parts of the hyperlink stream
1140
        $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000');
1141
        $unknown2 = pack('H*', '0303000000000000C000000000000046');
1142
        $unknown3 = pack('H*', 'FFFFADDE000000000000000000000000000000000000000');
1143
        $unknown4 = pack('v', 0x03);
1144
1145
        // Pack the main data stream
1146
        $data = pack('vvvv', $row1, $row2, $col1, $col2) .
1147
                            $unknown1 .
1148
                            $link_type .
1149
                            $unknown2 .
1150
                            $up_count .
1151
                            $dir_short_len .
1152
                            $dir_short .
1153
                            $unknown3 .
1154
                            $stream_len; /*.
1155
                          $dir_long_len .
1156
                          $unknown4     .
1157
                          $dir_long     .
1158
                          $sheet_len    .
1159
                          $sheet        ;*/
1160
1161
        // Pack the header data
1162
        $length = strlen($data);
1163
        $header = pack('vv', $record, $length);
1164
1165
        // Write the packed data
1166
        $this->append($header . $data);
1167
1168
        return 0;
1169
    }
1170
1171
    /**
1172
     * This method is used to set the height and format for a row.
1173
     *
1174
     * @param int $row The row to set
1175
     * @param int $height Height we are giving to the row.
1176
     *                        Use null to set XF without setting height
1177
     * @param int $xfIndex The optional cell style Xf index to apply to the columns
1178
     * @param bool $hidden The optional hidden attribute
1179
     * @param int $level The optional outline level for row, in range [0,7]
1180
     */
1181
    private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0)
1182
    {
1183
        $record = 0x0208; // Record identifier
1184
        $length = 0x0010; // Number of bytes to follow
1185
1186
        $colMic = 0x0000; // First defined column
1187
        $colMac = 0x0000; // Last defined column
1188
        $irwMac = 0x0000; // Used by Excel to optimise loading
1189
        $reserved = 0x0000; // Reserved
1190
        $grbit = 0x0000; // Option flags
1191
        $ixfe = $xfIndex;
1192
1193
        if ($height < 0) {
1194
            $height = null;
1195
        }
1196
1197
        // Use writeRow($row, null, $XF) to set XF format without setting height
1198
        if ($height != null) {
1199
            $miyRw = $height * 20; // row height
1200
        } else {
1201
            $miyRw = 0xff; // default row height is 256
1202
        }
1203
1204
        // Set the options flags. fUnsynced is used to show that the font and row
1205
        // heights are not compatible. This is usually the case for WriteExcel.
1206
        // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
1207
        // is collapsed. Instead it is used to indicate that the previous row is
1208
        // collapsed. The zero height flag, 0x20, is used to collapse a row.
1209
1210
        $grbit |= $level;
1211
        if ($hidden) {
1212
            $grbit |= 0x0030;
1213
        }
1214
        if ($height !== null) {
1215
            $grbit |= 0x0040; // fUnsynced
1216
        }
1217
        if ($xfIndex !== 0xF) {
1218
            $grbit |= 0x0080;
1219
        }
1220
        $grbit |= 0x0100;
1221
1222
        $header = pack('vv', $record, $length);
1223
        $data = pack('vvvvvvvv', $row, $colMic, $colMac, $miyRw, $irwMac, $reserved, $grbit, $ixfe);
1224
        $this->append($header . $data);
1225
    }
1226
1227
    /**
1228
     * Writes Excel DIMENSIONS to define the area in which there is data.
1229
     */
1230
    private function writeDimensions()
1231
    {
1232
        $record = 0x0200; // Record identifier
1233
1234
        $length = 0x000E;
1235
        $data = pack('VVvvv', $this->firstRowIndex, $this->lastRowIndex + 1, $this->firstColumnIndex, $this->lastColumnIndex + 1, 0x0000); // reserved
1236
1237
        $header = pack('vv', $record, $length);
1238
        $this->append($header . $data);
1239
    }
1240
1241
    /**
1242
     * Write BIFF record Window2.
1243
     */
1244
    private function writeWindow2()
1245
    {
1246
        $record = 0x023E; // Record identifier
1247
        $length = 0x0012;
1248
1249
        $grbit = 0x00B6; // Option flags
1250
        $rwTop = 0x0000; // Top row visible in window
1251
        $colLeft = 0x0000; // Leftmost column visible in window
1252
1253
        // The options flags that comprise $grbit
1254
        $fDspFmla = 0; // 0 - bit
1255
        $fDspGrid = $this->phpSheet->getShowGridlines() ? 1 : 0; // 1
1256
        $fDspRwCol = $this->phpSheet->getShowRowColHeaders() ? 1 : 0; // 2
1257
        $fFrozen = $this->phpSheet->getFreezePane() ? 1 : 0; // 3
1258
        $fDspZeros = 1; // 4
1259
        $fDefaultHdr = 1; // 5
1260
        $fArabic = $this->phpSheet->getRightToLeft() ? 1 : 0; // 6
1261
        $fDspGuts = $this->outlineOn; // 7
1262
        $fFrozenNoSplit = 0; // 0 - bit
1263
        // no support in PhpSpreadsheet for selected sheet, therefore sheet is only selected if it is the active sheet
1264
        $fSelected = ($this->phpSheet === $this->phpSheet->getParent()->getActiveSheet()) ? 1 : 0;
1265
        $fPageBreakPreview = $this->phpSheet->getSheetView()->getView() === SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW;
1266
1267
        $grbit = $fDspFmla;
1268
        $grbit |= $fDspGrid << 1;
1269
        $grbit |= $fDspRwCol << 2;
1270
        $grbit |= $fFrozen << 3;
1271
        $grbit |= $fDspZeros << 4;
1272
        $grbit |= $fDefaultHdr << 5;
1273
        $grbit |= $fArabic << 6;
1274
        $grbit |= $fDspGuts << 7;
1275
        $grbit |= $fFrozenNoSplit << 8;
1276
        $grbit |= $fSelected << 9; // Selected sheets.
1277
        $grbit |= $fSelected << 10; // Active sheet.
1278
        $grbit |= $fPageBreakPreview << 11;
1279
1280
        $header = pack('vv', $record, $length);
1281
        $data = pack('vvv', $grbit, $rwTop, $colLeft);
1282
1283
        // FIXME !!!
1284
        $rgbHdr = 0x0040; // Row/column heading and gridline color index
1285
        $zoom_factor_page_break = ($fPageBreakPreview ? $this->phpSheet->getSheetView()->getZoomScale() : 0x0000);
1286
        $zoom_factor_normal = $this->phpSheet->getSheetView()->getZoomScaleNormal();
1287
1288
        $data .= pack('vvvvV', $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
1289
1290
        $this->append($header . $data);
1291
    }
1292
1293
    /**
1294
     * Write BIFF record DEFAULTROWHEIGHT.
1295
     */
1296
    private function writeDefaultRowHeight()
1297
    {
1298
        $defaultRowHeight = $this->phpSheet->getDefaultRowDimension()->getRowHeight();
1299
1300
        if ($defaultRowHeight < 0) {
1301
            return;
1302
        }
1303
1304
        // convert to twips
1305
        $defaultRowHeight = (int) 20 * $defaultRowHeight;
1306
1307
        $record = 0x0225; // Record identifier
1308
        $length = 0x0004; // Number of bytes to follow
1309
1310
        $header = pack('vv', $record, $length);
1311
        $data = pack('vv', 1, $defaultRowHeight);
1312
        $this->append($header . $data);
1313
    }
1314
1315
    /**
1316
     * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
1317
     */
1318
    private function writeDefcol()
1319
    {
1320
        $defaultColWidth = 8;
1321
1322
        $record = 0x0055; // Record identifier
1323
        $length = 0x0002; // Number of bytes to follow
1324
1325
        $header = pack('vv', $record, $length);
1326
        $data = pack('v', $defaultColWidth);
1327
        $this->append($header . $data);
1328
    }
1329
1330
    /**
1331
     * Write BIFF record COLINFO to define column widths.
1332
     *
1333
     * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
1334
     * length record.
1335
     *
1336
     * @param array $col_array This is the only parameter received and is composed of the following:
1337
     *                0 => First formatted column,
1338
     *                1 => Last formatted column,
1339
     *                2 => Col width (8.43 is Excel default),
1340
     *                3 => The optional XF format of the column,
1341
     *                4 => Option flags.
1342
     *                5 => Optional outline level
1343
     */
1344
    private function writeColinfo($col_array)
1345
    {
1346
        if (isset($col_array[0])) {
1347
            $colFirst = $col_array[0];
1348
        }
1349
        if (isset($col_array[1])) {
1350
            $colLast = $col_array[1];
1351
        }
1352
        if (isset($col_array[2])) {
1353
            $coldx = $col_array[2];
1354
        } else {
1355
            $coldx = 8.43;
1356
        }
1357
        if (isset($col_array[3])) {
1358
            $xfIndex = $col_array[3];
1359
        } else {
1360
            $xfIndex = 15;
1361
        }
1362
        if (isset($col_array[4])) {
1363
            $grbit = $col_array[4];
1364
        } else {
1365
            $grbit = 0;
1366
        }
1367
        if (isset($col_array[5])) {
1368
            $level = $col_array[5];
1369
        } else {
1370
            $level = 0;
1371
        }
1372
        $record = 0x007D; // Record identifier
1373
        $length = 0x000C; // Number of bytes to follow
1374
1375
        $coldx *= 256; // Convert to units of 1/256 of a char
1376
1377
        $ixfe = $xfIndex;
1378
        $reserved = 0x0000; // Reserved
1379
1380
        $level = max(0, min($level, 7));
1381
        $grbit |= $level << 8;
1382
1383
        $header = pack('vv', $record, $length);
1384
        $data = pack('vvvvvv', $colFirst, $colLast, $coldx, $ixfe, $grbit, $reserved);
1385
        $this->append($header . $data);
1386
    }
1387
1388
    /**
1389
     * Write BIFF record SELECTION.
1390
     */
1391
    private function writeSelection()
1392
    {
1393
        // look up the selected cell range
1394
        $selectedCells = Coordinate::splitRange($this->phpSheet->getSelectedCells());
1395
        $selectedCells = $selectedCells[0];
1396
        if (count($selectedCells) == 2) {
1397
            [$first, $last] = $selectedCells;
1398
        } else {
1399
            $first = $selectedCells[0];
1400
            $last = $selectedCells[0];
1401
        }
1402
1403
        [$colFirst, $rwFirst] = Coordinate::coordinateFromString($first);
1404
        $colFirst = Coordinate::columnIndexFromString($colFirst) - 1; // base 0 column index
1405
        --$rwFirst; // base 0 row index
1406
1407
        [$colLast, $rwLast] = Coordinate::coordinateFromString($last);
1408
        $colLast = Coordinate::columnIndexFromString($colLast) - 1; // base 0 column index
1409
        --$rwLast; // base 0 row index
1410
1411
        // make sure we are not out of bounds
1412
        $colFirst = min($colFirst, 255);
1413
        $colLast = min($colLast, 255);
1414
1415
        $rwFirst = min($rwFirst, 65535);
1416
        $rwLast = min($rwLast, 65535);
1417
1418
        $record = 0x001D; // Record identifier
1419
        $length = 0x000F; // Number of bytes to follow
1420
1421
        $pnn = $this->activePane; // Pane position
1422
        $rwAct = $rwFirst; // Active row
1423
        $colAct = $colFirst; // Active column
1424
        $irefAct = 0; // Active cell ref
1425
        $cref = 1; // Number of refs
1426
1427
        if (!isset($rwLast)) {
1428
            $rwLast = $rwFirst; // Last  row in reference
1429
        }
1430
        if (!isset($colLast)) {
1431
            $colLast = $colFirst; // Last  col in reference
1432
        }
1433
1434
        // Swap last row/col for first row/col as necessary
1435
        if ($rwFirst > $rwLast) {
1436
            [$rwFirst, $rwLast] = [$rwLast, $rwFirst];
1437
        }
1438
1439
        if ($colFirst > $colLast) {
1440
            [$colFirst, $colLast] = [$colLast, $colFirst];
1441
        }
1442
1443
        $header = pack('vv', $record, $length);
1444
        $data = pack('CvvvvvvCC', $pnn, $rwAct, $colAct, $irefAct, $cref, $rwFirst, $rwLast, $colFirst, $colLast);
1445
        $this->append($header . $data);
1446
    }
1447
1448
    /**
1449
     * Store the MERGEDCELLS records for all ranges of merged cells.
1450
     */
1451
    private function writeMergedCells()
1452
    {
1453
        $mergeCells = $this->phpSheet->getMergeCells();
1454
        $countMergeCells = count($mergeCells);
1455
1456
        if ($countMergeCells == 0) {
1457
            return;
1458
        }
1459
1460
        // maximum allowed number of merged cells per record
1461
        $maxCountMergeCellsPerRecord = 1027;
1462
1463
        // record identifier
1464
        $record = 0x00E5;
1465
1466
        // counter for total number of merged cells treated so far by the writer
1467
        $i = 0;
1468
1469
        // counter for number of merged cells written in record currently being written
1470
        $j = 0;
1471
1472
        // initialize record data
1473
        $recordData = '';
1474
1475
        // loop through the merged cells
1476
        foreach ($mergeCells as $mergeCell) {
1477
            ++$i;
1478
            ++$j;
1479
1480
            // extract the row and column indexes
1481
            $range = Coordinate::splitRange($mergeCell);
1482
            [$first, $last] = $range[0];
1483
            [$firstColumn, $firstRow] = Coordinate::coordinateFromString($first);
1484
            [$lastColumn, $lastRow] = Coordinate::coordinateFromString($last);
1485
1486
            $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, Coordinate::columnIndexFromString($firstColumn) - 1, Coordinate::columnIndexFromString($lastColumn) - 1);
1487
1488
            // flush record if we have reached limit for number of merged cells, or reached final merged cell
1489
            if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) {
1490
                $recordData = pack('v', $j) . $recordData;
1491
                $length = strlen($recordData);
1492
                $header = pack('vv', $record, $length);
1493
                $this->append($header . $recordData);
1494
1495
                // initialize for next record, if any
1496
                $recordData = '';
1497
                $j = 0;
1498
            }
1499
        }
1500
    }
1501
1502
    /**
1503
     * Write SHEETLAYOUT record.
1504
     */
1505
    private function writeSheetLayout()
1506
    {
1507
        if (!$this->phpSheet->isTabColorSet()) {
1508
            return;
1509
        }
1510
1511
        $recordData = pack(
1512
            'vvVVVvv',
1513
            0x0862,
1514
            0x0000, // unused
1515
            0x00000000, // unused
1516
            0x00000000, // unused
1517
            0x00000014, // size of record data
1518
            $this->colors[$this->phpSheet->getTabColor()->getRGB()], // color index
1519
            0x0000        // unused
1520
        );
1521
1522
        $length = strlen($recordData);
1523
1524
        $record = 0x0862; // Record identifier
1525
        $header = pack('vv', $record, $length);
1526
        $this->append($header . $recordData);
1527
    }
1528
1529
    /**
1530
     * Write SHEETPROTECTION.
1531
     */
1532
    private function writeSheetProtection()
1533
    {
1534
        // record identifier
1535
        $record = 0x0867;
1536
1537
        // prepare options
1538
        $options = (int) !$this->phpSheet->getProtection()->getObjects()
1539
                    | (int) !$this->phpSheet->getProtection()->getScenarios() << 1
1540
                    | (int) !$this->phpSheet->getProtection()->getFormatCells() << 2
1541
                    | (int) !$this->phpSheet->getProtection()->getFormatColumns() << 3
1542
                    | (int) !$this->phpSheet->getProtection()->getFormatRows() << 4
1543
                    | (int) !$this->phpSheet->getProtection()->getInsertColumns() << 5
1544
                    | (int) !$this->phpSheet->getProtection()->getInsertRows() << 6
1545
                    | (int) !$this->phpSheet->getProtection()->getInsertHyperlinks() << 7
1546
                    | (int) !$this->phpSheet->getProtection()->getDeleteColumns() << 8
1547
                    | (int) !$this->phpSheet->getProtection()->getDeleteRows() << 9
1548
                    | (int) !$this->phpSheet->getProtection()->getSelectLockedCells() << 10
1549
                    | (int) !$this->phpSheet->getProtection()->getSort() << 11
1550
                    | (int) !$this->phpSheet->getProtection()->getAutoFilter() << 12
1551
                    | (int) !$this->phpSheet->getProtection()->getPivotTables() << 13
1552
                    | (int) !$this->phpSheet->getProtection()->getSelectUnlockedCells() << 14;
1553
1554
        // record data
1555
        $recordData = pack(
1556
            'vVVCVVvv',
1557
            0x0867, // repeated record identifier
1558
            0x0000, // not used
1559
            0x0000, // not used
1560
            0x00, // not used
1561
            0x01000200, // unknown data
1562
            0xFFFFFFFF, // unknown data
1563
            $options, // options
1564
            0x0000 // not used
1565
        );
1566
1567
        $length = strlen($recordData);
1568
        $header = pack('vv', $record, $length);
1569
1570
        $this->append($header . $recordData);
1571
    }
1572
1573
    /**
1574
     * Write BIFF record RANGEPROTECTION.
1575
     *
1576
     * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records
1577
     * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records
1578
     */
1579
    private function writeRangeProtection()
1580
    {
1581
        foreach ($this->phpSheet->getProtectedCells() as $range => $password) {
1582
            // number of ranges, e.g. 'A1:B3 C20:D25'
1583
            $cellRanges = explode(' ', $range);
1584
            $cref = count($cellRanges);
1585
1586
            $recordData = pack(
1587
                'vvVVvCVvVv',
1588
                0x0868,
1589
                0x00,
1590
                0x0000,
1591
                0x0000,
1592
                0x02,
1593
                0x0,
1594
                0x0000,
1595
                $cref,
1596
                0x0000,
1597
                0x00
1598
            );
1599
1600
            foreach ($cellRanges as $cellRange) {
1601
                $recordData .= $this->writeBIFF8CellRangeAddressFixed($cellRange);
1602
            }
1603
1604
            // the rgbFeat structure
1605
            $recordData .= pack(
1606
                'VV',
1607
                0x0000,
1608
                hexdec($password)
1609
            );
1610
1611
            $recordData .= StringHelper::UTF8toBIFF8UnicodeLong('p' . md5($recordData));
1612
1613
            $length = strlen($recordData);
1614
1615
            $record = 0x0868; // Record identifier
1616
            $header = pack('vv', $record, $length);
1617
            $this->append($header . $recordData);
1618
        }
1619
    }
1620
1621
    /**
1622
     * Writes the Excel BIFF PANE record.
1623
     * The panes can either be frozen or thawed (unfrozen).
1624
     * Frozen panes are specified in terms of an integer number of rows and columns.
1625
     * Thawed panes are specified in terms of Excel's units for rows and columns.
1626
     */
1627
    private function writePanes()
1628
    {
1629
        $panes = [];
1630
        if ($this->phpSheet->getFreezePane()) {
1631
            [$column, $row] = Coordinate::coordinateFromString($this->phpSheet->getFreezePane());
1632
            $panes[0] = Coordinate::columnIndexFromString($column) - 1;
1633
            $panes[1] = $row - 1;
1634
1635
            [$leftMostColumn, $topRow] = Coordinate::coordinateFromString($this->phpSheet->getTopLeftCell());
1636
            //Coordinates are zero-based in xls files
1637
            $panes[2] = $topRow - 1;
1638
            $panes[3] = Coordinate::columnIndexFromString($leftMostColumn) - 1;
1639
        } else {
1640
            // thaw panes
1641
            return;
1642
        }
1643
1644
        $x = $panes[0] ?? null;
1645
        $y = $panes[1] ?? null;
1646
        $rwTop = $panes[2] ?? null;
1647
        $colLeft = $panes[3] ?? null;
1648
        if (count($panes) > 4) { // if Active pane was received
1649
            $pnnAct = $panes[4];
1650
        } else {
1651
            $pnnAct = null;
1652
        }
1653
        $record = 0x0041; // Record identifier
1654
        $length = 0x000A; // Number of bytes to follow
1655
1656
        // Code specific to frozen or thawed panes.
1657
        if ($this->phpSheet->getFreezePane()) {
1658
            // Set default values for $rwTop and $colLeft
1659
            if (!isset($rwTop)) {
1660
                $rwTop = $y;
1661
            }
1662
            if (!isset($colLeft)) {
1663
                $colLeft = $x;
1664
            }
1665
        } else {
1666
            // Set default values for $rwTop and $colLeft
1667
            if (!isset($rwTop)) {
1668
                $rwTop = 0;
1669
            }
1670
            if (!isset($colLeft)) {
1671
                $colLeft = 0;
1672
            }
1673
1674
            // Convert Excel's row and column units to the internal units.
1675
            // The default row height is 12.75
1676
            // The default column width is 8.43
1677
            // The following slope and intersection values were interpolated.
1678
            //
1679
            $y = 20 * $y + 255;
1680
            $x = 113.879 * $x + 390;
1681
        }
1682
1683
        // Determine which pane should be active. There is also the undocumented
1684
        // option to override this should it be necessary: may be removed later.
1685
        //
1686
        if (!isset($pnnAct)) {
1687
            if ($x != 0 && $y != 0) {
1688
                $pnnAct = 0; // Bottom right
1689
            }
1690
            if ($x != 0 && $y == 0) {
1691
                $pnnAct = 1; // Top right
1692
            }
1693
            if ($x == 0 && $y != 0) {
1694
                $pnnAct = 2; // Bottom left
1695
            }
1696
            if ($x == 0 && $y == 0) {
1697
                $pnnAct = 3; // Top left
1698
            }
1699
        }
1700
1701
        $this->activePane = $pnnAct; // Used in writeSelection
1702
1703
        $header = pack('vv', $record, $length);
1704
        $data = pack('vvvvv', $x, $y, $rwTop, $colLeft, $pnnAct);
1705
        $this->append($header . $data);
1706
    }
1707
1708
    /**
1709
     * Store the page setup SETUP BIFF record.
1710
     */
1711
    private function writeSetup()
1712
    {
1713
        $record = 0x00A1; // Record identifier
1714
        $length = 0x0022; // Number of bytes to follow
1715
1716
        $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size
1717
1718
        $iScale = $this->phpSheet->getPageSetup()->getScale() ?
1719
            $this->phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor
1720
1721
        $iPageStart = 0x01; // Starting page number
1722
        $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide
1723
        $iFitHeight = (int) $this->phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high
1724
        $grbit = 0x00; // Option flags
1725
        $iRes = 0x0258; // Print resolution
1726
        $iVRes = 0x0258; // Vertical print resolution
1727
1728
        $numHdr = $this->phpSheet->getPageMargins()->getHeader(); // Header Margin
1729
1730
        $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin
1731
        $iCopies = 0x01; // Number of copies
1732
1733
        $fLeftToRight = 0x0; // Print over then down
1734
1735
        // Page orientation
1736
        $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE) ?
1737
            0x0 : 0x1;
1738
1739
        $fNoPls = 0x0; // Setup not read from printer
1740
        $fNoColor = 0x0; // Print black and white
1741
        $fDraft = 0x0; // Print draft quality
1742
        $fNotes = 0x0; // Print notes
1743
        $fNoOrient = 0x0; // Orientation not set
1744
        $fUsePage = 0x0; // Use custom starting page
1745
1746
        $grbit = $fLeftToRight;
1747
        $grbit |= $fLandscape << 1;
1748
        $grbit |= $fNoPls << 2;
1749
        $grbit |= $fNoColor << 3;
1750
        $grbit |= $fDraft << 4;
1751
        $grbit |= $fNotes << 5;
1752
        $grbit |= $fNoOrient << 6;
1753
        $grbit |= $fUsePage << 7;
1754
1755
        $numHdr = pack('d', $numHdr);
1756
        $numFtr = pack('d', $numFtr);
1757
        if (self::getByteOrder()) { // if it's Big Endian
1758
            $numHdr = strrev($numHdr);
1759
            $numFtr = strrev($numFtr);
1760
        }
1761
1762
        $header = pack('vv', $record, $length);
1763
        $data1 = pack('vvvvvvvv', $iPaperSize, $iScale, $iPageStart, $iFitWidth, $iFitHeight, $grbit, $iRes, $iVRes);
1764
        $data2 = $numHdr . $numFtr;
1765
        $data3 = pack('v', $iCopies);
1766
        $this->append($header . $data1 . $data2 . $data3);
1767
    }
1768
1769
    /**
1770
     * Store the header caption BIFF record.
1771
     */
1772
    private function writeHeader()
1773
    {
1774
        $record = 0x0014; // Record identifier
1775
1776
        /* removing for now
1777
        // need to fix character count (multibyte!)
1778
        if (strlen($this->phpSheet->getHeaderFooter()->getOddHeader()) <= 255) {
1779
            $str      = $this->phpSheet->getHeaderFooter()->getOddHeader();       // header string
1780
        } else {
1781
            $str = '';
1782
        }
1783
        */
1784
1785
        $recordData = StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddHeader());
1786
        $length = strlen($recordData);
1787
1788
        $header = pack('vv', $record, $length);
1789
1790
        $this->append($header . $recordData);
1791
    }
1792
1793
    /**
1794
     * Store the footer caption BIFF record.
1795
     */
1796
    private function writeFooter()
1797
    {
1798
        $record = 0x0015; // Record identifier
1799
1800
        /* removing for now
1801
        // need to fix character count (multibyte!)
1802
        if (strlen($this->phpSheet->getHeaderFooter()->getOddFooter()) <= 255) {
1803
            $str = $this->phpSheet->getHeaderFooter()->getOddFooter();
1804
        } else {
1805
            $str = '';
1806
        }
1807
        */
1808
1809
        $recordData = StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddFooter());
1810
        $length = strlen($recordData);
1811
1812
        $header = pack('vv', $record, $length);
1813
1814
        $this->append($header . $recordData);
1815
    }
1816
1817
    /**
1818
     * Store the horizontal centering HCENTER BIFF record.
1819
     */
1820
    private function writeHcenter()
1821
    {
1822
        $record = 0x0083; // Record identifier
1823
        $length = 0x0002; // Bytes to follow
1824
1825
        $fHCenter = $this->phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering
1826
1827
        $header = pack('vv', $record, $length);
1828
        $data = pack('v', $fHCenter);
1829
1830
        $this->append($header . $data);
1831
    }
1832
1833
    /**
1834
     * Store the vertical centering VCENTER BIFF record.
1835
     */
1836
    private function writeVcenter()
1837
    {
1838
        $record = 0x0084; // Record identifier
1839
        $length = 0x0002; // Bytes to follow
1840
1841
        $fVCenter = $this->phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering
1842
1843
        $header = pack('vv', $record, $length);
1844
        $data = pack('v', $fVCenter);
1845
        $this->append($header . $data);
1846
    }
1847
1848
    /**
1849
     * Store the LEFTMARGIN BIFF record.
1850
     */
1851
    private function writeMarginLeft()
1852
    {
1853
        $record = 0x0026; // Record identifier
1854
        $length = 0x0008; // Bytes to follow
1855
1856
        $margin = $this->phpSheet->getPageMargins()->getLeft(); // Margin in inches
1857
1858
        $header = pack('vv', $record, $length);
1859
        $data = pack('d', $margin);
1860
        if (self::getByteOrder()) { // if it's Big Endian
1861
            $data = strrev($data);
1862
        }
1863
1864
        $this->append($header . $data);
1865
    }
1866
1867
    /**
1868
     * Store the RIGHTMARGIN BIFF record.
1869
     */
1870
    private function writeMarginRight()
1871
    {
1872
        $record = 0x0027; // Record identifier
1873
        $length = 0x0008; // Bytes to follow
1874
1875
        $margin = $this->phpSheet->getPageMargins()->getRight(); // Margin in inches
1876
1877
        $header = pack('vv', $record, $length);
1878
        $data = pack('d', $margin);
1879
        if (self::getByteOrder()) { // if it's Big Endian
1880
            $data = strrev($data);
1881
        }
1882
1883
        $this->append($header . $data);
1884
    }
1885
1886
    /**
1887
     * Store the TOPMARGIN BIFF record.
1888
     */
1889
    private function writeMarginTop()
1890
    {
1891
        $record = 0x0028; // Record identifier
1892
        $length = 0x0008; // Bytes to follow
1893
1894
        $margin = $this->phpSheet->getPageMargins()->getTop(); // Margin in inches
1895
1896
        $header = pack('vv', $record, $length);
1897
        $data = pack('d', $margin);
1898
        if (self::getByteOrder()) { // if it's Big Endian
1899
            $data = strrev($data);
1900
        }
1901
1902
        $this->append($header . $data);
1903
    }
1904
1905
    /**
1906
     * Store the BOTTOMMARGIN BIFF record.
1907
     */
1908
    private function writeMarginBottom()
1909
    {
1910
        $record = 0x0029; // Record identifier
1911
        $length = 0x0008; // Bytes to follow
1912
1913
        $margin = $this->phpSheet->getPageMargins()->getBottom(); // Margin in inches
1914
1915
        $header = pack('vv', $record, $length);
1916
        $data = pack('d', $margin);
1917
        if (self::getByteOrder()) { // if it's Big Endian
1918
            $data = strrev($data);
1919
        }
1920
1921
        $this->append($header . $data);
1922
    }
1923
1924
    /**
1925
     * Write the PRINTHEADERS BIFF record.
1926
     */
1927
    private function writePrintHeaders()
1928
    {
1929
        $record = 0x002a; // Record identifier
1930
        $length = 0x0002; // Bytes to follow
1931
1932
        $fPrintRwCol = $this->printHeaders; // Boolean flag
1933
1934
        $header = pack('vv', $record, $length);
1935
        $data = pack('v', $fPrintRwCol);
1936
        $this->append($header . $data);
1937
    }
1938
1939
    /**
1940
     * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
1941
     * GRIDSET record.
1942
     */
1943
    private function writePrintGridlines()
1944
    {
1945
        $record = 0x002b; // Record identifier
1946
        $length = 0x0002; // Bytes to follow
1947
1948
        $fPrintGrid = $this->phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
1949
1950
        $header = pack('vv', $record, $length);
1951
        $data = pack('v', $fPrintGrid);
1952
        $this->append($header . $data);
1953
    }
1954
1955
    /**
1956
     * Write the GRIDSET BIFF record. Must be used in conjunction with the
1957
     * PRINTGRIDLINES record.
1958
     */
1959
    private function writeGridset()
1960
    {
1961
        $record = 0x0082; // Record identifier
1962
        $length = 0x0002; // Bytes to follow
1963
1964
        $fGridSet = !$this->phpSheet->getPrintGridlines(); // Boolean flag
1965
1966
        $header = pack('vv', $record, $length);
1967
        $data = pack('v', $fGridSet);
1968
        $this->append($header . $data);
1969
    }
1970
1971
    /**
1972
     * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet.
1973
     */
1974
    private function writeAutoFilterInfo()
1975
    {
1976
        $record = 0x009D; // Record identifier
1977
        $length = 0x0002; // Bytes to follow
1978
1979
        $rangeBounds = Coordinate::rangeBoundaries($this->phpSheet->getAutoFilter()->getRange());
1980
        $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0];
1981
1982
        $header = pack('vv', $record, $length);
1983
        $data = pack('v', $iNumFilters);
1984
        $this->append($header . $data);
1985
    }
1986
1987
    /**
1988
     * Write the GUTS BIFF record. This is used to configure the gutter margins
1989
     * where Excel outline symbols are displayed. The visibility of the gutters is
1990
     * controlled by a flag in WSBOOL.
1991
     *
1992
     * @see writeWsbool()
1993
     */
1994
    private function writeGuts()
1995
    {
1996
        $record = 0x0080; // Record identifier
1997
        $length = 0x0008; // Bytes to follow
1998
1999
        $dxRwGut = 0x0000; // Size of row gutter
2000
        $dxColGut = 0x0000; // Size of col gutter
2001
2002
        // determine maximum row outline level
2003
        $maxRowOutlineLevel = 0;
2004
        foreach ($this->phpSheet->getRowDimensions() as $rowDimension) {
2005
            $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel());
2006
        }
2007
2008
        $col_level = 0;
2009
2010
        // Calculate the maximum column outline level. The equivalent calculation
2011
        // for the row outline level is carried out in writeRow().
2012
        $colcount = count($this->columnInfo);
2013
        for ($i = 0; $i < $colcount; ++$i) {
2014
            $col_level = max($this->columnInfo[$i][5], $col_level);
2015
        }
2016
2017
        // Set the limits for the outline levels (0 <= x <= 7).
2018
        $col_level = max(0, min($col_level, 7));
2019
2020
        // The displayed level is one greater than the max outline levels
2021
        if ($maxRowOutlineLevel) {
2022
            ++$maxRowOutlineLevel;
2023
        }
2024
        if ($col_level) {
2025
            ++$col_level;
2026
        }
2027
2028
        $header = pack('vv', $record, $length);
2029
        $data = pack('vvvv', $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level);
2030
2031
        $this->append($header . $data);
2032
    }
2033
2034
    /**
2035
     * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
2036
     * with the SETUP record.
2037
     */
2038
    private function writeWsbool()
2039
    {
2040
        $record = 0x0081; // Record identifier
2041
        $length = 0x0002; // Bytes to follow
2042
        $grbit = 0x0000;
2043
2044
        // The only option that is of interest is the flag for fit to page. So we
2045
        // set all the options in one go.
2046
        //
2047
        // Set the option flags
2048
        $grbit |= 0x0001; // Auto page breaks visible
2049
        if ($this->outlineStyle) {
2050
            $grbit |= 0x0020; // Auto outline styles
2051
        }
2052
        if ($this->phpSheet->getShowSummaryBelow()) {
2053
            $grbit |= 0x0040; // Outline summary below
2054
        }
2055
        if ($this->phpSheet->getShowSummaryRight()) {
2056
            $grbit |= 0x0080; // Outline summary right
2057
        }
2058
        if ($this->phpSheet->getPageSetup()->getFitToPage()) {
2059
            $grbit |= 0x0100; // Page setup fit to page
2060
        }
2061
        if ($this->outlineOn) {
2062
            $grbit |= 0x0400; // Outline symbols displayed
2063
        }
2064
2065
        $header = pack('vv', $record, $length);
2066
        $data = pack('v', $grbit);
2067
        $this->append($header . $data);
2068
    }
2069
2070
    /**
2071
     * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records.
2072
     */
2073
    private function writeBreaks()
2074
    {
2075
        // initialize
2076
        $vbreaks = [];
2077
        $hbreaks = [];
2078
2079
        foreach ($this->phpSheet->getBreaks() as $cell => $breakType) {
2080
            // Fetch coordinates
2081
            $coordinates = Coordinate::coordinateFromString($cell);
2082
2083
            // Decide what to do by the type of break
2084
            switch ($breakType) {
2085
                case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_COLUMN:
2086
                    // Add to list of vertical breaks
2087
                    $vbreaks[] = Coordinate::columnIndexFromString($coordinates[0]) - 1;
2088
2089
                    break;
2090
                case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW:
2091
                    // Add to list of horizontal breaks
2092
                    $hbreaks[] = $coordinates[1];
2093
2094
                    break;
2095
                case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_NONE:
2096
                default:
2097
                    // Nothing to do
2098
                    break;
2099
            }
2100
        }
2101
2102
        //horizontal page breaks
2103
        if (!empty($hbreaks)) {
2104
            // Sort and filter array of page breaks
2105
            sort($hbreaks, SORT_NUMERIC);
2106
            if ($hbreaks[0] == 0) { // don't use first break if it's 0
2107
                array_shift($hbreaks);
2108
            }
2109
2110
            $record = 0x001b; // Record identifier
2111
            $cbrk = count($hbreaks); // Number of page breaks
2112
            $length = 2 + 6 * $cbrk; // Bytes to follow
2113
2114
            $header = pack('vv', $record, $length);
2115
            $data = pack('v', $cbrk);
2116
2117
            // Append each page break
2118
            foreach ($hbreaks as $hbreak) {
2119
                $data .= pack('vvv', $hbreak, 0x0000, 0x00ff);
2120
            }
2121
2122
            $this->append($header . $data);
2123
        }
2124
2125
        // vertical page breaks
2126
        if (!empty($vbreaks)) {
2127
            // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
2128
            // It is slightly higher in Excel 97/200, approx. 1026
2129
            $vbreaks = array_slice($vbreaks, 0, 1000);
2130
2131
            // Sort and filter array of page breaks
2132
            sort($vbreaks, SORT_NUMERIC);
2133
            if ($vbreaks[0] == 0) { // don't use first break if it's 0
2134
                array_shift($vbreaks);
2135
            }
2136
2137
            $record = 0x001a; // Record identifier
2138
            $cbrk = count($vbreaks); // Number of page breaks
2139
            $length = 2 + 6 * $cbrk; // Bytes to follow
2140
2141
            $header = pack('vv', $record, $length);
2142
            $data = pack('v', $cbrk);
2143
2144
            // Append each page break
2145
            foreach ($vbreaks as $vbreak) {
2146
                $data .= pack('vvv', $vbreak, 0x0000, 0xffff);
2147
            }
2148
2149
            $this->append($header . $data);
2150
        }
2151
    }
2152
2153
    /**
2154
     * Set the Biff PROTECT record to indicate that the worksheet is protected.
2155
     */
2156
    private function writeProtect()
2157
    {
2158
        // Exit unless sheet protection has been specified
2159
        if (!$this->phpSheet->getProtection()->getSheet()) {
2160
            return;
2161
        }
2162
2163
        $record = 0x0012; // Record identifier
2164
        $length = 0x0002; // Bytes to follow
2165
2166
        $fLock = 1; // Worksheet is protected
2167
2168
        $header = pack('vv', $record, $length);
2169
        $data = pack('v', $fLock);
2170
2171
        $this->append($header . $data);
2172
    }
2173
2174
    /**
2175
     * Write SCENPROTECT.
2176
     */
2177
    private function writeScenProtect()
2178
    {
2179
        // Exit if sheet protection is not active
2180
        if (!$this->phpSheet->getProtection()->getSheet()) {
2181
            return;
2182
        }
2183
2184
        // Exit if scenarios are not protected
2185
        if (!$this->phpSheet->getProtection()->getScenarios()) {
2186
            return;
2187
        }
2188
2189
        $record = 0x00DD; // Record identifier
2190
        $length = 0x0002; // Bytes to follow
2191
2192
        $header = pack('vv', $record, $length);
2193
        $data = pack('v', 1);
2194
2195
        $this->append($header . $data);
2196
    }
2197
2198
    /**
2199
     * Write OBJECTPROTECT.
2200
     */
2201
    private function writeObjectProtect()
2202
    {
2203
        // Exit if sheet protection is not active
2204
        if (!$this->phpSheet->getProtection()->getSheet()) {
2205
            return;
2206
        }
2207
2208
        // Exit if objects are not protected
2209
        if (!$this->phpSheet->getProtection()->getObjects()) {
2210
            return;
2211
        }
2212
2213
        $record = 0x0063; // Record identifier
2214
        $length = 0x0002; // Bytes to follow
2215
2216
        $header = pack('vv', $record, $length);
2217
        $data = pack('v', 1);
2218
2219
        $this->append($header . $data);
2220
    }
2221
2222
    /**
2223
     * Write the worksheet PASSWORD record.
2224
     */
2225
    private function writePassword()
2226
    {
2227
        // Exit unless sheet protection and password have been specified
2228
        if (!$this->phpSheet->getProtection()->getSheet() || !$this->phpSheet->getProtection()->getPassword()) {
2229
            return;
2230
        }
2231
2232
        $record = 0x0013; // Record identifier
2233
        $length = 0x0002; // Bytes to follow
2234
2235
        $wPassword = hexdec($this->phpSheet->getProtection()->getPassword()); // Encoded password
2236
2237
        $header = pack('vv', $record, $length);
2238
        $data = pack('v', $wPassword);
2239
2240
        $this->append($header . $data);
2241
    }
2242
2243
    /**
2244
     * Insert a 24bit bitmap image in a worksheet.
2245
     *
2246
     * @param int $row The row we are going to insert the bitmap into
2247
     * @param int $col The column we are going to insert the bitmap into
2248
     * @param mixed $bitmap The bitmap filename or GD-image resource
2249
     * @param int $x the horizontal position (offset) of the image inside the cell
2250
     * @param int $y the vertical position (offset) of the image inside the cell
2251
     * @param float $scale_x The horizontal scale
2252
     * @param float $scale_y The vertical scale
2253
     */
2254
    public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
2255
    {
2256
        $bitmap_array = (is_resource($bitmap) ? $this->processBitmapGd($bitmap) : $this->processBitmap($bitmap));
2257
        [$width, $height, $size, $data] = $bitmap_array;
2258
2259
        // Scale the frame of the image.
2260
        $width *= $scale_x;
2261
        $height *= $scale_y;
2262
2263
        // Calculate the vertices of the image and write the OBJ record
2264
        $this->positionImage($col, $row, $x, $y, $width, $height);
2265
2266
        // Write the IMDATA record to store the bitmap data
2267
        $record = 0x007f;
2268
        $length = 8 + $size;
2269
        $cf = 0x09;
2270
        $env = 0x01;
2271
        $lcb = $size;
2272
2273
        $header = pack('vvvvV', $record, $length, $cf, $env, $lcb);
2274
        $this->append($header . $data);
2275
    }
2276
2277
    /**
2278
     * Calculate the vertices that define the position of the image as required by
2279
     * the OBJ record.
2280
     *
2281
     *         +------------+------------+
2282
     *         |     A      |      B     |
2283
     *   +-----+------------+------------+
2284
     *   |     |(x1,y1)     |            |
2285
     *   |  1  |(A1)._______|______      |
2286
     *   |     |    |              |     |
2287
     *   |     |    |              |     |
2288
     *   +-----+----|    BITMAP    |-----+
2289
     *   |     |    |              |     |
2290
     *   |  2  |    |______________.     |
2291
     *   |     |            |        (B2)|
2292
     *   |     |            |     (x2,y2)|
2293
     *   +---- +------------+------------+
2294
     *
2295
     * Example of a bitmap that covers some of the area from cell A1 to cell B2.
2296
     *
2297
     * Based on the width and height of the bitmap we need to calculate 8 vars:
2298
     *     $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
2299
     * The width and height of the cells are also variable and have to be taken into
2300
     * account.
2301
     * The values of $col_start and $row_start are passed in from the calling
2302
     * function. The values of $col_end and $row_end are calculated by subtracting
2303
     * the width and height of the bitmap from the width and height of the
2304
     * underlying cells.
2305
     * The vertices are expressed as a percentage of the underlying cell width as
2306
     * follows (rhs values are in pixels):
2307
     *
2308
     *       x1 = X / W *1024
2309
     *       y1 = Y / H *256
2310
     *       x2 = (X-1) / W *1024
2311
     *       y2 = (Y-1) / H *256
2312
     *
2313
     *       Where:  X is distance from the left side of the underlying cell
2314
     *               Y is distance from the top of the underlying cell
2315
     *               W is the width of the cell
2316
     *               H is the height of the cell
2317
     * The SDK incorrectly states that the height should be expressed as a
2318
     *        percentage of 1024.
2319
     *
2320
     * @param int $col_start Col containing upper left corner of object
2321
     * @param int $row_start Row containing top left corner of object
2322
     * @param int $x1 Distance to left side of object
2323
     * @param int $y1 Distance to top of object
2324
     * @param int $width Width of image frame
2325
     * @param int $height Height of image frame
2326
     */
2327
    public function positionImage($col_start, $row_start, $x1, $y1, $width, $height)
2328
    {
2329
        // Initialise end cell to the same as the start cell
2330
        $col_end = $col_start; // Col containing lower right corner of object
2331
        $row_end = $row_start; // Row containing bottom right corner of object
2332
2333
        // Zero the specified offset if greater than the cell dimensions
2334
        if ($x1 >= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1))) {
2335
            $x1 = 0;
2336
        }
2337
        if ($y1 >= Xls::sizeRow($this->phpSheet, $row_start + 1)) {
2338
            $y1 = 0;
2339
        }
2340
2341
        $width = $width + $x1 - 1;
2342
        $height = $height + $y1 - 1;
2343
2344
        // Subtract the underlying cell widths to find the end cell of the image
2345
        while ($width >= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1))) {
2346
            $width -= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1));
2347
            ++$col_end;
2348
        }
2349
2350
        // Subtract the underlying cell heights to find the end cell of the image
2351
        while ($height >= Xls::sizeRow($this->phpSheet, $row_end + 1)) {
2352
            $height -= Xls::sizeRow($this->phpSheet, $row_end + 1);
2353
            ++$row_end;
2354
        }
2355
2356
        // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
2357
        // with zero eight or width.
2358
        //
2359
        if (Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1)) == 0) {
2360
            return;
2361
        }
2362
        if (Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)) == 0) {
2363
            return;
2364
        }
2365
        if (Xls::sizeRow($this->phpSheet, $row_start + 1) == 0) {
2366
            return;
2367
        }
2368
        if (Xls::sizeRow($this->phpSheet, $row_end + 1) == 0) {
2369
            return;
2370
        }
2371
2372
        // Convert the pixel values to the percentage value expected by Excel
2373
        $x1 = $x1 / Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1)) * 1024;
2374
        $y1 = $y1 / Xls::sizeRow($this->phpSheet, $row_start + 1) * 256;
2375
        $x2 = $width / Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)) * 1024; // Distance to right side of object
2376
        $y2 = $height / Xls::sizeRow($this->phpSheet, $row_end + 1) * 256; // Distance to bottom of object
2377
2378
        $this->writeObjPicture($col_start, $x1, $row_start, $y1, $col_end, $x2, $row_end, $y2);
2379
    }
2380
2381
    /**
2382
     * Store the OBJ record that precedes an IMDATA record. This could be generalise
2383
     * to support other Excel objects.
2384
     *
2385
     * @param int $colL Column containing upper left corner of object
2386
     * @param int $dxL Distance from left side of cell
2387
     * @param int $rwT Row containing top left corner of object
2388
     * @param int $dyT Distance from top of cell
2389
     * @param int $colR Column containing lower right corner of object
2390
     * @param int $dxR Distance from right of cell
2391
     * @param int $rwB Row containing bottom right corner of object
2392
     * @param int $dyB Distance from bottom of cell
2393
     */
2394
    private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB)
2395
    {
2396
        $record = 0x005d; // Record identifier
2397
        $length = 0x003c; // Bytes to follow
2398
2399
        $cObj = 0x0001; // Count of objects in file (set to 1)
2400
        $OT = 0x0008; // Object type. 8 = Picture
2401
        $id = 0x0001; // Object ID
2402
        $grbit = 0x0614; // Option flags
2403
2404
        $cbMacro = 0x0000; // Length of FMLA structure
2405
        $Reserved1 = 0x0000; // Reserved
2406
        $Reserved2 = 0x0000; // Reserved
2407
2408
        $icvBack = 0x09; // Background colour
2409
        $icvFore = 0x09; // Foreground colour
2410
        $fls = 0x00; // Fill pattern
2411
        $fAuto = 0x00; // Automatic fill
2412
        $icv = 0x08; // Line colour
2413
        $lns = 0xff; // Line style
2414
        $lnw = 0x01; // Line weight
2415
        $fAutoB = 0x00; // Automatic border
2416
        $frs = 0x0000; // Frame style
2417
        $cf = 0x0009; // Image format, 9 = bitmap
2418
        $Reserved3 = 0x0000; // Reserved
2419
        $cbPictFmla = 0x0000; // Length of FMLA structure
2420
        $Reserved4 = 0x0000; // Reserved
2421
        $grbit2 = 0x0001; // Option flags
2422
        $Reserved5 = 0x0000; // Reserved
2423
2424
        $header = pack('vv', $record, $length);
2425
        $data = pack('V', $cObj);
2426
        $data .= pack('v', $OT);
2427
        $data .= pack('v', $id);
2428
        $data .= pack('v', $grbit);
2429
        $data .= pack('v', $colL);
2430
        $data .= pack('v', $dxL);
2431
        $data .= pack('v', $rwT);
2432
        $data .= pack('v', $dyT);
2433
        $data .= pack('v', $colR);
2434
        $data .= pack('v', $dxR);
2435
        $data .= pack('v', $rwB);
2436
        $data .= pack('v', $dyB);
2437
        $data .= pack('v', $cbMacro);
2438
        $data .= pack('V', $Reserved1);
2439
        $data .= pack('v', $Reserved2);
2440
        $data .= pack('C', $icvBack);
2441
        $data .= pack('C', $icvFore);
2442
        $data .= pack('C', $fls);
2443
        $data .= pack('C', $fAuto);
2444
        $data .= pack('C', $icv);
2445
        $data .= pack('C', $lns);
2446
        $data .= pack('C', $lnw);
2447
        $data .= pack('C', $fAutoB);
2448
        $data .= pack('v', $frs);
2449
        $data .= pack('V', $cf);
2450
        $data .= pack('v', $Reserved3);
2451
        $data .= pack('v', $cbPictFmla);
2452
        $data .= pack('v', $Reserved4);
2453
        $data .= pack('v', $grbit2);
2454
        $data .= pack('V', $Reserved5);
2455
2456
        $this->append($header . $data);
2457
    }
2458
2459
    /**
2460
     * Convert a GD-image into the internal format.
2461
     *
2462
     * @param resource $image The image to process
2463
     *
2464
     * @return array Array with data and properties of the bitmap
2465
     */
2466
    public function processBitmapGd($image)
2467
    {
2468
        $width = imagesx($image);
2469
        $height = imagesy($image);
2470
2471
        $data = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18);
2472
        for ($j = $height; --$j;) {
2473
            for ($i = 0; $i < $width; ++$i) {
2474
                $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
2475
                foreach (['red', 'green', 'blue'] as $key) {
2476
                    $color[$key] = $color[$key] + round((255 - $color[$key]) * $color['alpha'] / 127);
2477
                }
2478
                $data .= chr($color['blue']) . chr($color['green']) . chr($color['red']);
2479
            }
2480
            if (3 * $width % 4) {
2481
                $data .= str_repeat("\x00", 4 - 3 * $width % 4);
2482
            }
2483
        }
2484
2485
        return [$width, $height, strlen($data), $data];
2486
    }
2487
2488
    /**
2489
     * Convert a 24 bit bitmap into the modified internal format used by Windows.
2490
     * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
2491
     * MSDN library.
2492
     *
2493
     * @param string $bitmap The bitmap to process
2494
     *
2495
     * @return array Array with data and properties of the bitmap
2496
     */
2497
    public function processBitmap($bitmap)
2498
    {
2499
        // Open file.
2500
        $bmp_fd = @fopen($bitmap, 'rb');
2501
        if (!$bmp_fd) {
2502
            throw new WriterException("Couldn't import $bitmap");
2503
        }
2504
2505
        // Slurp the file into a string.
2506
        $data = fread($bmp_fd, filesize($bitmap));
2507
2508
        // Check that the file is big enough to be a bitmap.
2509
        if (strlen($data) <= 0x36) {
2510
            throw new WriterException("$bitmap doesn't contain enough data.\n");
2511
        }
2512
2513
        // The first 2 bytes are used to identify the bitmap.
2514
        $identity = unpack('A2ident', $data);
2515
        if ($identity['ident'] != 'BM') {
2516
            throw new WriterException("$bitmap doesn't appear to be a valid bitmap image.\n");
2517
        }
2518
2519
        // Remove bitmap data: ID.
2520
        $data = substr($data, 2);
2521
2522
        // Read and remove the bitmap size. This is more reliable than reading
2523
        // the data size at offset 0x22.
2524
        //
2525
        $size_array = unpack('Vsa', substr($data, 0, 4));
2526
        $size = $size_array['sa'];
2527
        $data = substr($data, 4);
2528
        $size -= 0x36; // Subtract size of bitmap header.
2529
        $size += 0x0C; // Add size of BIFF header.
2530
2531
        // Remove bitmap data: reserved, offset, header length.
2532
        $data = substr($data, 12);
2533
2534
        // Read and remove the bitmap width and height. Verify the sizes.
2535
        $width_and_height = unpack('V2', substr($data, 0, 8));
2536
        $width = $width_and_height[1];
2537
        $height = $width_and_height[2];
2538
        $data = substr($data, 8);
2539
        if ($width > 0xFFFF) {
2540
            throw new WriterException("$bitmap: largest image width supported is 65k.\n");
2541
        }
2542
        if ($height > 0xFFFF) {
2543
            throw new WriterException("$bitmap: largest image height supported is 65k.\n");
2544
        }
2545
2546
        // Read and remove the bitmap planes and bpp data. Verify them.
2547
        $planes_and_bitcount = unpack('v2', substr($data, 0, 4));
2548
        $data = substr($data, 4);
2549
        if ($planes_and_bitcount[2] != 24) { // Bitcount
2550
            throw new WriterException("$bitmap isn't a 24bit true color bitmap.\n");
2551
        }
2552
        if ($planes_and_bitcount[1] != 1) {
2553
            throw new WriterException("$bitmap: only 1 plane supported in bitmap image.\n");
2554
        }
2555
2556
        // Read and remove the bitmap compression. Verify compression.
2557
        $compression = unpack('Vcomp', substr($data, 0, 4));
2558
        $data = substr($data, 4);
2559
2560
        if ($compression['comp'] != 0) {
2561
            throw new WriterException("$bitmap: compression not supported in bitmap image.\n");
2562
        }
2563
2564
        // Remove bitmap data: data size, hres, vres, colours, imp. colours.
2565
        $data = substr($data, 20);
2566
2567
        // Add the BITMAPCOREHEADER data
2568
        $header = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18);
2569
        $data = $header . $data;
2570
2571
        return [$width, $height, $size, $data];
2572
    }
2573
2574
    /**
2575
     * Store the window zoom factor. This should be a reduced fraction but for
2576
     * simplicity we will store all fractions with a numerator of 100.
2577
     */
2578
    private function writeZoom()
2579
    {
2580
        // If scale is 100 we don't need to write a record
2581
        if ($this->phpSheet->getSheetView()->getZoomScale() == 100) {
2582
            return;
2583
        }
2584
2585
        $record = 0x00A0; // Record identifier
2586
        $length = 0x0004; // Bytes to follow
2587
2588
        $header = pack('vv', $record, $length);
2589
        $data = pack('vv', $this->phpSheet->getSheetView()->getZoomScale(), 100);
2590
        $this->append($header . $data);
2591
    }
2592
2593
    /**
2594
     * Get Escher object.
2595
     *
2596
     * @return \PhpOffice\PhpSpreadsheet\Shared\Escher
2597
     */
2598
    public function getEscher()
2599
    {
2600
        return $this->escher;
2601
    }
2602
2603
    /**
2604
     * Set Escher object.
2605
     *
2606
     * @param \PhpOffice\PhpSpreadsheet\Shared\Escher $pValue
2607
     */
2608
    public function setEscher(\PhpOffice\PhpSpreadsheet\Shared\Escher $pValue = null)
2609
    {
2610
        $this->escher = $pValue;
2611
    }
2612
2613
    /**
2614
     * Write MSODRAWING record.
2615
     */
2616
    private function writeMsoDrawing()
2617
    {
2618
        // write the Escher stream if necessary
2619
        if (isset($this->escher)) {
2620
            $writer = new Escher($this->escher);
2621
            $data = $writer->close();
2622
            $spOffsets = $writer->getSpOffsets();
2623
            $spTypes = $writer->getSpTypes();
2624
            // write the neccesary MSODRAWING, OBJ records
2625
2626
            // split the Escher stream
2627
            $spOffsets[0] = 0;
2628
            $nm = count($spOffsets) - 1; // number of shapes excluding first shape
2629
            for ($i = 1; $i <= $nm; ++$i) {
2630
                // MSODRAWING record
2631
                $record = 0x00EC; // Record identifier
2632
2633
                // chunk of Escher stream for one shape
2634
                $dataChunk = substr($data, $spOffsets[$i - 1], $spOffsets[$i] - $spOffsets[$i - 1]);
2635
2636
                $length = strlen($dataChunk);
2637
                $header = pack('vv', $record, $length);
2638
2639
                $this->append($header . $dataChunk);
2640
2641
                // OBJ record
2642
                $record = 0x005D; // record identifier
2643
                $objData = '';
2644
2645
                // ftCmo
2646
                if ($spTypes[$i] == 0x00C9) {
2647
                    // Add ftCmo (common object data) subobject
2648
                    $objData .=
2649
                        pack(
2650
                            'vvvvvVVV',
2651
                            0x0015, // 0x0015 = ftCmo
2652
                            0x0012, // length of ftCmo data
2653
                            0x0014, // object type, 0x0014 = filter
2654
                            $i, // object id number, Excel seems to use 1-based index, local for the sheet
2655
                            0x2101, // option flags, 0x2001 is what OpenOffice.org uses
2656
                            0, // reserved
2657
                            0, // reserved
2658
                            0  // reserved
2659
                        );
2660
2661
                    // Add ftSbs Scroll bar subobject
2662
                    $objData .= pack('vv', 0x00C, 0x0014);
2663
                    $objData .= pack('H*', '0000000000000000640001000A00000010000100');
2664
                    // Add ftLbsData (List box data) subobject
2665
                    $objData .= pack('vv', 0x0013, 0x1FEE);
2666
                    $objData .= pack('H*', '00000000010001030000020008005700');
2667
                } else {
2668
                    // Add ftCmo (common object data) subobject
2669
                    $objData .=
2670
                        pack(
2671
                            'vvvvvVVV',
2672
                            0x0015, // 0x0015 = ftCmo
2673
                            0x0012, // length of ftCmo data
2674
                            0x0008, // object type, 0x0008 = picture
2675
                            $i, // object id number, Excel seems to use 1-based index, local for the sheet
2676
                            0x6011, // option flags, 0x6011 is what OpenOffice.org uses
2677
                            0, // reserved
2678
                            0, // reserved
2679
                            0  // reserved
2680
                        );
2681
                }
2682
2683
                // ftEnd
2684
                $objData .=
2685
                    pack(
2686
                        'vv',
2687
                        0x0000, // 0x0000 = ftEnd
2688
                        0x0000  // length of ftEnd data
2689
                    );
2690
2691
                $length = strlen($objData);
2692
                $header = pack('vv', $record, $length);
2693
                $this->append($header . $objData);
2694
            }
2695
        }
2696
    }
2697
2698
    /**
2699
     * Store the DATAVALIDATIONS and DATAVALIDATION records.
2700
     */
2701
    private function writeDataValidity()
2702
    {
2703
        // Datavalidation collection
2704
        $dataValidationCollection = $this->phpSheet->getDataValidationCollection();
2705
2706
        // Write data validations?
2707
        if (!empty($dataValidationCollection)) {
2708
            // DATAVALIDATIONS record
2709
            $record = 0x01B2; // Record identifier
2710
            $length = 0x0012; // Bytes to follow
2711
2712
            $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records
2713
            $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
2714
            $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
2715
            $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible
2716
2717
            $header = pack('vv', $record, $length);
2718
            $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, count($dataValidationCollection));
2719
            $this->append($header . $data);
2720
2721
            // DATAVALIDATION records
2722
            $record = 0x01BE; // Record identifier
2723
2724
            foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) {
2725
                // initialize record data
2726
                $data = '';
2727
2728
                // options
2729
                $options = 0x00000000;
2730
2731
                // data type
2732
                $type = 0x00;
2733
                switch ($dataValidation->getType()) {
2734
                    case DataValidation::TYPE_NONE:
2735
                        $type = 0x00;
2736
2737
                        break;
2738
                    case DataValidation::TYPE_WHOLE:
2739
                        $type = 0x01;
2740
2741
                        break;
2742
                    case DataValidation::TYPE_DECIMAL:
2743
                        $type = 0x02;
2744
2745
                        break;
2746
                    case DataValidation::TYPE_LIST:
2747
                        $type = 0x03;
2748
2749
                        break;
2750
                    case DataValidation::TYPE_DATE:
2751
                        $type = 0x04;
2752
2753
                        break;
2754
                    case DataValidation::TYPE_TIME:
2755
                        $type = 0x05;
2756
2757
                        break;
2758
                    case DataValidation::TYPE_TEXTLENGTH:
2759
                        $type = 0x06;
2760
2761
                        break;
2762
                    case DataValidation::TYPE_CUSTOM:
2763
                        $type = 0x07;
2764
2765
                        break;
2766
                }
2767
2768
                $options |= $type << 0;
2769
2770
                // error style
2771
                $errorStyle = 0x00;
2772
                switch ($dataValidation->getErrorStyle()) {
2773
                    case DataValidation::STYLE_STOP:
2774
                        $errorStyle = 0x00;
2775
2776
                        break;
2777
                    case DataValidation::STYLE_WARNING:
2778
                        $errorStyle = 0x01;
2779
2780
                        break;
2781
                    case DataValidation::STYLE_INFORMATION:
2782
                        $errorStyle = 0x02;
2783
2784
                        break;
2785
                }
2786
2787
                $options |= $errorStyle << 4;
2788
2789
                // explicit formula?
2790
                if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) {
2791
                    $options |= 0x01 << 7;
2792
                }
2793
2794
                // empty cells allowed
2795
                $options |= $dataValidation->getAllowBlank() << 8;
2796
2797
                // show drop down
2798
                $options |= (!$dataValidation->getShowDropDown()) << 9;
2799
2800
                // show input message
2801
                $options |= $dataValidation->getShowInputMessage() << 18;
2802
2803
                // show error message
2804
                $options |= $dataValidation->getShowErrorMessage() << 19;
2805
2806
                // condition operator
2807
                $operator = 0x00;
2808
                switch ($dataValidation->getOperator()) {
2809
                    case DataValidation::OPERATOR_BETWEEN:
2810
                        $operator = 0x00;
2811
2812
                        break;
2813
                    case DataValidation::OPERATOR_NOTBETWEEN:
2814
                        $operator = 0x01;
2815
2816
                        break;
2817
                    case DataValidation::OPERATOR_EQUAL:
2818
                        $operator = 0x02;
2819
2820
                        break;
2821
                    case DataValidation::OPERATOR_NOTEQUAL:
2822
                        $operator = 0x03;
2823
2824
                        break;
2825
                    case DataValidation::OPERATOR_GREATERTHAN:
2826
                        $operator = 0x04;
2827
2828
                        break;
2829
                    case DataValidation::OPERATOR_LESSTHAN:
2830
                        $operator = 0x05;
2831
2832
                        break;
2833
                    case DataValidation::OPERATOR_GREATERTHANOREQUAL:
2834
                        $operator = 0x06;
2835
2836
                        break;
2837
                    case DataValidation::OPERATOR_LESSTHANOREQUAL:
2838
                        $operator = 0x07;
2839
2840
                        break;
2841
                }
2842
2843
                $options |= $operator << 20;
2844
2845
                $data = pack('V', $options);
2846
2847
                // prompt title
2848
                $promptTitle = $dataValidation->getPromptTitle() !== '' ?
2849
                    $dataValidation->getPromptTitle() : chr(0);
2850
                $data .= StringHelper::UTF8toBIFF8UnicodeLong($promptTitle);
2851
2852
                // error title
2853
                $errorTitle = $dataValidation->getErrorTitle() !== '' ?
2854
                    $dataValidation->getErrorTitle() : chr(0);
2855
                $data .= StringHelper::UTF8toBIFF8UnicodeLong($errorTitle);
2856
2857
                // prompt text
2858
                $prompt = $dataValidation->getPrompt() !== '' ?
2859
                    $dataValidation->getPrompt() : chr(0);
2860
                $data .= StringHelper::UTF8toBIFF8UnicodeLong($prompt);
2861
2862
                // error text
2863
                $error = $dataValidation->getError() !== '' ?
2864
                    $dataValidation->getError() : chr(0);
2865
                $data .= StringHelper::UTF8toBIFF8UnicodeLong($error);
2866
2867
                // formula 1
2868
                try {
2869
                    $formula1 = $dataValidation->getFormula1();
2870
                    if ($type == 0x03) { // list type
2871
                        $formula1 = str_replace(',', chr(0), $formula1);
2872
                    }
2873
                    $this->parser->parse($formula1);
2874
                    $formula1 = $this->parser->toReversePolish();
2875
                    $sz1 = strlen($formula1);
2876
                } catch (PhpSpreadsheetException $e) {
2877
                    $sz1 = 0;
2878
                    $formula1 = '';
2879
                }
2880
                $data .= pack('vv', $sz1, 0x0000);
2881
                $data .= $formula1;
2882
2883
                // formula 2
2884
                try {
2885
                    $formula2 = $dataValidation->getFormula2();
2886
                    if ($formula2 === '') {
2887
                        throw new WriterException('No formula2');
2888
                    }
2889
                    $this->parser->parse($formula2);
2890
                    $formula2 = $this->parser->toReversePolish();
2891
                    $sz2 = strlen($formula2);
2892
                } catch (PhpSpreadsheetException $e) {
2893
                    $sz2 = 0;
2894
                    $formula2 = '';
2895
                }
2896
                $data .= pack('vv', $sz2, 0x0000);
2897
                $data .= $formula2;
2898
2899
                // cell range address list
2900
                $data .= pack('v', 0x0001);
2901
                $data .= $this->writeBIFF8CellRangeAddressFixed($cellCoordinate);
2902
2903
                $length = strlen($data);
2904
                $header = pack('vv', $record, $length);
2905
2906
                $this->append($header . $data);
2907
            }
2908
        }
2909
    }
2910
2911
    /**
2912
     * Map Error code.
2913
     *
2914
     * @param string $errorCode
2915
     *
2916
     * @return int
2917
     */
2918
    private static function mapErrorCode($errorCode)
2919
    {
2920
        switch ($errorCode) {
2921
            case '#NULL!':
2922
                return 0x00;
2923
            case '#DIV/0!':
2924
                return 0x07;
2925
            case '#VALUE!':
2926
                return 0x0F;
2927
            case '#REF!':
2928
                return 0x17;
2929
            case '#NAME?':
2930
                return 0x1D;
2931
            case '#NUM!':
2932
                return 0x24;
2933
            case '#N/A':
2934
                return 0x2A;
2935
        }
2936
2937
        return 0;
2938
    }
2939
2940
    /**
2941
     * Write PLV Record.
2942
     */
2943
    private function writePageLayoutView()
2944
    {
2945
        $record = 0x088B; // Record identifier
2946
        $length = 0x0010; // Bytes to follow
2947
2948
        $rt = 0x088B; // 2
2949
        $grbitFrt = 0x0000; // 2
2950
        $reserved = 0x0000000000000000; // 8
2951
        $wScalvePLV = $this->phpSheet->getSheetView()->getZoomScale(); // 2
2952
2953
        // The options flags that comprise $grbit
2954
        if ($this->phpSheet->getSheetView()->getView() == SheetView::SHEETVIEW_PAGE_LAYOUT) {
2955
            $fPageLayoutView = 1;
2956
        } else {
2957
            $fPageLayoutView = 0;
2958
        }
2959
        $fRulerVisible = 0;
2960
        $fWhitespaceHidden = 0;
2961
2962
        $grbit = $fPageLayoutView; // 2
2963
        $grbit |= $fRulerVisible << 1;
2964
        $grbit |= $fWhitespaceHidden << 3;
2965
2966
        $header = pack('vv', $record, $length);
2967
        $data = pack('vvVVvv', $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit);
2968
        $this->append($header . $data);
2969
    }
2970
2971
    /**
2972
     * Write CFRule Record.
2973
     *
2974
     * @param Conditional $conditional
2975
     */
2976
    private function writeCFRule(Conditional $conditional)
2977
    {
2978
        $record = 0x01B1; // Record identifier
2979
2980
        // $type : Type of the CF
2981
        // $operatorType : Comparison operator
2982
        if ($conditional->getConditionType() == Conditional::CONDITION_EXPRESSION) {
2983
            $type = 0x02;
2984
            $operatorType = 0x00;
2985
        } elseif ($conditional->getConditionType() == Conditional::CONDITION_CELLIS) {
2986
            $type = 0x01;
2987
2988
            switch ($conditional->getOperatorType()) {
2989
                case Conditional::OPERATOR_NONE:
2990
                    $operatorType = 0x00;
2991
2992
                    break;
2993
                case Conditional::OPERATOR_EQUAL:
2994
                    $operatorType = 0x03;
2995
2996
                    break;
2997
                case Conditional::OPERATOR_GREATERTHAN:
2998
                    $operatorType = 0x05;
2999
3000
                    break;
3001
                case Conditional::OPERATOR_GREATERTHANOREQUAL:
3002
                    $operatorType = 0x07;
3003
3004
                    break;
3005
                case Conditional::OPERATOR_LESSTHAN:
3006
                    $operatorType = 0x06;
3007
3008
                    break;
3009
                case Conditional::OPERATOR_LESSTHANOREQUAL:
3010
                    $operatorType = 0x08;
3011
3012
                    break;
3013
                case Conditional::OPERATOR_NOTEQUAL:
3014
                    $operatorType = 0x04;
3015
3016
                    break;
3017
                case Conditional::OPERATOR_BETWEEN:
3018
                    $operatorType = 0x01;
3019
3020
                    break;
3021
                    // not OPERATOR_NOTBETWEEN 0x02
3022
            }
3023
        }
3024
3025
        // $szValue1 : size of the formula data for first value or formula
3026
        // $szValue2 : size of the formula data for second value or formula
3027
        $arrConditions = $conditional->getConditions();
3028
        $numConditions = count($arrConditions);
3029
        if ($numConditions == 1) {
3030
            $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
3031
            $szValue2 = 0x0000;
3032
            $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
3033
            $operand2 = null;
3034
        } elseif ($numConditions == 2 && ($conditional->getOperatorType() == Conditional::OPERATOR_BETWEEN)) {
3035
            $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
3036
            $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000);
3037
            $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
3038
            $operand2 = pack('Cv', 0x1E, $arrConditions[1]);
3039
        } else {
3040
            $szValue1 = 0x0000;
3041
            $szValue2 = 0x0000;
3042
            $operand1 = null;
3043
            $operand2 = null;
3044
        }
3045
3046
        // $flags : Option flags
3047
        // Alignment
3048
        $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0);
3049
        $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0);
3050
        $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0);
3051
        $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0);
3052
        $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0);
3053
        $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0);
3054
        if ($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0) {
3055
            $bFormatAlign = 1;
3056
        } else {
3057
            $bFormatAlign = 0;
3058
        }
3059
        // Protection
3060
        $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0);
3061
        $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0);
3062
        if ($bProtLocked == 0 || $bProtHidden == 0) {
3063
            $bFormatProt = 1;
3064
        } else {
3065
            $bFormatProt = 0;
3066
        }
3067
        // Border
3068
        $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == Color::COLOR_BLACK
3069
                        && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0);
3070
        $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == Color::COLOR_BLACK
3071
                        && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0);
3072
        $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == Color::COLOR_BLACK
3073
                        && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0);
3074
        $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == Color::COLOR_BLACK
3075
                        && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0);
3076
        if ($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0) {
3077
            $bFormatBorder = 1;
3078
        } else {
3079
            $bFormatBorder = 0;
3080
        }
3081
        // Pattern
3082
        $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1);
3083
        $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1);
3084
        $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1);
3085
        if ($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0) {
3086
            $bFormatFill = 1;
3087
        } else {
3088
            $bFormatFill = 0;
3089
        }
3090
        // Font
3091
        if (
3092
            $conditional->getStyle()->getFont()->getName() != null
3093
            || $conditional->getStyle()->getFont()->getSize() != null
3094
            || $conditional->getStyle()->getFont()->getBold() != null
3095
            || $conditional->getStyle()->getFont()->getItalic() != null
3096
            || $conditional->getStyle()->getFont()->getSuperscript() != null
3097
            || $conditional->getStyle()->getFont()->getSubscript() != null
3098
            || $conditional->getStyle()->getFont()->getUnderline() != null
3099
            || $conditional->getStyle()->getFont()->getStrikethrough() != null
3100
            || $conditional->getStyle()->getFont()->getColor()->getARGB() != null
3101
        ) {
3102
            $bFormatFont = 1;
3103
        } else {
3104
            $bFormatFont = 0;
3105
        }
3106
        // Alignment
3107
        $flags = 0;
3108
        $flags |= (1 == $bAlignHz ? 0x00000001 : 0);
3109
        $flags |= (1 == $bAlignVt ? 0x00000002 : 0);
3110
        $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0);
3111
        $flags |= (1 == $bTxRotation ? 0x00000008 : 0);
3112
        // Justify last line flag
3113
        $flags |= (1 == 1 ? 0x00000010 : 0);
3114
        $flags |= (1 == $bIndent ? 0x00000020 : 0);
3115
        $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0);
3116
        // Default
3117
        $flags |= (1 == 1 ? 0x00000080 : 0);
3118
        // Protection
3119
        $flags |= (1 == $bProtLocked ? 0x00000100 : 0);
3120
        $flags |= (1 == $bProtHidden ? 0x00000200 : 0);
3121
        // Border
3122
        $flags |= (1 == $bBorderLeft ? 0x00000400 : 0);
3123
        $flags |= (1 == $bBorderRight ? 0x00000800 : 0);
3124
        $flags |= (1 == $bBorderTop ? 0x00001000 : 0);
3125
        $flags |= (1 == $bBorderBottom ? 0x00002000 : 0);
3126
        $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border
3127
        $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border
3128
        // Pattern
3129
        $flags |= (1 == $bFillStyle ? 0x00010000 : 0);
3130
        $flags |= (1 == $bFillColor ? 0x00020000 : 0);
3131
        $flags |= (1 == $bFillColorBg ? 0x00040000 : 0);
3132
        $flags |= (1 == 1 ? 0x00380000 : 0);
3133
        // Font
3134
        $flags |= (1 == $bFormatFont ? 0x04000000 : 0);
3135
        // Alignment:
3136
        $flags |= (1 == $bFormatAlign ? 0x08000000 : 0);
3137
        // Border
3138
        $flags |= (1 == $bFormatBorder ? 0x10000000 : 0);
3139
        // Pattern
3140
        $flags |= (1 == $bFormatFill ? 0x20000000 : 0);
3141
        // Protection
3142
        $flags |= (1 == $bFormatProt ? 0x40000000 : 0);
3143
        // Text direction
3144
        $flags |= (1 == 0 ? 0x80000000 : 0);
3145
3146
        // Data Blocks
3147
        if ($bFormatFont == 1) {
3148
            // Font Name
3149
            if ($conditional->getStyle()->getFont()->getName() == null) {
3150
                $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
3151
                $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
3152
            } else {
3153
                $dataBlockFont = StringHelper::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName());
3154
            }
3155
            // Font Size
3156
            if ($conditional->getStyle()->getFont()->getSize() == null) {
3157
                $dataBlockFont .= pack('V', 20 * 11);
3158
            } else {
3159
                $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize());
3160
            }
3161
            // Font Options
3162
            $dataBlockFont .= pack('V', 0);
3163
            // Font weight
3164
            if ($conditional->getStyle()->getFont()->getBold() == true) {
3165
                $dataBlockFont .= pack('v', 0x02BC);
3166
            } else {
3167
                $dataBlockFont .= pack('v', 0x0190);
3168
            }
3169
            // Escapement type
3170
            if ($conditional->getStyle()->getFont()->getSubscript() == true) {
3171
                $dataBlockFont .= pack('v', 0x02);
3172
                $fontEscapement = 0;
3173
            } elseif ($conditional->getStyle()->getFont()->getSuperscript() == true) {
3174
                $dataBlockFont .= pack('v', 0x01);
3175
                $fontEscapement = 0;
3176
            } else {
3177
                $dataBlockFont .= pack('v', 0x00);
3178
                $fontEscapement = 1;
3179
            }
3180
            // Underline type
3181
            switch ($conditional->getStyle()->getFont()->getUnderline()) {
3182
                case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE:
3183
                    $dataBlockFont .= pack('C', 0x00);
3184
                    $fontUnderline = 0;
3185
3186
                    break;
3187
                case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE:
3188
                    $dataBlockFont .= pack('C', 0x02);
3189
                    $fontUnderline = 0;
3190
3191
                    break;
3192
                case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING:
3193
                    $dataBlockFont .= pack('C', 0x22);
3194
                    $fontUnderline = 0;
3195
3196
                    break;
3197
                case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE:
3198
                    $dataBlockFont .= pack('C', 0x01);
3199
                    $fontUnderline = 0;
3200
3201
                    break;
3202
                case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING:
3203
                    $dataBlockFont .= pack('C', 0x21);
3204
                    $fontUnderline = 0;
3205
3206
                    break;
3207
                default:
3208
                    $dataBlockFont .= pack('C', 0x00);
3209
                    $fontUnderline = 1;
3210
3211
                    break;
3212
            }
3213
            // Not used (3)
3214
            $dataBlockFont .= pack('vC', 0x0000, 0x00);
3215
            // Font color index
3216
            switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) {
3217
                case '000000':
3218
                    $colorIdx = 0x08;
3219
3220
                    break;
3221
                case 'FFFFFF':
3222
                    $colorIdx = 0x09;
3223
3224
                    break;
3225
                case 'FF0000':
3226
                    $colorIdx = 0x0A;
3227
3228
                    break;
3229
                case '00FF00':
3230
                    $colorIdx = 0x0B;
3231
3232
                    break;
3233
                case '0000FF':
3234
                    $colorIdx = 0x0C;
3235
3236
                    break;
3237
                case 'FFFF00':
3238
                    $colorIdx = 0x0D;
3239
3240
                    break;
3241
                case 'FF00FF':
3242
                    $colorIdx = 0x0E;
3243
3244
                    break;
3245
                case '00FFFF':
3246
                    $colorIdx = 0x0F;
3247
3248
                    break;
3249
                case '800000':
3250
                    $colorIdx = 0x10;
3251
3252
                    break;
3253
                case '008000':
3254
                    $colorIdx = 0x11;
3255
3256
                    break;
3257
                case '000080':
3258
                    $colorIdx = 0x12;
3259
3260
                    break;
3261
                case '808000':
3262
                    $colorIdx = 0x13;
3263
3264
                    break;
3265
                case '800080':
3266
                    $colorIdx = 0x14;
3267
3268
                    break;
3269
                case '008080':
3270
                    $colorIdx = 0x15;
3271
3272
                    break;
3273
                case 'C0C0C0':
3274
                    $colorIdx = 0x16;
3275
3276
                    break;
3277
                case '808080':
3278
                    $colorIdx = 0x17;
3279
3280
                    break;
3281
                case '9999FF':
3282
                    $colorIdx = 0x18;
3283
3284
                    break;
3285
                case '993366':
3286
                    $colorIdx = 0x19;
3287
3288
                    break;
3289
                case 'FFFFCC':
3290
                    $colorIdx = 0x1A;
3291
3292
                    break;
3293
                case 'CCFFFF':
3294
                    $colorIdx = 0x1B;
3295
3296
                    break;
3297
                case '660066':
3298
                    $colorIdx = 0x1C;
3299
3300
                    break;
3301
                case 'FF8080':
3302
                    $colorIdx = 0x1D;
3303
3304
                    break;
3305
                case '0066CC':
3306
                    $colorIdx = 0x1E;
3307
3308
                    break;
3309
                case 'CCCCFF':
3310
                    $colorIdx = 0x1F;
3311
3312
                    break;
3313
                case '000080':
3314
                    $colorIdx = 0x20;
3315
3316
                    break;
3317
                case 'FF00FF':
3318
                    $colorIdx = 0x21;
3319
3320
                    break;
3321
                case 'FFFF00':
3322
                    $colorIdx = 0x22;
3323
3324
                    break;
3325
                case '00FFFF':
3326
                    $colorIdx = 0x23;
3327
3328
                    break;
3329
                case '800080':
3330
                    $colorIdx = 0x24;
3331
3332
                    break;
3333
                case '800000':
3334
                    $colorIdx = 0x25;
3335
3336
                    break;
3337
                case '008080':
3338
                    $colorIdx = 0x26;
3339
3340
                    break;
3341
                case '0000FF':
3342
                    $colorIdx = 0x27;
3343
3344
                    break;
3345
                case '00CCFF':
3346
                    $colorIdx = 0x28;
3347
3348
                    break;
3349
                case 'CCFFFF':
3350
                    $colorIdx = 0x29;
3351
3352
                    break;
3353
                case 'CCFFCC':
3354
                    $colorIdx = 0x2A;
3355
3356
                    break;
3357
                case 'FFFF99':
3358
                    $colorIdx = 0x2B;
3359
3360
                    break;
3361
                case '99CCFF':
3362
                    $colorIdx = 0x2C;
3363
3364
                    break;
3365
                case 'FF99CC':
3366
                    $colorIdx = 0x2D;
3367
3368
                    break;
3369
                case 'CC99FF':
3370
                    $colorIdx = 0x2E;
3371
3372
                    break;
3373
                case 'FFCC99':
3374
                    $colorIdx = 0x2F;
3375
3376
                    break;
3377
                case '3366FF':
3378
                    $colorIdx = 0x30;
3379
3380
                    break;
3381
                case '33CCCC':
3382
                    $colorIdx = 0x31;
3383
3384
                    break;
3385
                case '99CC00':
3386
                    $colorIdx = 0x32;
3387
3388
                    break;
3389
                case 'FFCC00':
3390
                    $colorIdx = 0x33;
3391
3392
                    break;
3393
                case 'FF9900':
3394
                    $colorIdx = 0x34;
3395
3396
                    break;
3397
                case 'FF6600':
3398
                    $colorIdx = 0x35;
3399
3400
                    break;
3401
                case '666699':
3402
                    $colorIdx = 0x36;
3403
3404
                    break;
3405
                case '969696':
3406
                    $colorIdx = 0x37;
3407
3408
                    break;
3409
                case '003366':
3410
                    $colorIdx = 0x38;
3411
3412
                    break;
3413
                case '339966':
3414
                    $colorIdx = 0x39;
3415
3416
                    break;
3417
                case '003300':
3418
                    $colorIdx = 0x3A;
3419
3420
                    break;
3421
                case '333300':
3422
                    $colorIdx = 0x3B;
3423
3424
                    break;
3425
                case '993300':
3426
                    $colorIdx = 0x3C;
3427
3428
                    break;
3429
                case '993366':
3430
                    $colorIdx = 0x3D;
3431
3432
                    break;
3433
                case '333399':
3434
                    $colorIdx = 0x3E;
3435
3436
                    break;
3437
                case '333333':
3438
                    $colorIdx = 0x3F;
3439
3440
                    break;
3441
                default:
3442
                    $colorIdx = 0x00;
3443
3444
                    break;
3445
            }
3446
            $dataBlockFont .= pack('V', $colorIdx);
3447
            // Not used (4)
3448
            $dataBlockFont .= pack('V', 0x00000000);
3449
            // Options flags for modified font attributes
3450
            $optionsFlags = 0;
3451
            $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0);
3452
            $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0);
3453
            $optionsFlags |= (1 == 1 ? 0x00000008 : 0);
3454
            $optionsFlags |= (1 == 1 ? 0x00000010 : 0);
3455
            $optionsFlags |= (1 == 0 ? 0x00000020 : 0);
3456
            $optionsFlags |= (1 == 1 ? 0x00000080 : 0);
3457
            $dataBlockFont .= pack('V', $optionsFlags);
3458
            // Escapement type
3459
            $dataBlockFont .= pack('V', $fontEscapement);
3460
            // Underline type
3461
            $dataBlockFont .= pack('V', $fontUnderline);
3462
            // Always
3463
            $dataBlockFont .= pack('V', 0x00000000);
3464
            // Always
3465
            $dataBlockFont .= pack('V', 0x00000000);
3466
            // Not used (8)
3467
            $dataBlockFont .= pack('VV', 0x00000000, 0x00000000);
3468
            // Always
3469
            $dataBlockFont .= pack('v', 0x0001);
3470
        }
3471
        if ($bFormatAlign == 1) {
3472
            $blockAlign = 0;
3473
            // Alignment and text break
3474
            switch ($conditional->getStyle()->getAlignment()->getHorizontal()) {
3475
                case Alignment::HORIZONTAL_GENERAL:
3476
                    $blockAlign = 0;
3477
3478
                    break;
3479
                case Alignment::HORIZONTAL_LEFT:
3480
                    $blockAlign = 1;
3481
3482
                    break;
3483
                case Alignment::HORIZONTAL_RIGHT:
3484
                    $blockAlign = 3;
3485
3486
                    break;
3487
                case Alignment::HORIZONTAL_CENTER:
3488
                    $blockAlign = 2;
3489
3490
                    break;
3491
                case Alignment::HORIZONTAL_CENTER_CONTINUOUS:
3492
                    $blockAlign = 6;
3493
3494
                    break;
3495
                case Alignment::HORIZONTAL_JUSTIFY:
3496
                    $blockAlign = 5;
3497
3498
                    break;
3499
            }
3500
            if ($conditional->getStyle()->getAlignment()->getWrapText() == true) {
3501
                $blockAlign |= 1 << 3;
3502
            } else {
3503
                $blockAlign |= 0 << 3;
3504
            }
3505
            switch ($conditional->getStyle()->getAlignment()->getVertical()) {
3506
                case Alignment::VERTICAL_BOTTOM:
3507
                    $blockAlign = 2 << 4;
3508
3509
                    break;
3510
                case Alignment::VERTICAL_TOP:
3511
                    $blockAlign = 0 << 4;
3512
3513
                    break;
3514
                case Alignment::VERTICAL_CENTER:
3515
                    $blockAlign = 1 << 4;
3516
3517
                    break;
3518
                case Alignment::VERTICAL_JUSTIFY:
3519
                    $blockAlign = 3 << 4;
3520
3521
                    break;
3522
            }
3523
            $blockAlign |= 0 << 7;
3524
3525
            // Text rotation angle
3526
            $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation();
3527
3528
            // Indentation
3529
            $blockIndent = $conditional->getStyle()->getAlignment()->getIndent();
3530
            if ($conditional->getStyle()->getAlignment()->getShrinkToFit() == true) {
3531
                $blockIndent |= 1 << 4;
3532
            } else {
3533
                $blockIndent |= 0 << 4;
3534
            }
3535
            $blockIndent |= 0 << 6;
3536
3537
            // Relative indentation
3538
            $blockIndentRelative = 255;
3539
3540
            $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000);
3541
        }
3542
        if ($bFormatBorder == 1) {
3543
            $blockLineStyle = 0;
3544
            switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()) {
3545
                case Border::BORDER_NONE:
3546
                    $blockLineStyle |= 0x00;
3547
3548
                    break;
3549
                case Border::BORDER_THIN:
3550
                    $blockLineStyle |= 0x01;
3551
3552
                    break;
3553
                case Border::BORDER_MEDIUM:
3554
                    $blockLineStyle |= 0x02;
3555
3556
                    break;
3557
                case Border::BORDER_DASHED:
3558
                    $blockLineStyle |= 0x03;
3559
3560
                    break;
3561
                case Border::BORDER_DOTTED:
3562
                    $blockLineStyle |= 0x04;
3563
3564
                    break;
3565
                case Border::BORDER_THICK:
3566
                    $blockLineStyle |= 0x05;
3567
3568
                    break;
3569
                case Border::BORDER_DOUBLE:
3570
                    $blockLineStyle |= 0x06;
3571
3572
                    break;
3573
                case Border::BORDER_HAIR:
3574
                    $blockLineStyle |= 0x07;
3575
3576
                    break;
3577
                case Border::BORDER_MEDIUMDASHED:
3578
                    $blockLineStyle |= 0x08;
3579
3580
                    break;
3581
                case Border::BORDER_DASHDOT:
3582
                    $blockLineStyle |= 0x09;
3583
3584
                    break;
3585
                case Border::BORDER_MEDIUMDASHDOT:
3586
                    $blockLineStyle |= 0x0A;
3587
3588
                    break;
3589
                case Border::BORDER_DASHDOTDOT:
3590
                    $blockLineStyle |= 0x0B;
3591
3592
                    break;
3593
                case Border::BORDER_MEDIUMDASHDOTDOT:
3594
                    $blockLineStyle |= 0x0C;
3595
3596
                    break;
3597
                case Border::BORDER_SLANTDASHDOT:
3598
                    $blockLineStyle |= 0x0D;
3599
3600
                    break;
3601
            }
3602
            switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()) {
3603
                case Border::BORDER_NONE:
3604
                    $blockLineStyle |= 0x00 << 4;
3605
3606
                    break;
3607
                case Border::BORDER_THIN:
3608
                    $blockLineStyle |= 0x01 << 4;
3609
3610
                    break;
3611
                case Border::BORDER_MEDIUM:
3612
                    $blockLineStyle |= 0x02 << 4;
3613
3614
                    break;
3615
                case Border::BORDER_DASHED:
3616
                    $blockLineStyle |= 0x03 << 4;
3617
3618
                    break;
3619
                case Border::BORDER_DOTTED:
3620
                    $blockLineStyle |= 0x04 << 4;
3621
3622
                    break;
3623
                case Border::BORDER_THICK:
3624
                    $blockLineStyle |= 0x05 << 4;
3625
3626
                    break;
3627
                case Border::BORDER_DOUBLE:
3628
                    $blockLineStyle |= 0x06 << 4;
3629
3630
                    break;
3631
                case Border::BORDER_HAIR:
3632
                    $blockLineStyle |= 0x07 << 4;
3633
3634
                    break;
3635
                case Border::BORDER_MEDIUMDASHED:
3636
                    $blockLineStyle |= 0x08 << 4;
3637
3638
                    break;
3639
                case Border::BORDER_DASHDOT:
3640
                    $blockLineStyle |= 0x09 << 4;
3641
3642
                    break;
3643
                case Border::BORDER_MEDIUMDASHDOT:
3644
                    $blockLineStyle |= 0x0A << 4;
3645
3646
                    break;
3647
                case Border::BORDER_DASHDOTDOT:
3648
                    $blockLineStyle |= 0x0B << 4;
3649
3650
                    break;
3651
                case Border::BORDER_MEDIUMDASHDOTDOT:
3652
                    $blockLineStyle |= 0x0C << 4;
3653
3654
                    break;
3655
                case Border::BORDER_SLANTDASHDOT:
3656
                    $blockLineStyle |= 0x0D << 4;
3657
3658
                    break;
3659
            }
3660
            switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()) {
3661
                case Border::BORDER_NONE:
3662
                    $blockLineStyle |= 0x00 << 8;
3663
3664
                    break;
3665
                case Border::BORDER_THIN:
3666
                    $blockLineStyle |= 0x01 << 8;
3667
3668
                    break;
3669
                case Border::BORDER_MEDIUM:
3670
                    $blockLineStyle |= 0x02 << 8;
3671
3672
                    break;
3673
                case Border::BORDER_DASHED:
3674
                    $blockLineStyle |= 0x03 << 8;
3675
3676
                    break;
3677
                case Border::BORDER_DOTTED:
3678
                    $blockLineStyle |= 0x04 << 8;
3679
3680
                    break;
3681
                case Border::BORDER_THICK:
3682
                    $blockLineStyle |= 0x05 << 8;
3683
3684
                    break;
3685
                case Border::BORDER_DOUBLE:
3686
                    $blockLineStyle |= 0x06 << 8;
3687
3688
                    break;
3689
                case Border::BORDER_HAIR:
3690
                    $blockLineStyle |= 0x07 << 8;
3691
3692
                    break;
3693
                case Border::BORDER_MEDIUMDASHED:
3694
                    $blockLineStyle |= 0x08 << 8;
3695
3696
                    break;
3697
                case Border::BORDER_DASHDOT:
3698
                    $blockLineStyle |= 0x09 << 8;
3699
3700
                    break;
3701
                case Border::BORDER_MEDIUMDASHDOT:
3702
                    $blockLineStyle |= 0x0A << 8;
3703
3704
                    break;
3705
                case Border::BORDER_DASHDOTDOT:
3706
                    $blockLineStyle |= 0x0B << 8;
3707
3708
                    break;
3709
                case Border::BORDER_MEDIUMDASHDOTDOT:
3710
                    $blockLineStyle |= 0x0C << 8;
3711
3712
                    break;
3713
                case Border::BORDER_SLANTDASHDOT:
3714
                    $blockLineStyle |= 0x0D << 8;
3715
3716
                    break;
3717
            }
3718
            switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()) {
3719
                case Border::BORDER_NONE:
3720
                    $blockLineStyle |= 0x00 << 12;
3721
3722
                    break;
3723
                case Border::BORDER_THIN:
3724
                    $blockLineStyle |= 0x01 << 12;
3725
3726
                    break;
3727
                case Border::BORDER_MEDIUM:
3728
                    $blockLineStyle |= 0x02 << 12;
3729
3730
                    break;
3731
                case Border::BORDER_DASHED:
3732
                    $blockLineStyle |= 0x03 << 12;
3733
3734
                    break;
3735
                case Border::BORDER_DOTTED:
3736
                    $blockLineStyle |= 0x04 << 12;
3737
3738
                    break;
3739
                case Border::BORDER_THICK:
3740
                    $blockLineStyle |= 0x05 << 12;
3741
3742
                    break;
3743
                case Border::BORDER_DOUBLE:
3744
                    $blockLineStyle |= 0x06 << 12;
3745
3746
                    break;
3747
                case Border::BORDER_HAIR:
3748
                    $blockLineStyle |= 0x07 << 12;
3749
3750
                    break;
3751
                case Border::BORDER_MEDIUMDASHED:
3752
                    $blockLineStyle |= 0x08 << 12;
3753
3754
                    break;
3755
                case Border::BORDER_DASHDOT:
3756
                    $blockLineStyle |= 0x09 << 12;
3757
3758
                    break;
3759
                case Border::BORDER_MEDIUMDASHDOT:
3760
                    $blockLineStyle |= 0x0A << 12;
3761
3762
                    break;
3763
                case Border::BORDER_DASHDOTDOT:
3764
                    $blockLineStyle |= 0x0B << 12;
3765
3766
                    break;
3767
                case Border::BORDER_MEDIUMDASHDOTDOT:
3768
                    $blockLineStyle |= 0x0C << 12;
3769
3770
                    break;
3771
                case Border::BORDER_SLANTDASHDOT:
3772
                    $blockLineStyle |= 0x0D << 12;
3773
3774
                    break;
3775
            }
3776
            //@todo writeCFRule() => $blockLineStyle => Index Color for left line
3777
            //@todo writeCFRule() => $blockLineStyle => Index Color for right line
3778
            //@todo writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off
3779
            //@todo writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off
3780
            $blockColor = 0;
3781
            //@todo writeCFRule() => $blockColor => Index Color for top line
3782
            //@todo writeCFRule() => $blockColor => Index Color for bottom line
3783
            //@todo writeCFRule() => $blockColor => Index Color for diagonal line
3784
            switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()) {
3785
                case Border::BORDER_NONE:
3786
                    $blockColor |= 0x00 << 21;
3787
3788
                    break;
3789
                case Border::BORDER_THIN:
3790
                    $blockColor |= 0x01 << 21;
3791
3792
                    break;
3793
                case Border::BORDER_MEDIUM:
3794
                    $blockColor |= 0x02 << 21;
3795
3796
                    break;
3797
                case Border::BORDER_DASHED:
3798
                    $blockColor |= 0x03 << 21;
3799
3800
                    break;
3801
                case Border::BORDER_DOTTED:
3802
                    $blockColor |= 0x04 << 21;
3803
3804
                    break;
3805
                case Border::BORDER_THICK:
3806
                    $blockColor |= 0x05 << 21;
3807
3808
                    break;
3809
                case Border::BORDER_DOUBLE:
3810
                    $blockColor |= 0x06 << 21;
3811
3812
                    break;
3813
                case Border::BORDER_HAIR:
3814
                    $blockColor |= 0x07 << 21;
3815
3816
                    break;
3817
                case Border::BORDER_MEDIUMDASHED:
3818
                    $blockColor |= 0x08 << 21;
3819
3820
                    break;
3821
                case Border::BORDER_DASHDOT:
3822
                    $blockColor |= 0x09 << 21;
3823
3824
                    break;
3825
                case Border::BORDER_MEDIUMDASHDOT:
3826
                    $blockColor |= 0x0A << 21;
3827
3828
                    break;
3829
                case Border::BORDER_DASHDOTDOT:
3830
                    $blockColor |= 0x0B << 21;
3831
3832
                    break;
3833
                case Border::BORDER_MEDIUMDASHDOTDOT:
3834
                    $blockColor |= 0x0C << 21;
3835
3836
                    break;
3837
                case Border::BORDER_SLANTDASHDOT:
3838
                    $blockColor |= 0x0D << 21;
3839
3840
                    break;
3841
            }
3842
            $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor);
3843
        }
3844
        if ($bFormatFill == 1) {
3845
            // Fill Patern Style
3846
            $blockFillPatternStyle = 0;
3847
            switch ($conditional->getStyle()->getFill()->getFillType()) {
3848
                case Fill::FILL_NONE:
3849
                    $blockFillPatternStyle = 0x00;
3850
3851
                    break;
3852
                case Fill::FILL_SOLID:
3853
                    $blockFillPatternStyle = 0x01;
3854
3855
                    break;
3856
                case Fill::FILL_PATTERN_MEDIUMGRAY:
3857
                    $blockFillPatternStyle = 0x02;
3858
3859
                    break;
3860
                case Fill::FILL_PATTERN_DARKGRAY:
3861
                    $blockFillPatternStyle = 0x03;
3862
3863
                    break;
3864
                case Fill::FILL_PATTERN_LIGHTGRAY:
3865
                    $blockFillPatternStyle = 0x04;
3866
3867
                    break;
3868
                case Fill::FILL_PATTERN_DARKHORIZONTAL:
3869
                    $blockFillPatternStyle = 0x05;
3870
3871
                    break;
3872
                case Fill::FILL_PATTERN_DARKVERTICAL:
3873
                    $blockFillPatternStyle = 0x06;
3874
3875
                    break;
3876
                case Fill::FILL_PATTERN_DARKDOWN:
3877
                    $blockFillPatternStyle = 0x07;
3878
3879
                    break;
3880
                case Fill::FILL_PATTERN_DARKUP:
3881
                    $blockFillPatternStyle = 0x08;
3882
3883
                    break;
3884
                case Fill::FILL_PATTERN_DARKGRID:
3885
                    $blockFillPatternStyle = 0x09;
3886
3887
                    break;
3888
                case Fill::FILL_PATTERN_DARKTRELLIS:
3889
                    $blockFillPatternStyle = 0x0A;
3890
3891
                    break;
3892
                case Fill::FILL_PATTERN_LIGHTHORIZONTAL:
3893
                    $blockFillPatternStyle = 0x0B;
3894
3895
                    break;
3896
                case Fill::FILL_PATTERN_LIGHTVERTICAL:
3897
                    $blockFillPatternStyle = 0x0C;
3898
3899
                    break;
3900
                case Fill::FILL_PATTERN_LIGHTDOWN:
3901
                    $blockFillPatternStyle = 0x0D;
3902
3903
                    break;
3904
                case Fill::FILL_PATTERN_LIGHTUP:
3905
                    $blockFillPatternStyle = 0x0E;
3906
3907
                    break;
3908
                case Fill::FILL_PATTERN_LIGHTGRID:
3909
                    $blockFillPatternStyle = 0x0F;
3910
3911
                    break;
3912
                case Fill::FILL_PATTERN_LIGHTTRELLIS:
3913
                    $blockFillPatternStyle = 0x10;
3914
3915
                    break;
3916
                case Fill::FILL_PATTERN_GRAY125:
3917
                    $blockFillPatternStyle = 0x11;
3918
3919
                    break;
3920
                case Fill::FILL_PATTERN_GRAY0625:
3921
                    $blockFillPatternStyle = 0x12;
3922
3923
                    break;
3924
                case Fill::FILL_GRADIENT_LINEAR:
3925
                    $blockFillPatternStyle = 0x00;
3926
3927
                    break; // does not exist in BIFF8
3928
                case Fill::FILL_GRADIENT_PATH:
3929
                    $blockFillPatternStyle = 0x00;
3930
3931
                    break; // does not exist in BIFF8
3932
                default:
3933
                    $blockFillPatternStyle = 0x00;
3934
3935
                    break;
3936
            }
3937
            // Color
3938
            switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) {
3939
                case '000000':
3940
                    $colorIdxBg = 0x08;
3941
3942
                    break;
3943
                case 'FFFFFF':
3944
                    $colorIdxBg = 0x09;
3945
3946
                    break;
3947
                case 'FF0000':
3948
                    $colorIdxBg = 0x0A;
3949
3950
                    break;
3951
                case '00FF00':
3952
                    $colorIdxBg = 0x0B;
3953
3954
                    break;
3955
                case '0000FF':
3956
                    $colorIdxBg = 0x0C;
3957
3958
                    break;
3959
                case 'FFFF00':
3960
                    $colorIdxBg = 0x0D;
3961
3962
                    break;
3963
                case 'FF00FF':
3964
                    $colorIdxBg = 0x0E;
3965
3966
                    break;
3967
                case '00FFFF':
3968
                    $colorIdxBg = 0x0F;
3969
3970
                    break;
3971
                case '800000':
3972
                    $colorIdxBg = 0x10;
3973
3974
                    break;
3975
                case '008000':
3976
                    $colorIdxBg = 0x11;
3977
3978
                    break;
3979
                case '000080':
3980
                    $colorIdxBg = 0x12;
3981
3982
                    break;
3983
                case '808000':
3984
                    $colorIdxBg = 0x13;
3985
3986
                    break;
3987
                case '800080':
3988
                    $colorIdxBg = 0x14;
3989
3990
                    break;
3991
                case '008080':
3992
                    $colorIdxBg = 0x15;
3993
3994
                    break;
3995
                case 'C0C0C0':
3996
                    $colorIdxBg = 0x16;
3997
3998
                    break;
3999
                case '808080':
4000
                    $colorIdxBg = 0x17;
4001
4002
                    break;
4003
                case '9999FF':
4004
                    $colorIdxBg = 0x18;
4005
4006
                    break;
4007
                case '993366':
4008
                    $colorIdxBg = 0x19;
4009
4010
                    break;
4011
                case 'FFFFCC':
4012
                    $colorIdxBg = 0x1A;
4013
4014
                    break;
4015
                case 'CCFFFF':
4016
                    $colorIdxBg = 0x1B;
4017
4018
                    break;
4019
                case '660066':
4020
                    $colorIdxBg = 0x1C;
4021
4022
                    break;
4023
                case 'FF8080':
4024
                    $colorIdxBg = 0x1D;
4025
4026
                    break;
4027
                case '0066CC':
4028
                    $colorIdxBg = 0x1E;
4029
4030
                    break;
4031
                case 'CCCCFF':
4032
                    $colorIdxBg = 0x1F;
4033
4034
                    break;
4035
                case '000080':
4036
                    $colorIdxBg = 0x20;
4037
4038
                    break;
4039
                case 'FF00FF':
4040
                    $colorIdxBg = 0x21;
4041
4042
                    break;
4043
                case 'FFFF00':
4044
                    $colorIdxBg = 0x22;
4045
4046
                    break;
4047
                case '00FFFF':
4048
                    $colorIdxBg = 0x23;
4049
4050
                    break;
4051
                case '800080':
4052
                    $colorIdxBg = 0x24;
4053
4054
                    break;
4055
                case '800000':
4056
                    $colorIdxBg = 0x25;
4057
4058
                    break;
4059
                case '008080':
4060
                    $colorIdxBg = 0x26;
4061
4062
                    break;
4063
                case '0000FF':
4064
                    $colorIdxBg = 0x27;
4065
4066
                    break;
4067
                case '00CCFF':
4068
                    $colorIdxBg = 0x28;
4069
4070
                    break;
4071
                case 'CCFFFF':
4072
                    $colorIdxBg = 0x29;
4073
4074
                    break;
4075
                case 'CCFFCC':
4076
                    $colorIdxBg = 0x2A;
4077
4078
                    break;
4079
                case 'FFFF99':
4080
                    $colorIdxBg = 0x2B;
4081
4082
                    break;
4083
                case '99CCFF':
4084
                    $colorIdxBg = 0x2C;
4085
4086
                    break;
4087
                case 'FF99CC':
4088
                    $colorIdxBg = 0x2D;
4089
4090
                    break;
4091
                case 'CC99FF':
4092
                    $colorIdxBg = 0x2E;
4093
4094
                    break;
4095
                case 'FFCC99':
4096
                    $colorIdxBg = 0x2F;
4097
4098
                    break;
4099
                case '3366FF':
4100
                    $colorIdxBg = 0x30;
4101
4102
                    break;
4103
                case '33CCCC':
4104
                    $colorIdxBg = 0x31;
4105
4106
                    break;
4107
                case '99CC00':
4108
                    $colorIdxBg = 0x32;
4109
4110
                    break;
4111
                case 'FFCC00':
4112
                    $colorIdxBg = 0x33;
4113
4114
                    break;
4115
                case 'FF9900':
4116
                    $colorIdxBg = 0x34;
4117
4118
                    break;
4119
                case 'FF6600':
4120
                    $colorIdxBg = 0x35;
4121
4122
                    break;
4123
                case '666699':
4124
                    $colorIdxBg = 0x36;
4125
4126
                    break;
4127
                case '969696':
4128
                    $colorIdxBg = 0x37;
4129
4130
                    break;
4131
                case '003366':
4132
                    $colorIdxBg = 0x38;
4133
4134
                    break;
4135
                case '339966':
4136
                    $colorIdxBg = 0x39;
4137
4138
                    break;
4139
                case '003300':
4140
                    $colorIdxBg = 0x3A;
4141
4142
                    break;
4143
                case '333300':
4144
                    $colorIdxBg = 0x3B;
4145
4146
                    break;
4147
                case '993300':
4148
                    $colorIdxBg = 0x3C;
4149
4150
                    break;
4151
                case '993366':
4152
                    $colorIdxBg = 0x3D;
4153
4154
                    break;
4155
                case '333399':
4156
                    $colorIdxBg = 0x3E;
4157
4158
                    break;
4159
                case '333333':
4160
                    $colorIdxBg = 0x3F;
4161
4162
                    break;
4163
                default:
4164
                          $colorIdxBg = 0x41;
4165
4166
                    break;
4167
            }
4168
            // Fg Color
4169
            switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) {
4170
                case '000000':
4171
                    $colorIdxFg = 0x08;
4172
4173
                    break;
4174
                case 'FFFFFF':
4175
                    $colorIdxFg = 0x09;
4176
4177
                    break;
4178
                case 'FF0000':
4179
                    $colorIdxFg = 0x0A;
4180
4181
                    break;
4182
                case '00FF00':
4183
                    $colorIdxFg = 0x0B;
4184
4185
                    break;
4186
                case '0000FF':
4187
                    $colorIdxFg = 0x0C;
4188
4189
                    break;
4190
                case 'FFFF00':
4191
                    $colorIdxFg = 0x0D;
4192
4193
                    break;
4194
                case 'FF00FF':
4195
                    $colorIdxFg = 0x0E;
4196
4197
                    break;
4198
                case '00FFFF':
4199
                    $colorIdxFg = 0x0F;
4200
4201
                    break;
4202
                case '800000':
4203
                    $colorIdxFg = 0x10;
4204
4205
                    break;
4206
                case '008000':
4207
                    $colorIdxFg = 0x11;
4208
4209
                    break;
4210
                case '000080':
4211
                    $colorIdxFg = 0x12;
4212
4213
                    break;
4214
                case '808000':
4215
                    $colorIdxFg = 0x13;
4216
4217
                    break;
4218
                case '800080':
4219
                    $colorIdxFg = 0x14;
4220
4221
                    break;
4222
                case '008080':
4223
                    $colorIdxFg = 0x15;
4224
4225
                    break;
4226
                case 'C0C0C0':
4227
                    $colorIdxFg = 0x16;
4228
4229
                    break;
4230
                case '808080':
4231
                    $colorIdxFg = 0x17;
4232
4233
                    break;
4234
                case '9999FF':
4235
                    $colorIdxFg = 0x18;
4236
4237
                    break;
4238
                case '993366':
4239
                    $colorIdxFg = 0x19;
4240
4241
                    break;
4242
                case 'FFFFCC':
4243
                    $colorIdxFg = 0x1A;
4244
4245
                    break;
4246
                case 'CCFFFF':
4247
                    $colorIdxFg = 0x1B;
4248
4249
                    break;
4250
                case '660066':
4251
                    $colorIdxFg = 0x1C;
4252
4253
                    break;
4254
                case 'FF8080':
4255
                    $colorIdxFg = 0x1D;
4256
4257
                    break;
4258
                case '0066CC':
4259
                    $colorIdxFg = 0x1E;
4260
4261
                    break;
4262
                case 'CCCCFF':
4263
                    $colorIdxFg = 0x1F;
4264
4265
                    break;
4266
                case '000080':
4267
                    $colorIdxFg = 0x20;
4268
4269
                    break;
4270
                case 'FF00FF':
4271
                    $colorIdxFg = 0x21;
4272
4273
                    break;
4274
                case 'FFFF00':
4275
                    $colorIdxFg = 0x22;
4276
4277
                    break;
4278
                case '00FFFF':
4279
                    $colorIdxFg = 0x23;
4280
4281
                    break;
4282
                case '800080':
4283
                    $colorIdxFg = 0x24;
4284
4285
                    break;
4286
                case '800000':
4287
                    $colorIdxFg = 0x25;
4288
4289
                    break;
4290
                case '008080':
4291
                    $colorIdxFg = 0x26;
4292
4293
                    break;
4294
                case '0000FF':
4295
                    $colorIdxFg = 0x27;
4296
4297
                    break;
4298
                case '00CCFF':
4299
                    $colorIdxFg = 0x28;
4300
4301
                    break;
4302
                case 'CCFFFF':
4303
                    $colorIdxFg = 0x29;
4304
4305
                    break;
4306
                case 'CCFFCC':
4307
                    $colorIdxFg = 0x2A;
4308
4309
                    break;
4310
                case 'FFFF99':
4311
                    $colorIdxFg = 0x2B;
4312
4313
                    break;
4314
                case '99CCFF':
4315
                    $colorIdxFg = 0x2C;
4316
4317
                    break;
4318
                case 'FF99CC':
4319
                    $colorIdxFg = 0x2D;
4320
4321
                    break;
4322
                case 'CC99FF':
4323
                    $colorIdxFg = 0x2E;
4324
4325
                    break;
4326
                case 'FFCC99':
4327
                    $colorIdxFg = 0x2F;
4328
4329
                    break;
4330
                case '3366FF':
4331
                    $colorIdxFg = 0x30;
4332
4333
                    break;
4334
                case '33CCCC':
4335
                    $colorIdxFg = 0x31;
4336
4337
                    break;
4338
                case '99CC00':
4339
                    $colorIdxFg = 0x32;
4340
4341
                    break;
4342
                case 'FFCC00':
4343
                    $colorIdxFg = 0x33;
4344
4345
                    break;
4346
                case 'FF9900':
4347
                    $colorIdxFg = 0x34;
4348
4349
                    break;
4350
                case 'FF6600':
4351
                    $colorIdxFg = 0x35;
4352
4353
                    break;
4354
                case '666699':
4355
                    $colorIdxFg = 0x36;
4356
4357
                    break;
4358
                case '969696':
4359
                    $colorIdxFg = 0x37;
4360
4361
                    break;
4362
                case '003366':
4363
                    $colorIdxFg = 0x38;
4364
4365
                    break;
4366
                case '339966':
4367
                    $colorIdxFg = 0x39;
4368
4369
                    break;
4370
                case '003300':
4371
                    $colorIdxFg = 0x3A;
4372
4373
                    break;
4374
                case '333300':
4375
                    $colorIdxFg = 0x3B;
4376
4377
                    break;
4378
                case '993300':
4379
                    $colorIdxFg = 0x3C;
4380
4381
                    break;
4382
                case '993366':
4383
                    $colorIdxFg = 0x3D;
4384
4385
                    break;
4386
                case '333399':
4387
                    $colorIdxFg = 0x3E;
4388
4389
                    break;
4390
                case '333333':
4391
                    $colorIdxFg = 0x3F;
4392
4393
                    break;
4394
                default:
4395
                          $colorIdxFg = 0x40;
4396
4397
                    break;
4398
            }
4399
            $dataBlockFill = pack('v', $blockFillPatternStyle);
4400
            $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7));
4401
        }
4402
        if ($bFormatProt == 1) {
4403
            $dataBlockProtection = 0;
4404
            if ($conditional->getStyle()->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED) {
4405
                $dataBlockProtection = 1;
4406
            }
4407
            if ($conditional->getStyle()->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED) {
4408
                $dataBlockProtection = 1 << 1;
4409
            }
4410
        }
4411
4412
        $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000);
4413
        if ($bFormatFont == 1) { // Block Formatting : OK
4414
            $data .= $dataBlockFont;
4415
        }
4416
        if ($bFormatAlign == 1) {
4417
            $data .= $dataBlockAlign;
4418
        }
4419
        if ($bFormatBorder == 1) {
4420
            $data .= $dataBlockBorder;
4421
        }
4422
        if ($bFormatFill == 1) { // Block Formatting : OK
4423
            $data .= $dataBlockFill;
4424
        }
4425
        if ($bFormatProt == 1) {
4426
            $data .= $dataBlockProtection;
4427
        }
4428
        if ($operand1 !== null) {
4429
            $data .= $operand1;
4430
        }
4431
        if ($operand2 !== null) {
4432
            $data .= $operand2;
4433
        }
4434
        $header = pack('vv', $record, strlen($data));
4435
        $this->append($header . $data);
4436
    }
4437
4438
    /**
4439
     * Write CFHeader record.
4440
     */
4441
    private function writeCFHeader()
4442
    {
4443
        $record = 0x01B0; // Record identifier
4444
        $length = 0x0016; // Bytes to follow
4445
4446
        $numColumnMin = null;
4447
        $numColumnMax = null;
4448
        $numRowMin = null;
4449
        $numRowMax = null;
4450
        $arrConditional = [];
4451
        foreach ($this->phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
4452
            foreach ($conditionalStyles as $conditional) {
4453
                if (
4454
                    $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION
4455
                        || $conditional->getConditionType() == Conditional::CONDITION_CELLIS
4456
                ) {
4457
                    if (!in_array($conditional->getHashCode(), $arrConditional)) {
4458
                        $arrConditional[] = $conditional->getHashCode();
4459
                    }
4460
                    // Cells
4461
                    $arrCoord = Coordinate::coordinateFromString($cellCoordinate);
4462
                    if (!is_numeric($arrCoord[0])) {
4463
                        $arrCoord[0] = Coordinate::columnIndexFromString($arrCoord[0]);
4464
                    }
4465
                    if ($numColumnMin === null || ($numColumnMin > $arrCoord[0])) {
4466
                        $numColumnMin = $arrCoord[0];
4467
                    }
4468
                    if ($numColumnMax === null || ($numColumnMax < $arrCoord[0])) {
4469
                        $numColumnMax = $arrCoord[0];
4470
                    }
4471
                    if ($numRowMin === null || ($numRowMin > $arrCoord[1])) {
4472
                        $numRowMin = $arrCoord[1];
4473
                    }
4474
                    if ($numRowMax === null || ($numRowMax < $arrCoord[1])) {
4475
                        $numRowMax = $arrCoord[1];
4476
                    }
4477
                }
4478
            }
4479
        }
4480
        $needRedraw = 1;
4481
        $cellRange = pack('vvvv', $numRowMin - 1, $numRowMax - 1, $numColumnMin - 1, $numColumnMax - 1);
4482
4483
        $header = pack('vv', $record, $length);
4484
        $data = pack('vv', count($arrConditional), $needRedraw);
4485
        $data .= $cellRange;
4486
        $data .= pack('v', 0x0001);
4487
        $data .= $cellRange;
4488
        $this->append($header . $data);
4489
    }
4490
}
4491