• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PhpSpreadsheet / 21013444139

14 Jan 2026 11:20PM UTC coverage: 96.199% (+0.2%) from 95.962%
21013444139

Pull #4657

github

web-flow
Merge dcaff346a into 48f2fe37d
Pull Request #4657: Handling Unions as Function Arguments

19 of 20 new or added lines in 1 file covered. (95.0%)

359 existing lines in 16 files now uncovered.

46287 of 48116 relevant lines covered (96.2%)

387.01 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.22
/src/PhpSpreadsheet/Shared/OLE.php
1
<?php
2

3
namespace PhpOffice\PhpSpreadsheet\Shared;
4

5
// vim: set expandtab tabstop=4 shiftwidth=4:
6
// +----------------------------------------------------------------------+
7
// | PHP Version 4                                                        |
8
// +----------------------------------------------------------------------+
9
// | Copyright (c) 1997-2002 The PHP Group                                |
10
// +----------------------------------------------------------------------+
11
// | This source file is subject to version 2.02 of the PHP license,      |
12
// | that is bundled with this package in the file LICENSE, and is        |
13
// | available at through the world-wide-web at                           |
14
// | http://www.php.net/license/2_02.txt.                                 |
15
// | If you did not receive a copy of the PHP license and are unable to   |
16
// | obtain it through the world-wide-web, please send a note to          |
17
// | license@php.net so we can mail you a copy immediately.               |
18
// +----------------------------------------------------------------------+
19
// | Author: Xavier Noguer <xnoguer@php.net>                              |
20
// | Based on OLE::Storage_Lite by Kawai, Takanori                        |
21
// +----------------------------------------------------------------------+
22
//
23

24
use PhpOffice\PhpSpreadsheet\Exception;
25
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
26
use PhpOffice\PhpSpreadsheet\Shared\OLE\ChainedBlockStream;
27
use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root;
28

29
/*
30
 * Array for storing OLE instances that are accessed from
31
 * OLE_ChainedBlockStream::stream_open().
32
 *
33
 * @var array
34
 */
35
$GLOBALS['_OLE_INSTANCES'] = [];
73✔
36

37
/**
38
 * OLE package base class.
39
 *
40
 * @author   Xavier Noguer <xnoguer@php.net>
41
 * @author   Christian Schmidt <schmidt@php.net>
42
 */
43
class OLE
44
{
45
    const OLE_PPS_TYPE_ROOT = 5;
46
    const OLE_PPS_TYPE_DIR = 1;
47
    const OLE_PPS_TYPE_FILE = 2;
48
    const OLE_DATA_SIZE_SMALL = 0x1000;
49
    const OLE_LONG_INT_SIZE = 4;
50
    const OLE_PPS_SIZE = 0x80;
51

52
    /**
53
     * The file handle for reading an OLE container.
54
     *
55
     * @var resource
56
     */
57
    public $_file_handle;
58

59
    /**
60
     * Array of PPS's found on the OLE container.
61
     *
62
     * @var array<OLE\PPS|OLE\PPS\File|Root>
63
     */
64
    public array $_list = [];
65

66
    /**
67
     * Root directory of OLE container.
68
     */
69
    public Root $root;
70

71
    /**
72
     * Big Block Allocation Table.
73
     *
74
     * @var mixed[] (blockId => nextBlockId)
75
     */
76
    public array $bbat;
77

78
    /**
79
     * Short Block Allocation Table.
80
     *
81
     * @var mixed[] (blockId => nextBlockId)
82
     */
83
    public array $sbat;
84

85
    /**
86
     * Size of big blocks. This is usually 512.
87
     *
88
     * @var int<1, max> number of octets per block
89
     */
90
    public int $bigBlockSize;
91

92
    /**
93
     * Size of small blocks. This is usually 64.
94
     *
95
     * @var int number of octets per block
96
     */
97
    public int $smallBlockSize;
98

99
    /**
100
     * Threshold for big blocks.
101
     */
102
    public int $bigBlockThreshold;
103

104
    /**
105
     * Reads an OLE container from the contents of the file given.
106
     *
107
     * @acces public
108
     *
109
     * @return bool true on success, PEAR_Error on failure
110
     */
111
    public function read(string $filename): bool
5✔
112
    {
113
        $fh = @fopen($filename, 'rb');
5✔
114
        if ($fh === false) {
5✔
115
            throw new ReaderException("Can't open file $filename");
1✔
116
        }
117
        $this->_file_handle = $fh;
4✔
118

119
        $signature = fread($fh, 8);
4✔
120
        if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) {
4✔
121
            throw new ReaderException("File doesn't seem to be an OLE container.");
1✔
122
        }
123
        fseek($fh, 28);
3✔
124
        if (fread($fh, 2) != "\xFE\xFF") {
3✔
125
            // This shouldn't be a problem in practice
126
            throw new ReaderException('Only Little-Endian encoding is supported.');
1✔
127
        }
128
        // Size of blocks and short blocks in bytes
129
        /** @var int<1, max> */
130
        $temp = 2 ** self::readInt2($fh);
2✔
131
        $this->bigBlockSize = $temp;
2✔
132
        $this->smallBlockSize = 2 ** self::readInt2($fh);
2✔
133

134
        // Skip UID, revision number and version number
135
        fseek($fh, 44);
2✔
136
        // Number of blocks in Big Block Allocation Table
137
        $bbatBlockCount = self::readInt4($fh);
2✔
138

139
        // Root chain 1st block
140
        $directoryFirstBlockId = self::readInt4($fh);
2✔
141

142
        // Skip unused bytes
143
        fseek($fh, 56);
2✔
144
        // Streams shorter than this are stored using small blocks
145
        $this->bigBlockThreshold = self::readInt4($fh);
2✔
146
        // Block id of first sector in Short Block Allocation Table
147
        $sbatFirstBlockId = self::readInt4($fh);
2✔
148
        // Number of blocks in Short Block Allocation Table
149
        $sbbatBlockCount = self::readInt4($fh);
2✔
150
        // Block id of first sector in Master Block Allocation Table
151
        $mbatFirstBlockId = self::readInt4($fh);
2✔
152
        // Number of blocks in Master Block Allocation Table
153
        $mbbatBlockCount = self::readInt4($fh);
2✔
154
        $this->bbat = [];
2✔
155

156
        // Remaining 4 * 109 bytes of current block is beginning of Master
157
        // Block Allocation Table
158
        $mbatBlocks = [];
2✔
159
        for ($i = 0; $i < 109; ++$i) {
2✔
160
            $mbatBlocks[] = self::readInt4($fh);
2✔
161
        }
162

163
        // Read rest of Master Block Allocation Table (if any is left)
164
        $pos = $this->getBlockOffset($mbatFirstBlockId);
2✔
165
        for ($i = 0; $i < $mbbatBlockCount; ++$i) {
2✔
166
            fseek($fh, $pos);
×
167
            for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) {
×
168
                $mbatBlocks[] = self::readInt4($fh);
×
169
            }
170
            // Last block id in each block points to next block
171
            $pos = $this->getBlockOffset(self::readInt4($fh));
×
172
        }
173

174
        // Read Big Block Allocation Table according to chain specified by $mbatBlocks
175
        for ($i = 0; $i < $bbatBlockCount; ++$i) {
2✔
176
            $pos = $this->getBlockOffset($mbatBlocks[$i]);
2✔
177
            fseek($fh, $pos);
2✔
178
            for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) {
2✔
179
                $this->bbat[] = self::readInt4($fh);
2✔
180
            }
181
        }
182

183
        // Read short block allocation table (SBAT)
184
        $this->sbat = [];
2✔
185
        $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4;
2✔
186
        $sbatFh = $this->getStream($sbatFirstBlockId);
2✔
187
        for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) {
2✔
188
            $this->sbat[$blockId] = self::readInt4($sbatFh);
1✔
189
        }
190
        fclose($sbatFh);
2✔
191

192
        $this->readPpsWks($directoryFirstBlockId);
2✔
193

194
        return true;
2✔
195
    }
196

197
    /**
198
     * @param int $blockId byte offset from beginning of file
199
     */
200
    public function getBlockOffset(int $blockId): int
2✔
201
    {
202
        return 512 + $blockId * $this->bigBlockSize;
2✔
203
    }
204

205
    /**
206
     * Returns a stream for use with fread() etc. External callers should
207
     * use \PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File::getStream().
208
     *
209
     * @param int|OLE\PPS $blockIdOrPps block id or PPS
210
     *
211
     * @return resource read-only stream
212
     */
213
    public function getStream($blockIdOrPps)
2✔
214
    {
215
        static $isRegistered = false;
2✔
216
        if (!$isRegistered) {
2✔
217
            stream_wrapper_register('ole-chainedblockstream', ChainedBlockStream::class);
1✔
218
            $isRegistered = true;
1✔
219
        }
220

221
        // Store current instance in global array, so that it can be accessed
222
        // in OLE_ChainedBlockStream::stream_open().
223
        // Object is removed from self::$instances in OLE_Stream::close().
224
        $GLOBALS['_OLE_INSTANCES'][] = $this; //* @phpstan-ignore-line
2✔
225
        $keys = array_keys($GLOBALS['_OLE_INSTANCES']); //* @phpstan-ignore-line
2✔
226
        $instanceId = end($keys);
2✔
227

228
        $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId;
2✔
229
        if ($blockIdOrPps instanceof OLE\PPS) {
2✔
230
            $path .= '&blockId=' . $blockIdOrPps->startBlock;
1✔
231
            $path .= '&size=' . $blockIdOrPps->Size;
1✔
232
        } else {
233
            $path .= '&blockId=' . $blockIdOrPps;
2✔
234
        }
235

236
        $resource = fopen($path, 'rb') ?: throw new Exception("Unable to open stream $path");
2✔
237

238
        return $resource;
2✔
239
    }
240

241
    /**
242
     * Reads a signed char.
243
     *
244
     * @param resource $fileHandle file handle
245
     */
246
    private static function readInt1($fileHandle): int
2✔
247
    {
248
        [, $tmp] = unpack('c', fread($fileHandle, 1) ?: '') ?: [0, 0];
2✔
249
        /** @var int $tmp */
250

251
        return $tmp;
2✔
252
    }
253

254
    /**
255
     * Reads an unsigned short (2 octets).
256
     *
257
     * @param resource $fileHandle file handle
258
     */
259
    private static function readInt2($fileHandle): int
2✔
260
    {
261
        [, $tmp] = unpack('v', fread($fileHandle, 2) ?: '') ?: [0, 0];
2✔
262
        /** @var int $tmp */
263

264
        return $tmp;
2✔
265
    }
266

267
    private const SIGNED_4OCTET_LIMIT = 2147483648;
268

269
    private const SIGNED_4OCTET_SUBTRACT = 2 * self::SIGNED_4OCTET_LIMIT;
270

271
    /**
272
     * Reads long (4 octets), interpreted as if signed on 32-bit system.
273
     *
274
     * @param resource $fileHandle file handle
275
     */
276
    private static function readInt4($fileHandle): int
2✔
277
    {
278
        [, $tmp] = unpack('V', fread($fileHandle, 4) ?: '') ?: [0, 0];
2✔
279
        /** @var int $tmp */
280
        if ($tmp >= self::SIGNED_4OCTET_LIMIT) {
2✔
281
            $tmp -= self::SIGNED_4OCTET_SUBTRACT;
2✔
282
        }
283

284
        return $tmp;
2✔
285
    }
286

287
    /**
288
     * Gets information about all PPS's on the OLE container from the PPS WK's
289
     * creates an OLE_PPS object for each one.
290
     *
291
     * @param int $blockId the block id of the first block
292
     *
293
     * @return bool true on success, PEAR_Error on failure
294
     */
295
    public function readPpsWks(int $blockId): bool
2✔
296
    {
297
        $fh = $this->getStream($blockId);
2✔
298
        for ($pos = 0; true; $pos += 128) {
2✔
299
            fseek($fh, $pos, SEEK_SET);
2✔
300
            $nameUtf16 = (string) fread($fh, 64);
2✔
301
            $nameLength = self::readInt2($fh);
2✔
302
            $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2);
2✔
303
            // Simple conversion from UTF-16LE to ISO-8859-1
304
            $name = str_replace("\x00", '', $nameUtf16);
2✔
305
            $type = self::readInt1($fh);
2✔
306
            switch ($type) {
307
                case self::OLE_PPS_TYPE_ROOT:
308
                    $pps = new Root(null, null, []);
2✔
309
                    $this->root = $pps;
2✔
310

311
                    break;
2✔
312
                case self::OLE_PPS_TYPE_DIR:
UNCOV
313
                    $pps = new OLE\PPS(null, null, null, null, null, null, null, null, null, []);
×
314

UNCOV
315
                    break;
×
316
                case self::OLE_PPS_TYPE_FILE:
317
                    $pps = new OLE\PPS\File($name);
2✔
318

319
                    break;
2✔
320
                default:
UNCOV
321
                    throw new Exception('Unsupported PPS type');
×
322
            }
323
            fseek($fh, 1, SEEK_CUR);
2✔
324
            $pps->Type = $type;
2✔
325
            $pps->Name = $name;
2✔
326
            $pps->PrevPps = self::readInt4($fh);
2✔
327
            $pps->NextPps = self::readInt4($fh);
2✔
328
            $pps->DirPps = self::readInt4($fh);
2✔
329
            fseek($fh, 20, SEEK_CUR);
2✔
330
            $pps->Time1st = self::OLE2LocalDate((string) fread($fh, 8));
2✔
331
            $pps->Time2nd = self::OLE2LocalDate((string) fread($fh, 8));
2✔
332
            $pps->startBlock = self::readInt4($fh);
2✔
333
            $pps->Size = self::readInt4($fh);
2✔
334
            $pps->No = count($this->_list);
2✔
335
            $this->_list[] = $pps;
2✔
336

337
            // check if the PPS tree (starting from root) is complete
338
            if (isset($this->root) && $this->ppsTreeComplete($this->root->No)) {
2✔
339
                break;
2✔
340
            }
341
        }
342
        fclose($fh);
2✔
343

344
        // Initialize $pps->children on directories
345
        foreach ($this->_list as $pps) {
2✔
346
            if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) {
2✔
347
                $nos = [$pps->DirPps];
2✔
348
                $pps->children = [];
2✔
349
                while (!empty($nos)) {
2✔
350
                    $no = array_pop($nos);
2✔
351
                    if ($no != -1) {
2✔
352
                        $childPps = $this->_list[$no];
2✔
353
                        $nos[] = $childPps->PrevPps;
2✔
354
                        $nos[] = $childPps->NextPps;
2✔
355
                        $pps->children[] = $childPps;
2✔
356
                    }
357
                }
358
            }
359
        }
360

361
        return true;
2✔
362
    }
363

364
    /**
365
     * It checks whether the PPS tree is complete (all PPS's read)
366
     * starting with the given PPS (not necessarily root).
367
     *
368
     * @param int $index The index of the PPS from which we are checking
369
     *
370
     * @return bool Whether the PPS tree for the given PPS is complete
371
     */
372
    private function ppsTreeComplete(int $index): bool
2✔
373
    {
374
        if (!isset($this->_list[$index])) {
2✔
375
            return false;
2✔
376
        }
377
        $pps = $this->_list[$index];
2✔
378

379
        return
2✔
380
            ($pps->PrevPps == -1
2✔
381
                || $this->ppsTreeComplete($pps->PrevPps))
2✔
382
            && ($pps->NextPps == -1
2✔
383
                || $this->ppsTreeComplete($pps->NextPps))
2✔
384
            && ($pps->DirPps == -1
2✔
385
                || $this->ppsTreeComplete($pps->DirPps));
2✔
386
    }
387

388
    /**
389
     * Checks whether a PPS is a File PPS or not.
390
     * If there is no PPS for the index given, it will return false.
391
     *
392
     * @param int $index The index for the PPS
393
     *
394
     * @return bool true if it's a File PPS, false otherwise
395
     */
396
    public function isFile(int $index): bool
1✔
397
    {
398
        if (isset($this->_list[$index])) {
1✔
399
            return $this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE;
1✔
400
        }
401

402
        return false;
1✔
403
    }
404

405
    /**
406
     * Checks whether a PPS is a Root PPS or not.
407
     * If there is no PPS for the index given, it will return false.
408
     *
409
     * @param int $index the index for the PPS
410
     *
411
     * @return bool true if it's a Root PPS, false otherwise
412
     */
413
    public function isRoot(int $index): bool
1✔
414
    {
415
        if (isset($this->_list[$index])) {
1✔
416
            return $this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT;
1✔
417
        }
418

419
        return false;
1✔
420
    }
421

422
    /**
423
     * Gives the total number of PPS's found in the OLE container.
424
     *
425
     * @return int The total number of PPS's found in the OLE container
426
     */
427
    public function ppsTotal(): int
1✔
428
    {
429
        return count($this->_list);
1✔
430
    }
431

432
    /**
433
     * Gets data from a PPS
434
     * If there is no PPS for the index given, it will return an empty string.
435
     *
436
     * @param int $index The index for the PPS
437
     * @param int $position The position from which to start reading
438
     *                          (relative to the PPS)
439
     * @param int $length The amount of bytes to read (at most)
440
     *
441
     * @return string The binary string containing the data requested
442
     *
443
     * @see OLE_PPS_File::getStream()
444
     */
445
    public function getData(int $index, int $position, int $length): string
1✔
446
    {
447
        // if position is not valid return empty string
448
        if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) {
1✔
449
            return '';
1✔
450
        }
451
        $fh = $this->getStream($this->_list[$index]);
1✔
452
        $data = (string) stream_get_contents($fh, $length, $position);
1✔
453
        fclose($fh);
1✔
454

455
        return $data;
1✔
456
    }
457

458
    /**
459
     * Gets the data length from a PPS
460
     * If there is no PPS for the index given, it will return 0.
461
     *
462
     * @param int $index The index for the PPS
463
     *
464
     * @return int The amount of bytes in data the PPS has
465
     */
466
    public function getDataLength(int $index): int
1✔
467
    {
468
        if (isset($this->_list[$index])) {
1✔
469
            return $this->_list[$index]->Size;
1✔
470
        }
471

472
        return 0;
1✔
473
    }
474

475
    /**
476
     * Utility function to transform ASCII text to Unicode.
477
     *
478
     * @param string $ascii The ASCII string to transform
479
     *
480
     * @return string The string in Unicode
481
     */
482
    public static function ascToUcs(string $ascii): string
131✔
483
    {
484
        $rawname = '';
131✔
485
        $iMax = strlen($ascii);
131✔
486
        for ($i = 0; $i < $iMax; ++$i) {
131✔
487
            $rawname .= $ascii[$i]
131✔
488
                . "\x00";
131✔
489
        }
490

491
        return $rawname;
131✔
492
    }
493

494
    /**
495
     * Utility function
496
     * Returns a string for the OLE container with the date given.
497
     *
498
     * @param float|int $date A timestamp
499
     *
500
     * @return string The string for the OLE container
501
     */
502
    public static function localDateToOLE($date): string
128✔
503
    {
504
        if (!$date) {
128✔
505
            return "\x00\x00\x00\x00\x00\x00\x00\x00";
128✔
506
        }
507
        $dateTime = Date::dateTimeFromTimestamp("$date");
128✔
508

509
        // days from 1-1-1601 until the beginning of UNIX era
510
        $days = 134774;
128✔
511
        // calculate seconds
512
        $big_date = $days * 24 * 3600 + (float) $dateTime->format('U');
128✔
513
        // multiply just to make MS happy
514
        $big_date *= 10000000;
128✔
515

516
        // Make HEX string
517
        $res = '';
128✔
518

519
        $factor = 2 ** 56;
128✔
520
        while ($factor >= 1) {
128✔
521
            $hex = (int) floor($big_date / $factor);
128✔
522
            $res = pack('c', $hex) . $res;
128✔
523
            $big_date = fmod($big_date, $factor);
128✔
524
            $factor /= 256;
128✔
525
        }
526

527
        return $res;
128✔
528
    }
529

530
    /**
531
     * Returns a timestamp from an OLE container's date.
532
     *
533
     * @param string $oleTimestamp A binary string with the encoded date
534
     *
535
     * @return float|int The Unix timestamp corresponding to the string
536
     */
537
    public static function OLE2LocalDate(string $oleTimestamp)
138✔
538
    {
539
        if (strlen($oleTimestamp) != 8) {
138✔
540
            throw new ReaderException('Expecting 8 byte string');
1✔
541
        }
542

543
        // convert to units of 100 ns since 1601:
544
        /** @var int[] */
545
        $unpackedTimestamp = unpack('v4', $oleTimestamp) ?: [];
137✔
546
        $timestampHigh = (float) $unpackedTimestamp[4] * 65536 + (float) $unpackedTimestamp[3];
137✔
547
        $timestampLow = (float) $unpackedTimestamp[2] * 65536 + (float) $unpackedTimestamp[1];
137✔
548

549
        // translate to seconds since 1601:
550
        $timestampHigh /= 10000000;
137✔
551
        $timestampLow /= 10000000;
137✔
552

553
        // days from 1601 to 1970:
554
        $days = 134774;
137✔
555

556
        // translate to seconds since 1970:
557
        $unixTimestamp = floor(65536.0 * 65536.0 * $timestampHigh + $timestampLow - $days * 24 * 3600 + 0.5);
137✔
558

559
        return IntOrFloat::evaluate($unixTimestamp);
137✔
560
    }
561
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc