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

PHPOffice / PhpSpreadsheet / 18013950625

25 Sep 2025 04:20PM UTC coverage: 95.867% (+0.3%) from 95.602%
18013950625

push

github

web-flow
Merge pull request #4663 from oleibman/tweakcoveralls

Tweak Coveralls

45116 of 47061 relevant lines covered (95.87%)

373.63 hits per line

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

82.89
/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
3✔
112
    {
113
        $fh = @fopen($filename, 'rb');
3✔
114
        if ($fh === false) {
3✔
115
            throw new ReaderException("Can't open file $filename");
1✔
116
        }
117
        $this->_file_handle = $fh;
2✔
118

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

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

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

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

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

163
        // Read rest of Master Block Allocation Table (if any is left)
164
        $pos = $this->getBlockOffset($mbatFirstBlockId);
1✔
165
        for ($i = 0; $i < $mbbatBlockCount; ++$i) {
1✔
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) {
1✔
176
            $pos = $this->getBlockOffset($mbatBlocks[$i]);
1✔
177
            fseek($fh, $pos);
1✔
178
            for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) {
1✔
179
                $this->bbat[] = self::readInt4($fh);
1✔
180
            }
181
        }
182

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

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

194
        return true;
1✔
195
    }
196

197
    /**
198
     * @param int $blockId byte offset from beginning of file
199
     */
200
    public function getBlockOffset(int $blockId): int
1✔
201
    {
202
        return 512 + $blockId * $this->bigBlockSize;
1✔
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)
1✔
214
    {
215
        static $isRegistered = false;
1✔
216
        if (!$isRegistered) {
1✔
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
1✔
225
        $keys = array_keys($GLOBALS['_OLE_INSTANCES']); //* @phpstan-ignore-line
1✔
226
        $instanceId = end($keys);
1✔
227

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

236
        $resource = fopen($path, 'rb');
1✔
237
        if ($resource === false) {
1✔
238
            throw new Exception("Unable to open stream $path");
×
239
        }
240

241
        return $resource;
1✔
242
    }
243

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

254
        return $tmp;
1✔
255
    }
256

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

267
        return $tmp;
1✔
268
    }
269

270
    private const SIGNED_4OCTET_LIMIT = 2147483648;
271

272
    private const SIGNED_4OCTET_SUBTRACT = 2 * self::SIGNED_4OCTET_LIMIT;
273

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

287
        return $tmp;
1✔
288
    }
289

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

314
                    break;
1✔
315
                case self::OLE_PPS_TYPE_DIR:
316
                    $pps = new OLE\PPS(null, null, null, null, null, null, null, null, null, []);
×
317

318
                    break;
×
319
                case self::OLE_PPS_TYPE_FILE:
320
                    $pps = new OLE\PPS\File($name);
1✔
321

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

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

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

364
        return true;
1✔
365
    }
366

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

382
        return
1✔
383
            ($pps->PrevPps == -1
1✔
384
                || $this->ppsTreeComplete($pps->PrevPps))
1✔
385
            && ($pps->NextPps == -1
1✔
386
                || $this->ppsTreeComplete($pps->NextPps))
1✔
387
            && ($pps->DirPps == -1
1✔
388
                || $this->ppsTreeComplete($pps->DirPps));
1✔
389
    }
390

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

405
        return false;
×
406
    }
407

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

422
        return false;
×
423
    }
424

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

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

458
        return $data;
×
459
    }
460

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

475
        return 0;
×
476
    }
477

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

494
        return $rawname;
126✔
495
    }
496

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

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

519
        // Make HEX string
520
        $res = '';
124✔
521

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

530
        return $res;
124✔
531
    }
532

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

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

552
        // translate to seconds since 1601:
553
        $timestampHigh /= 10000000;
134✔
554
        $timestampLow /= 10000000;
134✔
555

556
        // days from 1601 to 1970:
557
        $days = 134774;
134✔
558

559
        // translate to seconds since 1970:
560
        $unixTimestamp = floor(65536.0 * 65536.0 * $timestampHigh + $timestampLow - $days * 24 * 3600 + 0.5);
134✔
561

562
        return IntOrFloat::evaluate($unixTimestamp);
134✔
563
    }
564
}
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