-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathSimpleXLS.php
1327 lines (1183 loc) · 51.3 KB
/
SimpleXLS.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Shuchkin;
/*
* Example
echo '<pre>';
if ( $xls = SimpleXLS::parse('excel5book.xls')) {
print_r( $xls->rows() ); // dump first sheet
print_r( $xls->rows(1)); /// dump second sheet
} else {
echo SimpleXLS::parseError();
}
echo '</pre>';
*/
/**
* A class for reading Microsoft Excel Spreadsheets.
*
* SimpleXLS version 2016-2020 packaged by Sergey Shuchkin <[email protected]> from
* Spreadsheet_Excel_Reader class developed by Vadim Tkachenko <[email protected]>
*/
class SimpleXLS
{
public const BIFF8 = 0x600;
public const BIFF7 = 0x500;
public const WORKBOOKGLOBALS = 0x5;
public const WORKSHEET = 0x10;
//const TYPE_BOF = 0x809;
public const TYPE_EOF = 0x0a;
public const TYPE_BOUNDSHEET = 0x85;
public const TYPE_DIMENSION = 0x200;
public const TYPE_ROW = 0x208;
public const TYPE_DBCELL = 0xd7;
public const TYPE_FILEPASS = 0x2f;
//const TYPE_NOTE = 0x1c;
//const TYPE_TXO = 0x1b6;
public const TYPE_RK = 0x7e;
public const TYPE_RK2 = 0x27e;
public const TYPE_MULRK = 0xbd;
public const TYPE_MULBLANK = 0xbe;
//const TYPE_INDEX = 0x20b;
public const TYPE_SST = 0xfc;
//const TYPE_EXTSST = 0xff;
//const TYPE_CONTINUE = 0x3c;
public const TYPE_LABEL = 0x204;
public const TYPE_LABELSST = 0xfd;
public const TYPE_NUMBER = 0x203;
public const TYPE_NAME = 0x18;
//const TYPE_ARRAY = 0x221;
//const TYPE_STRING = 0x207;
public const TYPE_FORMULA = 0x406;
public const TYPE_FORMULA2 = 0x6;
public const TYPE_FORMAT = 0x41e;
public const TYPE_XF = 0xe0;
public const TYPE_BOOLERR = 0x205;
//const TYPE_UNKNOWN = 0xffff;
public const TYPE_NINETEENFOUR = 0x22;
public const TYPE_MERGEDCELLS = 0xE5;
public const TYPE_WINDOW1 = 0x3D;
//const DEF_NUM_FORMAT = "%.2f";
public const DEF_NUM_FORMAT = '%s';
// OLE
public const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c;
public const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c;
public const ROOT_START_BLOCK_POS = 0x30;
public const BIG_BLOCK_SIZE = 0x200;
public const SMALL_BLOCK_SIZE = 0x40;
public const EXTENSION_BLOCK_POS = 0x44;
public const NUM_EXTENSION_BLOCK_POS = 0x48;
public const PROPERTY_STORAGE_BLOCK_SIZE = 0x80;
public const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c;
public const SMALL_BLOCK_THRESHOLD = 0x1000;
// property storage offsets
public const SIZE_OF_NAME_POS = 0x40;
public const TYPE_POS = 0x42;
public const START_BLOCK_POS = 0x74;
public const SIZE_POS = 0x78;
/**
* Array of worksheets found
*
* @var array
* @access public
*/
public $boundsheets = array();
public $activeSheet = 0;
/**
* Array of format records found
*
* @var array
* @access public
*/
public $formatRecords = array();
/**
*
* @var array
* @access public
*/
public $sst = array();
/**
* Array of worksheets
*
* The data is stored in 'cells' and the meta-data is stored in an array
* called 'cellsInfo'
*
* Example:
*
* $sheets --> 'cells' --> row --> column --> Interpreted value
* --> 'cellsInfo' --> row --> column --> 'type' - Can be 'date', 'number', or 'unknown'
* --> 'raw' - The raw data that Excel stores for that data cell
*
* @var array
* @access public
*/
public $sheets = array();
/**
* List of default date formats used by Excel
*
* @var array
* @access public
*/
public $dateFormats = array(
0xe => 'd/m/Y',
0xf => 'd-M-Y',
0x10 => 'd-M',
0x11 => 'M-Y',
0x12 => 'h:i a',
0x13 => 'h:i:s a',
0x14 => 'H:i',
0x15 => 'H:i:s',
0x16 => 'd/m/Y H:i',
0x2d => 'i:s',
0x2e => 'H:i:s',
0x2f => 'i:s.S'
);
/**
* Default number formats used by Excel
*
* @var array
* @access public
*/
public $numberFormats = array(
0x1 => '%1.0f', // "0"
0x2 => '%1.2f', // "0.00",
0x3 => '%1.0f', //"#,##0",
0x4 => '%1.2f', //"#,##0.00",
0x5 => '%1.0f', /*"$#,##0;($#,##0)",*/
0x6 => '$%1.0f', /*"$#,##0;($#,##0)",*/
0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x9 => '%1.0f%%', // "0%"
0xa => '%1.2f%%', // "0.00%"
0xb => '%1.2f', // 0.00E00",
0x25 => '%1.0f', // "#,##0;(#,##0)",
0x26 => '%1.0f', //"#,##0;(#,##0)",
0x27 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x28 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x29 => '%1.0f', //"#,##0;(#,##0)",
0x2a => '$%1.0f', //"$#,##0;($#,##0)",
0x2b => '%1.2f', //"#,##0.00;(#,##0.00)",
0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x30 => '%1.0f'
);
protected $datetimeFormat = 'Y-m-d H:i:s';
/**
* Default encoding
*
* @var string
* @access private
*/
protected $defaultEncoding = 'UTF-8';
/**
* Default number format
*
* @var integer
* @access private
*/
protected $defaultFormat = self::DEF_NUM_FORMAT;
/**
* List of formats to use for each column
*
* @var array
* @access private
*/
protected $columnsFormat = array();
protected $nineteenFour;
protected $multiplier;
protected $sn;
protected $curFormat;
// OLERead
protected $data;
protected $bigBlockChain;
protected $smallBlockChain;
protected $rootEntry;
protected $entry;
protected $props;
protected $wrkbook; // false - to use excel format
protected $error = false;
protected $debug;
// {{{ Spreadsheet_Excel_Reader()
/**
* Constructor
*
* @param string $filename XLS Filename or xls contents
* @param bool $isData If True then $filename is contents
* @param bool $debug Trigger PHP errors?
*/
public function __construct(string $filename, bool $isData = false, bool $debug = false)
{
$this->debug = $debug;
$this->_oleread($filename, $isData);
$this->_parse();
}
public static function parseFile($filename, $debug = false)
{
return self::parse($filename, false, $debug);
}
public static function parseData($data, $debug = false)
{
return self::parse($data, true, $debug);
}
public static function parse($filename, $isData = false, $debug = false)
{
$xls = new self($filename, $isData, $debug);
if ($xls->success()) {
return $xls;
}
self::parseError($xls->error());
return false;
}
public static function parseError($set = false)
{
static $error = false;
return $set ? $error = $set : $error;
}
public function error($set = false)
{
if ($set) {
$this->error = $set;
if ($this->debug) {
trigger_error($set);
}
}
return $this->error;
}
public function success(): bool
{
return ! $this->error;
}
public function rows($worksheetIndex = 0, $limit = 0)
{
return iterator_to_array($this->readRows($worksheetIndex, $limit), false);
}
/**
* @param $sheetNum
* @param $limit
* @return \Generator
*/
public function readRows($sheetNum = 0, $limit = 0)
{
if ($this->sheets[ $sheetNum ]) {
$s = $this->sheets[ $sheetNum ];
for ($i = 0; $i < $s['numRows']; $i ++) {
$r = array();
for ($j = 0; $j < $s['numCols']; $j ++) {
$r[ $j ] = $s['cells'][$i][$j] ?? '';
}
yield $r;
$limit--;
if ($limit === 0) {
break;
}
}
}
return;
}
public function rowsEx($sheetNum = 0, $limit = 0): array
{
if ($this->sheets[ $sheetNum ]) {
$s = $this->sheets[ $sheetNum ];
$result = array();
for ($i = 0; $i < $s['numRows']; $i ++) {
$r = array();
for ($j = 0; $j < $s['numCols']; $j ++) {
$v = $s['cellsInfo'][$i][$j] ?? array();
// if ( $v['type'] === self::TYPE_RK || $v['type'] === self::TYPE_RK2 ||
$v['value'] = $s['cells'][$i][$j] ?? '';
$r[ $j ] = $v;
}
$result[] = $r;
$limit--;
if ($limit === 0) {
break;
}
}
return $result;
}
return [];
}
public function toHTML($worksheetIndex = 0): string
{
$s = '<table class=excel>';
foreach ($this->rows($worksheetIndex) as $r) {
$s .= '<tr>';
foreach ($r as $c) {
$s .= '<td nowrap>' . ( $c === '' ? ' ' : htmlspecialchars($c, ENT_QUOTES) ) . '</td>';
}
$s .= "</tr>\r\n";
}
$s .= '</table>';
return $s;
}
public function setDateTimeFormat($value): SimpleXLS
{
$this->datetimeFormat = is_string($value) ? $value : false;
return $this;
}
public function sheetNames(): array
{
$result = array();
foreach ($this->boundsheets as $k => $v) {
$result[ $k ] = $v['name'];
}
return $result;
}
public function sheetName($index)
{
return isset($this->boundsheets[ $index ]) ? $this->boundsheets[ $index ]['name'] : null;
}
// }}}
protected function _oleread($sFileName, $isData = false): bool
{
if ($isData) {
$this->data = $sFileName;
} else {
// check if file exist and is readable (Darko Miljanovic)
if (! is_readable($sFileName)) {
$this->error('File not is readable ' . $sFileName);
return false;
}
$this->data = file_get_contents($sFileName);
if (! $this->data) {
$this->error('File reading error ' . $sFileName);
return false;
}
}
//echo IDENTIFIER_OLE;
//echo 'start';
if (strpos($this->data, pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1)) !== 0) {
$this->error('File is not XLS');
return false;
}
$numBigBlockDepotBlocks = $this->_getInt4d(self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
$sbdStartBlock = $this->_getInt4d(self::SMALL_BLOCK_DEPOT_BLOCK_POS);
$rootStartBlock = $this->_getInt4d(self::ROOT_START_BLOCK_POS);
$extensionBlock = $this->_getInt4d(self::EXTENSION_BLOCK_POS);
$numExtensionBlocks = $this->_getInt4d(self::NUM_EXTENSION_BLOCK_POS);
/*
echo $this->numBigBlockDepotBlocks." ";
echo $this->sbdStartBlock." ";
echo $this->rootStartBlock." ";
echo $this->extensionBlock." ";
echo $this->numExtensionBlocks." ";
*/
//echo "sbdStartBlock = $this->sbdStartBlock\n";
$bigBlockDepotBlocks = array();
$pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS;
// echo "pos = $pos";
$bbdBlocks = $numBigBlockDepotBlocks;
if ($numExtensionBlocks !== 0) {
$bbdBlocks = ( self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS ) / 4;
}
for ($i = 0; $i < $bbdBlocks; $i ++) {
$bigBlockDepotBlocks[ $i ] = $this->_getInt4d($pos);
$pos += 4;
}
for ($j = 0; $j < $numExtensionBlocks; $j ++) {
$pos = ( $extensionBlock + 1 ) * self::BIG_BLOCK_SIZE;
$blocksToRead = min($numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1);
for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; $i ++) {
$bigBlockDepotBlocks[ $i ] = $this->_getInt4d($pos);
$pos += 4;
}
$bbdBlocks += $blocksToRead;
if ($bbdBlocks < $numBigBlockDepotBlocks) {
$extensionBlock = $this->_getInt4d($pos);
}
}
// var_dump($bigBlockDepotBlocks);
// readBigBlockDepot
$index = 0;
$this->bigBlockChain = array();
for ($i = 0; $i < $numBigBlockDepotBlocks; $i ++) {
$pos = ( $bigBlockDepotBlocks[ $i ] + 1 ) * self::BIG_BLOCK_SIZE;
//echo "pos = $pos";
for ($j = 0; $j < self::BIG_BLOCK_SIZE / 4; $j ++) {
$this->bigBlockChain[ $index ] = $this->_getInt4d($pos);
$pos += 4;
$index ++;
}
}
//var_dump($this->bigBlockChain);
//echo '=====2';
// readSmallBlockDepot();
$index = 0;
$sbdBlock = $sbdStartBlock;
$this->smallBlockChain = array();
while ($sbdBlock !== - 2) {
$pos = ( $sbdBlock + 1 ) * self::BIG_BLOCK_SIZE;
for ($j = 0; $j < self::BIG_BLOCK_SIZE / 4; $j ++) {
$this->smallBlockChain[ $index ] = $this->_getInt4d($pos);
$pos += 4;
$index ++;
}
$sbdBlock = $this->bigBlockChain[ $sbdBlock ];
}
// readData(rootStartBlock)
$block = $rootStartBlock;
$this->entry = $this->_readData($block);
/*
while ($block != -2) {
$pos = ($block + 1) * self::BIG_BLOCK_SIZE;
$this->entry = $this->entry.substr($this->_data, $pos, self::BIG_BLOCK_SIZE);
$block = $this->bigBlockChain[$block];
}
*/
//echo '==='.$this->entry."===";
$this->_readPropertySets();
$this->data = $this->_readWorkBook();
return true;
}
// {{{ setOutputEncoding()
protected function _getInt2d($pos): int
{
return ord($this->data[ $pos ]) | ord($this->data[ $pos + 1 ]) << 8;
// return ($value > 0x7FFFFFFF) ? $value - 0x100000000 : $value;
}
protected function _getInt4d($pos): int
{
$value = ord($this->data[ $pos ]) | ( ord($this->data[ $pos + 1 ]) << 8 ) | ( ord($this->data[ $pos + 2 ]) << 16 ) | ( ord($this->data[ $pos + 3 ]) << 24 );
return ($value > 0x7FFFFFFF) ? $value - 0x100000000 : $value;
}
// }}}
// {{{ setRowColOffset()
protected function _readData($bl): string
{
$block = $bl;
$data = '';
while ($block !== - 2) {
$pos = ( $block + 1 ) * self::BIG_BLOCK_SIZE;
$data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
//echo "pos = $pos data=$data\n";
$block = $this->bigBlockChain[ $block ];
}
return $data;
}
// }}}
// {{{ setDefaultFormat()
protected function _readPropertySets(): void
{
$offset = 0;
//var_dump($this->entry);
while ($offset < strlen($this->entry)) {
$d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE);
$nameSize = ord($d[ self::SIZE_OF_NAME_POS ]) | ( ord($d[ self::SIZE_OF_NAME_POS + 1 ]) << 8 );
$type = ord($d[ self::TYPE_POS ]);
//$maxBlock = $this->_strlen($d) / self::BIG_BLOCK_SIZE - 1;
$startBlock = ord($d[ self::START_BLOCK_POS]) | ( ord($d[ self::START_BLOCK_POS + 1 ]) << 8 ) | ( ord($d[ self::START_BLOCK_POS + 2 ]) << 16 ) | ( ord($d[ self::START_BLOCK_POS + 3 ]) << 24 );
$size = ord($d[ self::SIZE_POS]) | ( ord($d[ self::SIZE_POS + 1 ]) << 8 ) | ( ord($d[ self::SIZE_POS + 2 ]) << 16 ) | ( ord($d[ self::SIZE_POS + 3 ]) << 24 );
$name = '';
for ($i = 0; $i < $nameSize; $i ++) {
$name .= $d[ $i ];
}
$name = str_replace("\x00", '', $name);
$this->props[] = array(
'name' => $name,
'type' => $type,
'startBlock' => $startBlock,
'size' => $size
);
if (( $name === 'Workbook' ) || ( $name === 'Book' )) {
$this->wrkbook = count($this->props) - 1;
}
if ($name === 'Root Entry') {
$this->rootEntry = count($this->props) - 1;
}
//echo "name ==$name=\n";
$offset += self::PROPERTY_STORAGE_BLOCK_SIZE;
}
}
// }}}
// {{{ setColumnFormat()
protected function _readWorkBook(): string
{
if ($this->props[ $this->wrkbook ]['size'] < self::SMALL_BLOCK_THRESHOLD) {
// getSmallBlockStream(PropertyStorage ps)
$rootdata = $this->_readData($this->props[ $this->rootEntry ]['startBlock']);
$streamData = '';
$block = (int) $this->props[ $this->wrkbook ]['startBlock'];
//$count = 0;
while ($block !== - 2) {
$pos = $block * self::SMALL_BLOCK_SIZE;
$streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE);
$block = $this->smallBlockChain[ $block ];
}
return $streamData;
}
$numBlocks = $this->props[ $this->wrkbook ]['size'] / self::BIG_BLOCK_SIZE;
if ($this->props[ $this->wrkbook ]['size'] % self::BIG_BLOCK_SIZE !== 0) {
$numBlocks ++;
}
if ($numBlocks === 0) {
return '';
}
//echo "numBlocks = $numBlocks\n";
//byte[] streamData = new byte[numBlocks * self::BIG_BLOCK_SIZE];
//print_r($this->wrkbook);
$streamData = '';
$block = $this->props[ $this->wrkbook ]['startBlock'];
//echo "block = $block";
while ($block !== - 2) {
$pos = ( $block + 1 ) * self::BIG_BLOCK_SIZE;
$streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
$block = $this->bigBlockChain[ $block ];
}
//echo 'stream'.$streamData;
return $streamData;
}
// }}}
protected function parseSubstreamHeader($pos): array
{
$length = $this->_getInt2d($pos + 2);
$version = $this->_getInt2d($pos + 4);
$substreamType = $this->_getInt2d($pos + 6);
return array( $length, $version, $substreamType );
}
// {{{ _parse()
/**
* Parse a workbook
*
* @access private
* @return bool
*/
protected function _parse()
{
$pos = 0;
// $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
[$length, $version, $substreamType] = $this->parseSubstreamHeader($pos);
// echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
// die();
if (( $version !== self::BIFF8 ) &&
( $version !== self::BIFF7 )
) {
return false;
}
if ($substreamType !== self::WORKBOOKGLOBALS) {
return false;
}
//print_r($rec);
$pos += $length + 4;
$code = ord($this->data[ $pos ]) | ord($this->data[ $pos + 1 ]) << 8;
$length = ord($this->data[ $pos + 2 ]) | ord($this->data[ $pos + 3 ]) << 8;
while ($code !== self::TYPE_EOF) {
switch ($code) {
case self::TYPE_SST:
//echo "Type_SST\n";
$formattingRuns = 0;
$extendedRunLength = 0;
$spos = $pos + 4;
$limitpos = $spos + $length;
$uniqueStrings = $this->_getInt4d($spos + 4);
$spos += 8;
for ($i = 0; $i < $uniqueStrings; $i ++) {
// Read in the number of characters
if ($spos === $limitpos) {
$opcode = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
$conlength = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
if ($opcode !== 0x3c) {
return - 1;
}
$spos += 4;
$limitpos = $spos + $conlength;
}
$numChars = ord($this->data[ $spos ]) | ( ord($this->data[ $spos + 1 ]) << 8 );
//echo "i = $i pos = $pos numChars = $numChars ";
$spos += 2;
$optionFlags = ord($this->data[ $spos ]);
$spos ++;
$asciiEncoding = ( ( $optionFlags & 0x01 ) === 0 );
$extendedString = ( ( $optionFlags & 0x04 ) !== 0 );
// See if string contains formatting information
$richString = ( ( $optionFlags & 0x08 ) !== 0 );
if ($richString) {
// Read in the crun
$formattingRuns = $this->_getInt2d($spos);
$spos += 2;
}
if ($extendedString) {
// Read in cchExtRst
$extendedRunLength = $this->_getInt4d($spos);
$spos += 4;
}
$len = $asciiEncoding ? $numChars : $numChars * 2;
if ($spos + $len < $limitpos) {
$retstr = substr($this->data, $spos, $len);
$spos += $len;
} else {
// found countinue
$retstr = substr($this->data, $spos, $limitpos - $spos);
$bytesRead = $limitpos - $spos;
$charsLeft = $numChars - ( $asciiEncoding ? $bytesRead : ( $bytesRead / 2 ) );
$spos = $limitpos;
while ($charsLeft > 0) {
$opcode = $this->_getInt2d($spos);
$conlength = $this->_getInt2d($spos + 2);
if ($opcode !== 0x3c) {
return - 1;
}
$spos += 4;
$limitpos = $spos + $conlength;
$option = ord($this->data[ $spos ]);
$spos ++;
if ($asciiEncoding && ( $option === 0 )) {
$len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len;
$asciiEncoding = true;
} elseif (! $asciiEncoding && ( $option !== 0 )) {
$len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len / 2;
$asciiEncoding = false;
} elseif (! $asciiEncoding && ( $option === 0 )) {
// Bummer - the string starts off as Unicode, but after the
// continuation it is in straightforward ASCII encoding
$len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
for ($j = 0; $j < $len; $j ++) {
$retstr .= $this->data[ $spos + $j ] . chr(0);
}
$charsLeft -= $len;
$asciiEncoding = false;
} else {
$newstr = '';
for ($j = 0, $len_retstr = strlen($retstr); $j < $len_retstr; $j ++) {
$newstr = $retstr[ $j ] . chr(0);
}
$retstr = $newstr;
$len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len / 2;
$asciiEncoding = false;
//echo "Izavrat\n";
}
$spos += $len;
}
}
$retstr = $asciiEncoding ? $this->_latin1toDef($retstr) : $this->_UTF16toDef($retstr);
// echo "Str $i = $retstr\n";
if ($richString) {
$spos += 4 * $formattingRuns;
}
// For extended strings, skip over the extended string data
if ($extendedString) {
$spos += $extendedRunLength;
}
//if ($retstr == 'Derby'){
// echo "bb\n";
//}
$this->sst[] = $retstr;
}
/*$continueRecords = array();
while ($this->getNextCode() == Type_CONTINUE) {
$continueRecords[] = &$this->nextRecord();
}
//echo " 1 Type_SST\n";
$this->shareStrings = new SSTRecord($r, $continueRecords);
//print_r($this->shareStrings->strings);
*/
// echo 'SST read: '.($time_end-$time_start)."\n";
break;
case self::TYPE_FILEPASS:
return false;
case self::TYPE_NAME:
//echo "Type_NAME\n";
break;
case self::TYPE_FORMAT:
$indexCode = $this->_getInt2d($pos + 4);
if ($version === self::BIFF8) {
$numchars = $this->_getInt2d($pos + 6);
if (ord($this->data[ $pos + 8 ]) === 0) { // ascii
$formatString = substr($this->data, $pos + 9, $numchars);
$formatString = $this->_latin1toDef($formatString);
} else {
$formatString = substr($this->data, $pos + 9, $numchars * 2);
$formatString = $this->_UTF16toDef($formatString);
}
} else {
$numchars = ord($this->data[ $pos + 6 ]);
$formatString = substr($this->data, $pos + 7, $numchars * 2);
$formatString = $this->_latin1toDef($formatString);
}
$this->formatRecords[ $indexCode ] = $formatString;
// echo "Type.FORMAT[$indexCode]=$formatString\n";
break;
case self::TYPE_XF:
$formatstr = '';
$indexCode = $this->_getInt2d($pos + 6);
// echo "\nType.XF code=".$indexCode." dateFormat=".$this->dateFormats[ $indexCode ]." numberFormats=".$this->numberFormats[ $indexCode ].PHP_EOL;
if (array_key_exists($indexCode, $this->dateFormats)) {
//echo "isdate ".$dateFormats[$indexCode];
$this->formatRecords['xfrecords'][] = array(
'type' => 'date',
'format' => $this->dateFormats[ $indexCode ]
);
} elseif (array_key_exists($indexCode, $this->numberFormats)) {
//echo "isnumber ".$this->numberFormats[$indexCode];
$this->formatRecords['xfrecords'][] = array(
'type' => 'number',
'format' => $this->numberFormats[ $indexCode ]
);
} else {
$isdate = false;
if ($indexCode > 0) {
if (isset($this->formatRecords[ $indexCode ])) {
// die( 'L:'.__LINE__ );
$formatstr = $this->formatRecords[ $indexCode ];
}
//echo '.other.';
// echo "\nfl=".strlen( $formatstr)." fs=$formatstr=\n";
// echo "\ncode=".$indexCode." fl=".strlen( $formatstr)." fs=$formatstr=\n";
$fs = str_replace('\\', '', $formatstr);
if ($fs && preg_match('/^[hmsday\/\-:\., ]+$/i', $fs)) { // found day and time format
$isdate = true;
$formatstr = str_replace(array( 'yyyy',':mm','mm','dddd','dd', 'h','ss' ), array('Y',':i','m','l','d', 'H','s' ), $fs);
}
}
if ($isdate) {
$this->formatRecords['xfrecords'][] = array(
'type' => 'date',
'format' => $formatstr,
'code' => $indexCode
);
} else {
// echo 'fs='.$formatstr.PHP_EOL;
$this->formatRecords['xfrecords'][] = array(
'type' => 'other',
'format' => '',
'code' => $indexCode
);
}
}
// echo count( $this->formatRecords['xfrecords'] ).' fs='.$formatstr.' ' . PHP_EOL;
//echo "\n";
break;
case self::TYPE_NINETEENFOUR:
//echo "Type.NINETEENFOUR\n";
$this->nineteenFour = ( ord($this->data[ $pos + 4 ]) === 1 );
break;
case self::TYPE_BOUNDSHEET:
//echo "Type.BOUNDSHEET\n";
$rec_offset = $this->_getInt4d($pos + 4);
// $rec_typeFlag = ord($this->_data[$pos + 8]);
$rec_length = ord($this->data[ $pos + 10 ]);
$hidden = false;
$rec_name = '';
if ($version === self::BIFF8) {
//ord($this->data[$pos + 9])
$hidden = ord($this->data[$pos + 8]) === 1;
$chartype = ord($this->data[ $pos + 11 ]);
if ($chartype === 0) {
$rec_name = substr($this->data, $pos + 12, $rec_length);
$rec_name = $this->_latin1toDef($rec_name);
} else {
$rec_name = substr($this->data, $pos + 12, $rec_length * 2);
$rec_name = $this->_UTF16toDef($rec_name);
}
} elseif ($version === self::BIFF7) {
$rec_name = substr($this->data, $pos + 11, $rec_length);
}
$this->boundsheets[] = array(
'name' => $rec_name,
'offset' => $rec_offset,
'hidden' => $hidden,
'active' => false
);
break;
case self::TYPE_WINDOW1:
$this->activeSheet = $this->_getInt2d($pos + 14);
break;
}
//echo "Code = ".base_convert($r['code'],10,16)."\n";
$pos += $length + 4;
$code = $this->_getInt2d($pos);
$length = $this->_getInt2d($pos + 2);
//$r = &$this->nextRecord();
//echo "1 Code = ".base_convert($r['code'],10,16)."\n";
}
foreach ($this->boundsheets as $key => $val) {
$this->sn = $key;
$this->_parseSheet($val['offset']);
if ($key === $this->activeSheet) {
$this->boundsheets[ $key ]['active'] = true;
}
}
return true;
}
protected function _latin1toDef($string)
{
$result = $string;
if ($this->defaultEncoding) {
$result = mb_convert_encoding($string, $this->defaultEncoding, 'ISO-8859-1');
}
return $result;
}
protected function _UTF16toDef($string)
{
$result = $string;
if ($this->defaultEncoding && $this->defaultEncoding !== 'UTF-16LE') {
$result = mb_convert_encoding($string, $this->defaultEncoding, 'UTF-16LE');
}
return $result;
}
protected function _parseSheet($spos): bool
{
$cont = true;
// read BOF
// $code = ord($this->_data[$spos]) | ord($this->_data[$spos + 1]) << 8;
[$length, $version, $substreamType] = $this->parseSubstreamHeader($spos);
if (( $version !== self::BIFF8 ) && ( $version !== self::BIFF7 )) {
return false;
}
if ($substreamType !== self::WORKSHEET) {
return false;
}
//echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
$spos += $length + 4;
//var_dump($this->formatRecords);
//echo "code $code $length";
$this->sheets[ $this->sn ]['maxrow'] = 0;
$this->sheets[ $this->sn ]['maxcol'] = 0;
$this->sheets[ $this->sn ]['numRows'] = 0;
$this->sheets[ $this->sn ]['numCols'] = 0;
while ($cont) {
//echo "mem= ".memory_get_usage()."\n";
// $r = &$this->file->nextRecord();
$lowcode = ord($this->data[ $spos ]);
if ($lowcode === self::TYPE_EOF) {
break;
}
$t_code = $lowcode | ord($this->data[ $spos + 1 ]) << 8;
$length = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
$spos += 4;
//echo "Code=".base_convert($code,10,16)." $code\n";
$this->multiplier = 1; // need for format with %
switch ($t_code) {
case self::TYPE_DIMENSION:
//echo 'Type_DIMENSION ';
if (!isset($this->numRows)) {
if (( $length === 10 ) || ( $version === self::BIFF7 )) {
$this->sheets[ $this->sn ]['numRows'] = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
$this->sheets[ $this->sn ]['numCols'] = ord($this->data[ $spos + 6 ]) | ord($this->data[ $spos + 7 ]) << 8;
} else {
$this->sheets[ $this->sn ]['numRows'] = ord($this->data[ $spos + 4 ]) | ord($this->data[ $spos + 5 ]) << 8;
$this->sheets[ $this->sn ]['numCols'] = ord($this->data[ $spos + 10 ]) | ord($this->data[ $spos + 11 ]) << 8;
}
}
//echo 'numRows '.$this->numRows.' '.$this->numCols."\n";
break;
case self::TYPE_MERGEDCELLS:
$cellRanges = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
for ($i = 0; $i < $cellRanges; $i ++) {
$fr = ord($this->data[ $spos + 8 * $i + 2 ]) | ord($this->data[ $spos + 8 * $i + 3 ]) << 8;
$lr = ord($this->data[ $spos + 8 * $i + 4 ]) | ord($this->data[ $spos + 8 * $i + 5 ]) << 8;
$fc = ord($this->data[ $spos + 8 * $i + 6 ]) | ord($this->data[ $spos + 8 * $i + 7 ]) << 8;
$lc = ord($this->data[ $spos + 8 * $i + 8 ]) | ord($this->data[ $spos + 8 * $i + 9 ]) << 8;
//$this->sheets[$this->sn]['mergedCells'][] = array($fr + 1, $fc + 1, $lr + 1, $lc + 1);
if ($lr - $fr > 0) {
$this->sheets[ $this->sn ]['cellsInfo'][ $fr + 1 ][ $fc + 1 ]['rowspan'] = $lr - $fr + 1;
}
if ($lc - $fc > 0) {
$this->sheets[ $this->sn ]['cellsInfo'][ $fr + 1 ][ $fc + 1 ]['colspan'] = $lc - $fc + 1;
}
}
//echo "Merged Cells $cellRanges $lr $fr $lc $fc\n";
break;
case self::TYPE_RK: