first commit

This commit is contained in:
2026-07-03 15:46:56 -04:00
commit bf8532aa1e
1545 changed files with 450330 additions and 0 deletions
@@ -0,0 +1,71 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
class Biff5 extends Xls
{
/**
* Reads a cell range address in BIFF5 e.g. 'A2:B6' or 'A1'
* always fixed range
* section 2.5.14.
*/
public static function readBIFF5CellRangeAddressFixed(string $subData): string
{
// offset: 0; size: 2; index to first row
$fr = self::getUInt2d($subData, 0) + 1;
// offset: 2; size: 2; index to last row
$lr = self::getUInt2d($subData, 2) + 1;
// offset: 4; size: 1; index to first column
$fc = ord($subData[4]);
// offset: 5; size: 1; index to last column
$lc = ord($subData[5]);
// check values
if ($fr > $lr || $fc > $lc) {
throw new ReaderException('Not a cell range address');
}
// column index to letter
$fc = Coordinate::stringFromColumnIndex($fc + 1);
$lc = Coordinate::stringFromColumnIndex($lc + 1);
if ($fr == $lr && $fc == $lc) {
return "$fc$fr";
}
return "$fc$fr:$lc$lr";
}
/**
* Read BIFF5 cell range address list
* section 2.5.15.
*
* @return array{size: int, cellRangeAddresses: string[]}
*/
public static function readBIFF5CellRangeAddressList(string $subData): array
{
$cellRangeAddresses = [];
// offset: 0; size: 2; number of the following cell range addresses
$nm = self::getUInt2d($subData, 0);
$offset = 2;
// offset: 2; size: 6 * $nm; list of $nm (fixed) cell range addresses
for ($i = 0; $i < $nm; ++$i) {
$cellRangeAddresses[] = self::readBIFF5CellRangeAddressFixed(substr($subData, $offset, 6));
$offset += 6;
}
return [
'size' => 2 + 6 * $nm,
'cellRangeAddresses' => $cellRangeAddresses,
];
}
}
@@ -0,0 +1,371 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
class Biff8 extends Xls
{
/**
* read BIFF8 constant value array from array data
* returns e.g. ['value' => '{1,2;3,4}', 'size' => 40]
* section 2.5.8.
*
* @return array{value: string, size: int}
*/
protected static function readBIFF8ConstantArray(string $arrayData): array
{
// offset: 0; size: 1; number of columns decreased by 1
$nc = ord($arrayData[0]);
// offset: 1; size: 2; number of rows decreased by 1
$nr = self::getUInt2d($arrayData, 1);
$size = 3; // initialize
$arrayData = substr($arrayData, 3);
// offset: 3; size: var; list of ($nc + 1) * ($nr + 1) constant values
$matrixChunks = [];
for ($r = 1; $r <= $nr + 1; ++$r) {
$items = [];
for ($c = 1; $c <= $nc + 1; ++$c) {
$constant = self::readBIFF8Constant($arrayData);
$items[] = $constant['value'];
$arrayData = substr($arrayData, $constant['size']);
$size += $constant['size'];
}
$matrixChunks[] = implode(',', $items); // looks like e.g. '1,"hello"'
}
$matrix = '{' . implode(';', $matrixChunks) . '}';
return [
'value' => $matrix,
'size' => $size,
];
}
/**
* read BIFF8 constant value which may be 'Empty Value', 'Number', 'String Value', 'Boolean Value', 'Error Value'
* section 2.5.7
* returns e.g. ['value' => '5', 'size' => 9].
*
* @return array{value: bool|float|int|string, size: int}
*/
private static function readBIFF8Constant(string $valueData): array
{
// offset: 0; size: 1; identifier for type of constant
$identifier = ord($valueData[0]);
switch ($identifier) {
case 0x00: // empty constant (what is this?)
$value = '';
$size = 9;
break;
case 0x01: // number
// offset: 1; size: 8; IEEE 754 floating-point value
$value = self::extractNumber(substr($valueData, 1, 8));
$size = 9;
break;
case 0x02: // string value
// offset: 1; size: var; Unicode string, 16-bit string length
$string = self::readUnicodeStringLong(substr($valueData, 1));
$value = '"' . $string['value'] . '"';
$size = 1 + $string['size'];
break;
case 0x04: // boolean
// offset: 1; size: 1; 0 = FALSE, 1 = TRUE
if (ord($valueData[1])) {
$value = 'TRUE';
} else {
$value = 'FALSE';
}
$size = 9;
break;
case 0x10: // error code
// offset: 1; size: 1; error code
$value = ErrorCode::lookup(ord($valueData[1]));
$size = 9;
break;
default:
throw new ReaderException('Unsupported BIFF8 constant');
}
return [
'value' => $value,
'size' => $size,
];
}
/**
* Read BIFF8 cell range address list
* section 2.5.15.
*
* @return array{size: int, cellRangeAddresses: mixed[]}
*/
public static function readBIFF8CellRangeAddressList(string $subData): array
{
$cellRangeAddresses = [];
// offset: 0; size: 2; number of the following cell range addresses
$nm = self::getUInt2d($subData, 0);
$offset = 2;
// offset: 2; size: 8 * $nm; list of $nm (fixed) cell range addresses
for ($i = 0; $i < $nm; ++$i) {
$cellRangeAddresses[] = self::readBIFF8CellRangeAddressFixed(substr($subData, $offset, 8));
$offset += 8;
}
return [
'size' => 2 + 8 * $nm,
'cellRangeAddresses' => $cellRangeAddresses,
];
}
/**
* Reads a cell address in BIFF8 e.g. 'A2' or '$A$2'
* section 3.3.4.
*/
protected static function readBIFF8CellAddress(string $cellAddressStructure): string
{
// offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767))
$row = self::getUInt2d($cellAddressStructure, 0) + 1;
// offset: 2; size: 2; index to column or column offset + relative flags
// bit: 7-0; mask 0x00FF; column index
$column = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($cellAddressStructure, 2)) + 1);
// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
if (!(0x4000 & self::getUInt2d($cellAddressStructure, 2))) {
$column = '$' . $column;
}
// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
if (!(0x8000 & self::getUInt2d($cellAddressStructure, 2))) {
$row = '$' . $row;
}
return $column . $row;
}
/**
* Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column
* to indicate offsets from a base cell
* section 3.3.4.
*
* @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
*/
protected static function readBIFF8CellAddressB(string $cellAddressStructure, string $baseCell = 'A1'): string
{
[$baseCol, $baseRow] = Coordinate::coordinateFromString($baseCell);
$baseCol = Coordinate::columnIndexFromString($baseCol) - 1;
$baseRow = (int) $baseRow;
// offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767))
$rowIndex = self::getUInt2d($cellAddressStructure, 0);
$row = self::getUInt2d($cellAddressStructure, 0) + 1;
// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
if (!(0x4000 & self::getUInt2d($cellAddressStructure, 2))) {
// offset: 2; size: 2; index to column or column offset + relative flags
// bit: 7-0; mask 0x00FF; column index
$colIndex = 0x00FF & self::getUInt2d($cellAddressStructure, 2);
$column = Coordinate::stringFromColumnIndex($colIndex + 1);
$column = '$' . $column;
} else {
// offset: 2; size: 2; index to column or column offset + relative flags
// bit: 7-0; mask 0x00FF; column index
$relativeColIndex = 0x00FF & self::getInt2d($cellAddressStructure, 2);
$colIndex = $baseCol + $relativeColIndex;
$colIndex = ($colIndex < 256) ? $colIndex : $colIndex - 256;
$colIndex = ($colIndex >= 0) ? $colIndex : $colIndex + 256;
$column = Coordinate::stringFromColumnIndex($colIndex + 1);
}
// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
if (!(0x8000 & self::getUInt2d($cellAddressStructure, 2))) {
$row = '$' . $row;
} else {
$rowIndex = ($rowIndex <= 32767) ? $rowIndex : $rowIndex - 65536;
$row = $baseRow + $rowIndex;
}
return $column . $row;
}
/**
* Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1'
* always fixed range
* section 2.5.14.
*/
protected static function readBIFF8CellRangeAddressFixed(string $subData): string
{
// offset: 0; size: 2; index to first row
$fr = self::getUInt2d($subData, 0) + 1;
// offset: 2; size: 2; index to last row
$lr = self::getUInt2d($subData, 2) + 1;
// offset: 4; size: 2; index to first column
$fc = self::getUInt2d($subData, 4);
// offset: 6; size: 2; index to last column
$lc = self::getUInt2d($subData, 6);
// check values
if ($fr > $lr || $fc > $lc) {
throw new ReaderException('Not a cell range address');
}
// column index to letter
$fc = Coordinate::stringFromColumnIndex($fc + 1);
$lc = Coordinate::stringFromColumnIndex($lc + 1);
if ($fr == $lr && $fc == $lc) {
return "$fc$fr";
}
return "$fc$fr:$lc$lr";
}
/**
* Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6'
* there are flags indicating whether column/row index is relative
* section 3.3.4.
*/
protected static function readBIFF8CellRangeAddress(string $subData): string
{
// todo: if cell range is just a single cell, should this funciton
// not just return e.g. 'A1' and not 'A1:A1' ?
// offset: 0; size: 2; index to first row (0... 65535) (or offset (-32768... 32767))
$fr = self::getUInt2d($subData, 0) + 1;
// offset: 2; size: 2; index to last row (0... 65535) (or offset (-32768... 32767))
$lr = self::getUInt2d($subData, 2) + 1;
// offset: 4; size: 2; index to first column or column offset + relative flags
// bit: 7-0; mask 0x00FF; column index
$fc = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($subData, 4)) + 1);
// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
if (!(0x4000 & self::getUInt2d($subData, 4))) {
$fc = '$' . $fc;
}
// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
if (!(0x8000 & self::getUInt2d($subData, 4))) {
$fr = '$' . $fr;
}
// offset: 6; size: 2; index to last column or column offset + relative flags
// bit: 7-0; mask 0x00FF; column index
$lc = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($subData, 6)) + 1);
// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
if (!(0x4000 & self::getUInt2d($subData, 6))) {
$lc = '$' . $lc;
}
// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
if (!(0x8000 & self::getUInt2d($subData, 6))) {
$lr = '$' . $lr;
}
return "$fc$fr:$lc$lr";
}
/**
* Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column
* to indicate offsets from a base cell
* section 3.3.4.
*
* @param string $baseCell Base cell
*
* @return string Cell range address
*/
protected static function readBIFF8CellRangeAddressB(string $subData, string $baseCell = 'A1'): string
{
[$baseCol, $baseRow] = Coordinate::indexesFromString($baseCell);
$baseCol = $baseCol - 1;
// TODO: if cell range is just a single cell, should this funciton
// not just return e.g. 'A1' and not 'A1:A1' ?
// offset: 0; size: 2; first row
$frIndex = self::getUInt2d($subData, 0); // adjust below
// offset: 2; size: 2; relative index to first row (0... 65535) should be treated as offset (-32768... 32767)
$lrIndex = self::getUInt2d($subData, 2); // adjust below
// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
if (!(0x4000 & self::getUInt2d($subData, 4))) {
// absolute column index
// offset: 4; size: 2; first column with relative/absolute flags
// bit: 7-0; mask 0x00FF; column index
$fcIndex = 0x00FF & self::getUInt2d($subData, 4);
$fc = Coordinate::stringFromColumnIndex($fcIndex + 1);
$fc = '$' . $fc;
} else {
// column offset
// offset: 4; size: 2; first column with relative/absolute flags
// bit: 7-0; mask 0x00FF; column index
$relativeFcIndex = 0x00FF & self::getInt2d($subData, 4);
$fcIndex = $baseCol + $relativeFcIndex;
$fcIndex = ($fcIndex < 256) ? $fcIndex : $fcIndex - 256;
$fcIndex = ($fcIndex >= 0) ? $fcIndex : $fcIndex + 256;
$fc = Coordinate::stringFromColumnIndex($fcIndex + 1);
}
// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
if (!(0x8000 & self::getUInt2d($subData, 4))) {
// absolute row index
$fr = $frIndex + 1;
$fr = '$' . $fr;
} else {
// row offset
$frIndex = ($frIndex <= 32767) ? $frIndex : $frIndex - 65536;
$fr = $baseRow + $frIndex;
}
// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
if (!(0x4000 & self::getUInt2d($subData, 6))) {
// absolute column index
// offset: 6; size: 2; last column with relative/absolute flags
// bit: 7-0; mask 0x00FF; column index
$lcIndex = 0x00FF & self::getUInt2d($subData, 6);
$lc = Coordinate::stringFromColumnIndex($lcIndex + 1);
$lc = '$' . $lc;
} else {
// column offset
// offset: 6; size: 2; last column with relative/absolute flags
// bit: 7-0; mask 0x00FF; column index
$relativeLcIndex = 0x00FF & self::getInt2d($subData, 6);
$lcIndex = $baseCol + $relativeLcIndex;
$lcIndex = ($lcIndex < 256) ? $lcIndex : $lcIndex - 256;
$lcIndex = ($lcIndex >= 0) ? $lcIndex : $lcIndex + 256;
$lc = Coordinate::stringFromColumnIndex($lcIndex + 1);
}
// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
if (!(0x8000 & self::getUInt2d($subData, 6))) {
// absolute row index
$lr = $lrIndex + 1;
$lr = '$' . $lr;
} else {
// row offset
$lrIndex = ($lrIndex <= 32767) ? $lrIndex : $lrIndex - 65536;
$lr = $baseRow + $lrIndex;
}
return "$fc$fr:$lc$lr";
}
}
@@ -0,0 +1,29 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
class Color
{
/**
* Read color.
*
* @param int $color Indexed color
* @param string[][] $palette Color palette
*
* @return string[] RGB color value, example: ['rgb' => 'FF0000']
*/
public static function map(int $color, array $palette, int $version): array
{
if ($color <= 0x07 || $color >= 0x40) {
// special built-in color
return Color\BuiltIn::lookup($color);
} elseif (isset($palette[$color - 8])) {
// palette color, color index 0x08 maps to pallete index 0
return $palette[$color - 8];
}
return ($version === Xls::XLS_BIFF8) ? Color\BIFF8::lookup($color) : Color\BIFF5::lookup($color);
}
}
@@ -0,0 +1,75 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color;
class BIFF5
{
private const BIFF5_COLOR_MAP = [
0x08 => '000000',
0x09 => 'FFFFFF',
0x0A => 'FF0000',
0x0B => '00FF00',
0x0C => '0000FF',
0x0D => 'FFFF00',
0x0E => 'FF00FF',
0x0F => '00FFFF',
0x10 => '800000',
0x11 => '008000',
0x12 => '000080',
0x13 => '808000',
0x14 => '800080',
0x15 => '008080',
0x16 => 'C0C0C0',
0x17 => '808080',
0x18 => '8080FF',
0x19 => '802060',
0x1A => 'FFFFC0',
0x1B => 'A0E0F0',
0x1C => '600080',
0x1D => 'FF8080',
0x1E => '0080C0',
0x1F => 'C0C0FF',
0x20 => '000080',
0x21 => 'FF00FF',
0x22 => 'FFFF00',
0x23 => '00FFFF',
0x24 => '800080',
0x25 => '800000',
0x26 => '008080',
0x27 => '0000FF',
0x28 => '00CFFF',
0x29 => '69FFFF',
0x2A => 'E0FFE0',
0x2B => 'FFFF80',
0x2C => 'A6CAF0',
0x2D => 'DD9CB3',
0x2E => 'B38FEE',
0x2F => 'E3E3E3',
0x30 => '2A6FF9',
0x31 => '3FB8CD',
0x32 => '488436',
0x33 => '958C41',
0x34 => '8E5E42',
0x35 => 'A0627A',
0x36 => '624FAC',
0x37 => '969696',
0x38 => '1D2FBE',
0x39 => '286676',
0x3A => '004500',
0x3B => '453E01',
0x3C => '6A2813',
0x3D => '85396A',
0x3E => '4A3285',
0x3F => '424242',
];
/**
* Map color array from BIFF5 built-in color index.
*
* @return array{rgb: string}
*/
public static function lookup(int $color): array
{
return ['rgb' => self::BIFF5_COLOR_MAP[$color] ?? '000000'];
}
}
@@ -0,0 +1,75 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color;
class BIFF8
{
private const BIFF8_COLOR_MAP = [
0x08 => '000000',
0x09 => 'FFFFFF',
0x0A => 'FF0000',
0x0B => '00FF00',
0x0C => '0000FF',
0x0D => 'FFFF00',
0x0E => 'FF00FF',
0x0F => '00FFFF',
0x10 => '800000',
0x11 => '008000',
0x12 => '000080',
0x13 => '808000',
0x14 => '800080',
0x15 => '008080',
0x16 => 'C0C0C0',
0x17 => '808080',
0x18 => '9999FF',
0x19 => '993366',
0x1A => 'FFFFCC',
0x1B => 'CCFFFF',
0x1C => '660066',
0x1D => 'FF8080',
0x1E => '0066CC',
0x1F => 'CCCCFF',
0x20 => '000080',
0x21 => 'FF00FF',
0x22 => 'FFFF00',
0x23 => '00FFFF',
0x24 => '800080',
0x25 => '800000',
0x26 => '008080',
0x27 => '0000FF',
0x28 => '00CCFF',
0x29 => 'CCFFFF',
0x2A => 'CCFFCC',
0x2B => 'FFFF99',
0x2C => '99CCFF',
0x2D => 'FF99CC',
0x2E => 'CC99FF',
0x2F => 'FFCC99',
0x30 => '3366FF',
0x31 => '33CCCC',
0x32 => '99CC00',
0x33 => 'FFCC00',
0x34 => 'FF9900',
0x35 => 'FF6600',
0x36 => '666699',
0x37 => '969696',
0x38 => '003366',
0x39 => '339966',
0x3A => '003300',
0x3B => '333300',
0x3C => '993300',
0x3D => '993366',
0x3E => '333399',
0x3F => '333333',
];
/**
* Map color array from BIFF8 built-in color index.
*
* @return array{rgb: string}
*/
public static function lookup(int $color): array
{
return ['rgb' => self::BIFF8_COLOR_MAP[$color] ?? '000000'];
}
}
@@ -0,0 +1,31 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color;
class BuiltIn
{
private const BUILTIN_COLOR_MAP = [
0x00 => '000000',
0x01 => 'FFFFFF',
0x02 => 'FF0000',
0x03 => '00FF00',
0x04 => '0000FF',
0x05 => 'FFFF00',
0x06 => 'FF00FF',
0x07 => '00FFFF',
0x40 => '000000', // system window text color
0x41 => 'FFFFFF', // system window background color
];
/**
* Map built-in color to RGB value.
*
* @param int $color Indexed color
*
* @return array{rgb: string}
*/
public static function lookup(int $color): array
{
return ['rgb' => self::BUILTIN_COLOR_MAP[$color] ?? '000000'];
}
}
@@ -0,0 +1,345 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\FillPattern;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Style;
class ConditionalFormatting extends Xls
{
/**
* @var array<int, string>
*/
private static array $types = [
0x01 => Conditional::CONDITION_CELLIS,
0x02 => Conditional::CONDITION_EXPRESSION,
];
/**
* @var array<int, string>
*/
private static array $operators = [
0x00 => Conditional::OPERATOR_NONE,
0x01 => Conditional::OPERATOR_BETWEEN,
0x02 => Conditional::OPERATOR_NOTBETWEEN,
0x03 => Conditional::OPERATOR_EQUAL,
0x04 => Conditional::OPERATOR_NOTEQUAL,
0x05 => Conditional::OPERATOR_GREATERTHAN,
0x06 => Conditional::OPERATOR_LESSTHAN,
0x07 => Conditional::OPERATOR_GREATERTHANOREQUAL,
0x08 => Conditional::OPERATOR_LESSTHANOREQUAL,
];
public static function type(int $type): ?string
{
return self::$types[$type] ?? null;
}
public static function operator(int $operator): ?string
{
return self::$operators[$operator] ?? null;
}
/**
* Parse conditional formatting blocks.
*
* @see https://www.openoffice.org/sc/excelfileformat.pdf Search for CFHEADER followed by CFRULE
*
* @return mixed[]
*/
protected function readCFHeader2(Xls $xls): array
{
$length = self::getUInt2d($xls->data, $xls->pos + 2);
$recordData = $xls->readRecordData($xls->data, $xls->pos + 4, $length);
// move stream pointer forward to next record
$xls->pos += 4 + $length;
if ($xls->readDataOnly) {
return [];
}
// offset: 0; size: 2; Rule Count
// $ruleCount = self::getUInt2d($recordData, 0);
// offset: var; size: var; cell range address list with
$cellRangeAddressList = ($xls->version == self::XLS_BIFF8)
? Biff8::readBIFF8CellRangeAddressList(substr($recordData, 12))
: Biff5::readBIFF5CellRangeAddressList(substr($recordData, 12));
$cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses'];
return $cellRangeAddresses;
}
/** @param string[] $cellRangeAddresses */
protected function readCFRule2(array $cellRangeAddresses, Xls $xls): void
{
$length = self::getUInt2d($xls->data, $xls->pos + 2);
$recordData = $xls->readRecordData($xls->data, $xls->pos + 4, $length);
// move stream pointer forward to next record
$xls->pos += 4 + $length;
if ($xls->readDataOnly) {
return;
}
// offset: 0; size: 2; Options
$cfRule = self::getUInt2d($recordData, 0);
// bit: 8-15; mask: 0x00FF; type
$type = (0x00FF & $cfRule) >> 0;
$type = self::type($type);
// bit: 0-7; mask: 0xFF00; type
$operator = (0xFF00 & $cfRule) >> 8;
$operator = self::operator($operator);
if ($type === null || $operator === null) {
return;
}
// offset: 2; size: 2; Size1
$size1 = self::getUInt2d($recordData, 2);
// offset: 4; size: 2; Size2
$size2 = self::getUInt2d($recordData, 4);
// offset: 6; size: 4; Options
$options = self::getInt4d($recordData, 6);
$style = new Style(false, true); // non-supervisor, conditional
$noFormatSet = true;
//$xls->getCFStyleOptions($options, $style);
$hasFontRecord = (bool) ((0x04000000 & $options) >> 26);
$hasAlignmentRecord = (bool) ((0x08000000 & $options) >> 27);
$hasBorderRecord = (bool) ((0x10000000 & $options) >> 28);
$hasFillRecord = (bool) ((0x20000000 & $options) >> 29);
$hasProtectionRecord = (bool) ((0x40000000 & $options) >> 30);
// note unexpected values for following 4
$hasBorderLeft = !(bool) (0x00000400 & $options);
$hasBorderRight = !(bool) (0x00000800 & $options);
$hasBorderTop = !(bool) (0x00001000 & $options);
$hasBorderBottom = !(bool) (0x00002000 & $options);
$offset = 12;
if ($hasFontRecord === true) {
$fontStyle = substr($recordData, $offset, 118);
$this->getCFFontStyle($fontStyle, $style, $xls);
$offset += 118;
$noFormatSet = false;
}
if ($hasAlignmentRecord === true) {
//$alignmentStyle = substr($recordData, $offset, 8);
//$this->getCFAlignmentStyle($alignmentStyle, $style, $xls);
$offset += 8;
}
if ($hasBorderRecord === true) {
$borderStyle = substr($recordData, $offset, 8);
$this->getCFBorderStyle($borderStyle, $style, $hasBorderLeft, $hasBorderRight, $hasBorderTop, $hasBorderBottom, $xls);
$offset += 8;
$noFormatSet = false;
}
if ($hasFillRecord === true) {
$fillStyle = substr($recordData, $offset, 4);
$this->getCFFillStyle($fillStyle, $style, $xls);
$offset += 4;
$noFormatSet = false;
}
if ($hasProtectionRecord === true) {
//$protectionStyle = substr($recordData, $offset, 4);
//$this->getCFProtectionStyle($protectionStyle, $style, $xls);
$offset += 2;
}
$formula1 = $formula2 = null;
if ($size1 > 0) {
$formula1 = $this->readCFFormula($recordData, $offset, $size1, $xls);
if ($formula1 === null) {
return;
}
$offset += $size1;
}
if ($size2 > 0) {
$formula2 = $this->readCFFormula($recordData, $offset, $size2, $xls);
if ($formula2 === null) {
return;
}
$offset += $size2;
}
$this->setCFRules($cellRangeAddresses, $type, $operator, $formula1, $formula2, $style, $noFormatSet, $xls);
}
/*private function getCFStyleOptions(int $options, Style $style, Xls $xls): void
{
}*/
private function getCFFontStyle(string $options, Style $style, Xls $xls): void
{
$fontSize = self::getInt4d($options, 64);
if ($fontSize !== -1) {
$style->getFont()->setSize($fontSize / 20); // Convert twips to points
}
$options68 = self::getInt4d($options, 68);
$options88 = self::getInt4d($options, 88);
if (($options88 & 2) === 0) {
$bold = self::getUInt2d($options, 72); // 400 = normal, 700 = bold
if ($bold !== 0) {
$style->getFont()->setBold($bold >= 550);
}
if (($options68 & 2) !== 0) {
$style->getFont()->setItalic(true);
}
}
if (($options88 & 0x80) === 0) {
if (($options68 & 0x80) !== 0) {
$style->getFont()->setStrikethrough(true);
}
}
$color = self::getInt4d($options, 80);
if ($color !== -1) {
$style->getFont()
->getColor()
->setRGB(Color::map($color, $xls->palette, $xls->version)['rgb']);
}
}
/*private function getCFAlignmentStyle(string $options, Style $style, Xls $xls): void
{
}*/
private function getCFBorderStyle(string $options, Style $style, bool $hasBorderLeft, bool $hasBorderRight, bool $hasBorderTop, bool $hasBorderBottom, Xls $xls): void
{
/** @var false|int[] */
$valueArray = unpack('V', $options);
$value = is_array($valueArray) ? $valueArray[1] : 0;
$left = $value & 15;
$right = ($value >> 4) & 15;
$top = ($value >> 8) & 15;
$bottom = ($value >> 12) & 15;
$leftc = ($value >> 16) & 0x7F;
$rightc = ($value >> 23) & 0x7F;
/** @var false|int[] */
$valueArray = unpack('V', substr($options, 4));
$value = is_array($valueArray) ? $valueArray[1] : 0;
$topc = $value & 0x7F;
$bottomc = ($value & 0x3F80) >> 7;
if ($hasBorderLeft) {
$style->getBorders()->getLeft()
->setBorderStyle(self::BORDER_STYLE_MAP[$left]);
$style->getBorders()->getLeft()->getColor()
->setRGB(Color::map($leftc, $xls->palette, $xls->version)['rgb']);
}
if ($hasBorderRight) {
$style->getBorders()->getRight()
->setBorderStyle(self::BORDER_STYLE_MAP[$right]);
$style->getBorders()->getRight()->getColor()
->setRGB(Color::map($rightc, $xls->palette, $xls->version)['rgb']);
}
if ($hasBorderTop) {
$style->getBorders()->getTop()
->setBorderStyle(self::BORDER_STYLE_MAP[$top]);
$style->getBorders()->getTop()->getColor()
->setRGB(Color::map($topc, $xls->palette, $xls->version)['rgb']);
}
if ($hasBorderBottom) {
$style->getBorders()->getBottom()
->setBorderStyle(self::BORDER_STYLE_MAP[$bottom]);
$style->getBorders()->getBottom()->getColor()
->setRGB(Color::map($bottomc, $xls->palette, $xls->version)['rgb']);
}
}
private function getCFFillStyle(string $options, Style $style, Xls $xls): void
{
$fillPattern = self::getUInt2d($options, 0);
// bit: 10-15; mask: 0xFC00; type
$fillPattern = (0xFC00 & $fillPattern) >> 10;
$fillPattern = FillPattern::lookup($fillPattern);
$fillPattern = $fillPattern === Fill::FILL_NONE ? Fill::FILL_SOLID : $fillPattern;
if ($fillPattern !== Fill::FILL_NONE) {
$style->getFill()->setFillType($fillPattern);
$fillColors = self::getUInt2d($options, 2);
// bit: 0-6; mask: 0x007F; type
$color1 = (0x007F & $fillColors) >> 0;
// bit: 7-13; mask: 0x3F80; type
$color2 = (0x3F80 & $fillColors) >> 7;
if ($fillPattern === Fill::FILL_SOLID) {
$style->getFill()->getStartColor()->setRGB(Color::map($color2, $xls->palette, $xls->version)['rgb']);
} else {
$style->getFill()->getStartColor()->setRGB(Color::map($color1, $xls->palette, $xls->version)['rgb']);
$style->getFill()->getEndColor()->setRGB(Color::map($color2, $xls->palette, $xls->version)['rgb']);
}
}
}
/*private function getCFProtectionStyle(string $options, Style $style, Xls $xls): void
{
}*/
private function readCFFormula(string $recordData, int $offset, int $size, Xls $xls): float|int|string|null
{
try {
$formula = substr($recordData, $offset, $size);
$formula = pack('v', $size) . $formula; // prepend the length
$formula = $xls->getFormulaFromStructure($formula);
if (is_numeric($formula)) {
return (str_contains($formula, '.')) ? (float) $formula : (int) $formula;
}
return $formula;
} catch (PhpSpreadsheetException) {
return null;
}
}
/** @param string[] $cellRanges */
private function setCFRules(array $cellRanges, string $type, string $operator, null|float|int|string $formula1, null|float|int|string $formula2, Style $style, bool $noFormatSet, Xls $xls): void
{
foreach ($cellRanges as $cellRange) {
$conditional = new Conditional();
$conditional->setNoFormatSet($noFormatSet);
$conditional->setConditionType($type);
$conditional->setOperatorType($operator);
$conditional->setStopIfTrue(true);
if ($formula1 !== null) {
$conditional->addCondition($formula1);
}
if ($formula2 !== null) {
$conditional->addCondition($formula2);
}
$conditional->setStyle($style);
$conditionalStyles = $xls->phpSheet
->getStyle($cellRange)
->getConditionalStyles();
$conditionalStyles[] = $conditional;
$xls->phpSheet
->getStyle($cellRange)
->setConditionalStyles($conditionalStyles);
}
}
}
@@ -0,0 +1,219 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet as XlsWorksheet;
class DataValidationHelper extends Xls
{
/**
* @var array<int, string>
*/
private static array $types = [
0x00 => DataValidation::TYPE_NONE,
0x01 => DataValidation::TYPE_WHOLE,
0x02 => DataValidation::TYPE_DECIMAL,
0x03 => DataValidation::TYPE_LIST,
0x04 => DataValidation::TYPE_DATE,
0x05 => DataValidation::TYPE_TIME,
0x06 => DataValidation::TYPE_TEXTLENGTH,
0x07 => DataValidation::TYPE_CUSTOM,
];
/**
* @var array<int, string>
*/
private static array $errorStyles = [
0x00 => DataValidation::STYLE_STOP,
0x01 => DataValidation::STYLE_WARNING,
0x02 => DataValidation::STYLE_INFORMATION,
];
/**
* @var array<int, string>
*/
private static array $operators = [
0x00 => DataValidation::OPERATOR_BETWEEN,
0x01 => DataValidation::OPERATOR_NOTBETWEEN,
0x02 => DataValidation::OPERATOR_EQUAL,
0x03 => DataValidation::OPERATOR_NOTEQUAL,
0x04 => DataValidation::OPERATOR_GREATERTHAN,
0x05 => DataValidation::OPERATOR_LESSTHAN,
0x06 => DataValidation::OPERATOR_GREATERTHANOREQUAL,
0x07 => DataValidation::OPERATOR_LESSTHANOREQUAL,
];
public static function type(int $type): ?string
{
return self::$types[$type] ?? null;
}
public static function errorStyle(int $errorStyle): ?string
{
return self::$errorStyles[$errorStyle] ?? null;
}
public static function operator(int $operator): ?string
{
return self::$operators[$operator] ?? null;
}
/**
* Read DATAVALIDATION record.
*/
protected function readDataValidation2(Xls $xls): void
{
$length = self::getUInt2d($xls->data, $xls->pos + 2);
$recordData = $xls->readRecordData($xls->data, $xls->pos + 4, $length);
// move stream pointer forward to next record
$xls->pos += 4 + $length;
if ($xls->readDataOnly) {
return;
}
// offset: 0; size: 4; Options
$options = self::getInt4d($recordData, 0);
// bit: 0-3; mask: 0x0000000F; type
$type = (0x0000000F & $options) >> 0;
$type = self::type($type);
// bit: 4-6; mask: 0x00000070; error type
$errorStyle = (0x00000070 & $options) >> 4;
$errorStyle = self::errorStyle($errorStyle);
// bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list)
// I have only seen cases where this is 1
//$explicitFormula = (0x00000080 & $options) >> 7;
// bit: 8; mask: 0x00000100; 1= empty cells allowed
$allowBlank = (0x00000100 & $options) >> 8;
// bit: 9; mask: 0x00000200; 1= suppress drop down arrow in list type validity
$suppressDropDown = (0x00000200 & $options) >> 9;
// bit: 18; mask: 0x00040000; 1= show prompt box if cell selected
$showInputMessage = (0x00040000 & $options) >> 18;
// bit: 19; mask: 0x00080000; 1= show error box if invalid values entered
$showErrorMessage = (0x00080000 & $options) >> 19;
// bit: 20-23; mask: 0x00F00000; condition operator
$operator = (0x00F00000 & $options) >> 20;
$operator = self::operator($operator);
if ($type === null || $errorStyle === null || $operator === null) {
return;
}
// offset: 4; size: var; title of the prompt box
$offset = 4;
$string = self::readUnicodeStringLong(substr($recordData, $offset));
$promptTitle = $string['value'] !== chr(0) ? $string['value'] : '';
$offset += $string['size'];
// offset: var; size: var; title of the error box
$string = self::readUnicodeStringLong(substr($recordData, $offset));
$errorTitle = $string['value'] !== chr(0) ? $string['value'] : '';
$offset += $string['size'];
// offset: var; size: var; text of the prompt box
$string = self::readUnicodeStringLong(substr($recordData, $offset));
$prompt = $string['value'] !== chr(0) ? $string['value'] : '';
$offset += $string['size'];
// offset: var; size: var; text of the error box
$string = self::readUnicodeStringLong(substr($recordData, $offset));
$error = $string['value'] !== chr(0) ? $string['value'] : '';
$offset += $string['size'];
// offset: var; size: 2; size of the formula data for the first condition
$sz1 = self::getUInt2d($recordData, $offset);
$offset += 2;
// offset: var; size: 2; not used
$offset += 2;
// offset: var; size: $sz1; formula data for first condition (without size field)
$formula1 = substr($recordData, $offset, $sz1);
$formula1 = pack('v', $sz1) . $formula1; // prepend the length
try {
$formula1 = $xls->getFormulaFromStructure($formula1);
// in list type validity, null characters are used as item separators
if ($type == DataValidation::TYPE_LIST) {
$formula1 = str_replace(chr(0), ',', $formula1);
}
} catch (PhpSpreadsheetException $e) {
return;
}
$offset += $sz1;
// offset: var; size: 2; size of the formula data for the first condition
$sz2 = self::getUInt2d($recordData, $offset);
$offset += 2;
// offset: var; size: 2; not used
$offset += 2;
// offset: var; size: $sz2; formula data for second condition (without size field)
$formula2 = substr($recordData, $offset, $sz2);
$formula2 = pack('v', $sz2) . $formula2; // prepend the length
try {
$formula2 = $xls->getFormulaFromStructure($formula2);
} catch (PhpSpreadsheetException) {
return;
}
$offset += $sz2;
// offset: var; size: var; cell range address list with
$cellRangeAddressList = Biff8::readBIFF8CellRangeAddressList(substr($recordData, $offset));
/** @var string[] */
$cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses'];
$maxRow = (string) AddressRange::MAX_ROW;
$maxCol = AddressRange::MAX_COLUMN;
$maxXlsRow = (string) XlsWorksheet::MAX_XLS_ROW;
$maxXlsColumnString = (string) XlsWorksheet::MAX_XLS_COLUMN_STRING;
foreach ($cellRangeAddresses as $cellRange) {
$cellRange = preg_replace(
[
"/([a-z]+)1:([a-z]+)$maxXlsRow/i",
"/([a-z]+\\d+):([a-z]+)$maxXlsRow/i",
"/A(\\d+):$maxXlsColumnString(\\d+)/i",
"/([a-z]+\\d+):$maxXlsColumnString(\\d+)/i",
],
[
'$1:$2',
'$1:${2}' . $maxRow,
'$1:$2',
'$1:' . $maxCol . '$2',
],
$cellRange
) ?? $cellRange;
$objValidation = new DataValidation();
$objValidation->setType($type);
$objValidation->setErrorStyle($errorStyle);
$objValidation->setAllowBlank((bool) $allowBlank);
$objValidation->setShowInputMessage((bool) $showInputMessage);
$objValidation->setShowErrorMessage((bool) $showErrorMessage);
$objValidation->setShowDropDown(!$suppressDropDown);
$objValidation->setOperator($operator);
$objValidation->setErrorTitle($errorTitle);
$objValidation->setError($error);
$objValidation->setPromptTitle($promptTitle);
$objValidation->setPrompt($prompt);
$objValidation->setFormula1($formula1);
$objValidation->setFormula2($formula2);
$xls->phpSheet->setDataValidation($cellRange, $objValidation);
}
}
}
@@ -0,0 +1,24 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
class ErrorCode
{
private const ERROR_CODE_MAP = [
0x00 => '#NULL!',
0x07 => '#DIV/0!',
0x0F => '#VALUE!',
0x17 => '#REF!',
0x1D => '#NAME?',
0x24 => '#NUM!',
0x2A => '#N/A',
];
/**
* Map error code, e.g. '#N/A'.
*/
public static function lookup(int $code): string|bool
{
return self::ERROR_CODE_MAP[$code] ?? false;
}
}
@@ -0,0 +1,616 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip;
/**
* @template T of BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer
*/
class Escher
{
const DGGCONTAINER = 0xF000;
const BSTORECONTAINER = 0xF001;
const DGCONTAINER = 0xF002;
const SPGRCONTAINER = 0xF003;
const SPCONTAINER = 0xF004;
const DGG = 0xF006;
const BSE = 0xF007;
const DG = 0xF008;
const SPGR = 0xF009;
const SP = 0xF00A;
const OPT = 0xF00B;
const CLIENTTEXTBOX = 0xF00D;
const CLIENTANCHOR = 0xF010;
const CLIENTDATA = 0xF011;
const BLIPJPEG = 0xF01D;
const BLIPPNG = 0xF01E;
const SPLITMENUCOLORS = 0xF11E;
const TERTIARYOPT = 0xF122;
/**
* Escher stream data (binary).
*/
private string $data;
/**
* Size in bytes of the Escher stream data.
*/
private int $dataSize;
/**
* Current position of stream pointer in Escher stream data.
*/
private int $pos;
/**
* The object to be returned by the reader. Modified during load.
*
* @var T
*/
private BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer $object;
/**
* Create a new Escher instance.
*
* @param T $object
*/
public function __construct(BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer $object)
{
$this->object = $object;
}
private const WHICH_ROUTINE = [
self::DGGCONTAINER => 'readDggContainer',
self::DGG => 'readDgg',
self::BSTORECONTAINER => 'readBstoreContainer',
self::BSE => 'readBSE',
self::BLIPJPEG => 'readBlipJPEG',
self::BLIPPNG => 'readBlipPNG',
self::OPT => 'readOPT',
self::TERTIARYOPT => 'readTertiaryOPT',
self::SPLITMENUCOLORS => 'readSplitMenuColors',
self::DGCONTAINER => 'readDgContainer',
self::DG => 'readDg',
self::SPGRCONTAINER => 'readSpgrContainer',
self::SPCONTAINER => 'readSpContainer',
self::SPGR => 'readSpgr',
self::SP => 'readSp',
self::CLIENTTEXTBOX => 'readClientTextbox',
self::CLIENTANCHOR => 'readClientAnchor',
self::CLIENTDATA => 'readClientData',
];
/**
* Load Escher stream data. May be a partial Escher stream.
*
* @return T
*/
public function load(string $data): BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer
{
$this->data = $data;
// total byte size of Excel data (workbook global substream + sheet substreams)
$this->dataSize = strlen($this->data);
$this->pos = 0;
// Parse Escher stream
while ($this->pos < $this->dataSize) {
// offset: 2; size: 2: Record Type
$fbt = Xls::getUInt2d($this->data, $this->pos + 2);
$routine = self::WHICH_ROUTINE[$fbt] ?? 'readDefault';
if (method_exists($this, $routine)) {
$this->$routine();
}
}
return $this->object;
}
/**
* Read a generic record.
*/
private function readDefault(): void
{
// offset 0; size: 2; recVer and recInstance
//$verInstance = Xls::getUInt2d($this->data, $this->pos);
// offset: 2; size: 2: Record Type
//$fbt = Xls::getUInt2d($this->data, $this->pos + 2);
// bit: 0-3; mask: 0x000F; recVer
//$recVer = (0x000F & $verInstance) >> 0;
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read DggContainer record (Drawing Group Container).
*/
private function readDggContainer(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
// record is a container, read contents
$dggContainer = new DggContainer();
$this->applyAttribute('setDggContainer', $dggContainer);
$reader = new self($dggContainer);
$reader->load($recordData);
}
/**
* Read Dgg record (Drawing Group).
*/
private function readDgg(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read BstoreContainer record (Blip Store Container).
*/
private function readBstoreContainer(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
// record is a container, read contents
$bstoreContainer = new BstoreContainer();
$this->applyAttribute('setBstoreContainer', $bstoreContainer);
$reader = new self($bstoreContainer);
$reader->load($recordData);
}
/**
* Read BSE record.
*/
private function readBSE(): void
{
// offset: 0; size: 2; recVer and recInstance
// bit: 4-15; mask: 0xFFF0; recInstance
$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4;
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
// add BSE to BstoreContainer
$BSE = new BSE();
$this->applyAttribute('addBSE', $BSE);
$BSE->setBLIPType($recInstance);
// offset: 0; size: 1; btWin32 (MSOBLIPTYPE)
//$btWin32 = ord($recordData[0]);
// offset: 1; size: 1; btWin32 (MSOBLIPTYPE)
//$btMacOS = ord($recordData[1]);
// offset: 2; size: 16; MD4 digest
//$rgbUid = substr($recordData, 2, 16);
// offset: 18; size: 2; tag
//$tag = Xls::getUInt2d($recordData, 18);
// offset: 20; size: 4; size of BLIP in bytes
//$size = Xls::getInt4d($recordData, 20);
// offset: 24; size: 4; number of references to this BLIP
//$cRef = Xls::getInt4d($recordData, 24);
// offset: 28; size: 4; MSOFO file offset
//$foDelay = Xls::getInt4d($recordData, 28);
// offset: 32; size: 1; unused1
//$unused1 = ord($recordData[32]);
// offset: 33; size: 1; size of nameData in bytes (including null terminator)
$cbName = ord($recordData[33]);
// offset: 34; size: 1; unused2
//$unused2 = ord($recordData[34]);
// offset: 35; size: 1; unused3
//$unused3 = ord($recordData[35]);
// offset: 36; size: $cbName; nameData
//$nameData = substr($recordData, 36, $cbName);
// offset: 36 + $cbName, size: var; the BLIP data
$blipData = substr($recordData, 36 + $cbName);
// record is a container, read contents
$reader = new self($BSE);
$reader->load($blipData);
}
/**
* Read BlipJPEG record. Holds raw JPEG image data.
*/
private function readBlipJPEG(): void
{
// offset: 0; size: 2; recVer and recInstance
// bit: 4-15; mask: 0xFFF0; recInstance
$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4;
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
$pos = 0;
// offset: 0; size: 16; rgbUid1 (MD4 digest of)
//$rgbUid1 = substr($recordData, 0, 16);
$pos += 16;
// offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3
if (in_array($recInstance, [0x046B, 0x06E3])) {
//$rgbUid2 = substr($recordData, 16, 16);
$pos += 16;
}
// offset: var; size: 1; tag
//$tag = ord($recordData[$pos]);
++$pos;
// offset: var; size: var; the raw image data
$data = substr($recordData, $pos);
$blip = new Blip();
$blip->setData($data);
$this->applyAttribute('setBlip', $blip);
}
/**
* Read BlipPNG record. Holds raw PNG image data.
*/
private function readBlipPNG(): void
{
// offset: 0; size: 2; recVer and recInstance
// bit: 4-15; mask: 0xFFF0; recInstance
$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4;
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
$pos = 0;
// offset: 0; size: 16; rgbUid1 (MD4 digest of)
//$rgbUid1 = substr($recordData, 0, 16);
$pos += 16;
// offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3
if ($recInstance == 0x06E1) {
//$rgbUid2 = substr($recordData, 16, 16);
$pos += 16;
}
// offset: var; size: 1; tag
//$tag = ord($recordData[$pos]);
++$pos;
// offset: var; size: var; the raw image data
$data = substr($recordData, $pos);
$blip = new Blip();
$blip->setData($data);
$this->applyAttribute('setBlip', $blip);
}
/**
* Read OPT record. This record may occur within DggContainer record or SpContainer.
*/
private function readOPT(): void
{
// offset: 0; size: 2; recVer and recInstance
// bit: 4-15; mask: 0xFFF0; recInstance
$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4;
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
$this->readOfficeArtRGFOPTE($recordData, $recInstance);
}
/**
* Read TertiaryOPT record.
*/
private function readTertiaryOPT(): void
{
// offset: 0; size: 2; recVer and recInstance
// bit: 4-15; mask: 0xFFF0; recInstance
//$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4;
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read SplitMenuColors record.
*/
private function readSplitMenuColors(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read DgContainer record (Drawing Container).
*/
private function readDgContainer(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
// record is a container, read contents
$dgContainer = new DgContainer();
$this->applyAttribute('setDgContainer', $dgContainer);
$reader = new self($dgContainer);
$reader->load($recordData);
}
/**
* Read Dg record (Drawing).
*/
private function readDg(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read SpgrContainer record (Shape Group Container).
*/
private function readSpgrContainer(): void
{
// context is either context DgContainer or SpgrContainer
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
// record is a container, read contents
$spgrContainer = new SpgrContainer();
if ($this->object instanceof DgContainer) {
// DgContainer
$this->object->setSpgrContainer($spgrContainer);
} elseif ($this->object instanceof SpgrContainer) {
// SpgrContainer
$this->object->addChild($spgrContainer);
}
$reader = new self($spgrContainer);
$reader->load($recordData);
}
/**
* Read SpContainer record (Shape Container).
*/
private function readSpContainer(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// add spContainer to spgrContainer
$spContainer = new SpContainer();
$this->applyAttribute('addChild', $spContainer);
// move stream pointer to next record
$this->pos += 8 + $length;
// record is a container, read contents
$reader = new self($spContainer);
$reader->load($recordData);
}
/**
* Read Spgr record (Shape Group).
*/
private function readSpgr(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read Sp record (Shape).
*/
private function readSp(): void
{
// offset: 0; size: 2; recVer and recInstance
// bit: 4-15; mask: 0xFFF0; recInstance
//$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4;
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read ClientTextbox record.
*/
private function readClientTextbox(): void
{
// offset: 0; size: 2; recVer and recInstance
// bit: 4-15; mask: 0xFFF0; recInstance
//$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4;
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read ClientAnchor record. This record holds information about where the shape is anchored in worksheet.
*/
private function readClientAnchor(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
// offset: 2; size: 2; upper-left corner column index (0-based)
$c1 = Xls::getUInt2d($recordData, 2);
// offset: 4; size: 2; upper-left corner horizontal offset in 1/1024 of column width
$startOffsetX = Xls::getUInt2d($recordData, 4);
// offset: 6; size: 2; upper-left corner row index (0-based)
$r1 = Xls::getUInt2d($recordData, 6);
// offset: 8; size: 2; upper-left corner vertical offset in 1/256 of row height
$startOffsetY = Xls::getUInt2d($recordData, 8);
// offset: 10; size: 2; bottom-right corner column index (0-based)
$c2 = Xls::getUInt2d($recordData, 10);
// offset: 12; size: 2; bottom-right corner horizontal offset in 1/1024 of column width
$endOffsetX = Xls::getUInt2d($recordData, 12);
// offset: 14; size: 2; bottom-right corner row index (0-based)
$r2 = Xls::getUInt2d($recordData, 14);
// offset: 16; size: 2; bottom-right corner vertical offset in 1/256 of row height
$endOffsetY = Xls::getUInt2d($recordData, 16);
$this->applyAttribute('setStartCoordinates', Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1));
$this->applyAttribute('setStartOffsetX', $startOffsetX);
$this->applyAttribute('setStartOffsetY', $startOffsetY);
$this->applyAttribute('setEndCoordinates', Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1));
$this->applyAttribute('setEndOffsetX', $endOffsetX);
$this->applyAttribute('setEndOffsetY', $endOffsetY);
}
private function applyAttribute(string $name, mixed $value): void
{
if (method_exists($this->object, $name)) {
$this->object->$name($value);
}
}
/**
* Read ClientData record.
*/
private function readClientData(): void
{
$length = Xls::getInt4d($this->data, $this->pos + 4);
//$recordData = substr($this->data, $this->pos + 8, $length);
// move stream pointer to next record
$this->pos += 8 + $length;
}
/**
* Read OfficeArtRGFOPTE table of property-value pairs.
*
* @param string $data Binary data
* @param int $n Number of properties
*/
private function readOfficeArtRGFOPTE(string $data, int $n): void
{
$splicedComplexData = substr($data, 6 * $n);
// loop through property-value pairs
for ($i = 0; $i < $n; ++$i) {
// read 6 bytes at a time
$fopte = substr($data, 6 * $i, 6);
// offset: 0; size: 2; opid
$opid = Xls::getUInt2d($fopte, 0);
// bit: 0-13; mask: 0x3FFF; opid.opid
$opidOpid = (0x3FFF & $opid) >> 0;
// bit: 14; mask 0x4000; 1 = value in op field is BLIP identifier
//$opidFBid = (0x4000 & $opid) >> 14;
// bit: 15; mask 0x8000; 1 = this is a complex property, op field specifies size of complex data
$opidFComplex = (0x8000 & $opid) >> 15;
// offset: 2; size: 4; the value for this property
$op = Xls::getInt4d($fopte, 2);
if ($opidFComplex) {
$complexData = substr($splicedComplexData, 0, $op);
$splicedComplexData = substr($splicedComplexData, $op);
// we store string value with complex data
$value = $complexData;
} else {
// we store integer value
$value = $op;
}
if (method_exists($this->object, 'setOPT')) {
$this->object->setOPT($opidOpid, $value);
}
}
}
}
@@ -0,0 +1,267 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ListFunctions extends Xls
{
/**
* Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object.
*
* @return string[]
*/
protected function listWorksheetNames2(string $filename, Xls $xls): array
{
File::assertFile($filename);
$worksheetNames = [];
// Read the OLE file
$xls->loadOLE($filename);
// total byte size of Excel data (workbook global substream + sheet substreams)
$xls->dataSize = strlen($xls->data);
$xls->pos = 0;
$xls->sheets = [];
// Parse Workbook Global Substream
while ($xls->pos < $xls->dataSize) {
$code = self::getUInt2d($xls->data, $xls->pos);
match ($code) {
self::XLS_TYPE_BOF => $xls->readBof(),
self::XLS_TYPE_SHEET => $xls->readSheet(),
self::XLS_TYPE_EOF => $xls->readDefault(),
self::XLS_TYPE_CODEPAGE => $xls->readCodepage(),
default => $xls->readDefault(),
};
if ($code === self::XLS_TYPE_EOF) {
break;
}
}
foreach ($xls->sheets as $sheet) {
if ($sheet['sheetType'] === 0x00) {
// 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
$worksheetNames[] = $sheet['name'];
}
}
return $worksheetNames;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
* @return array<int, array{worksheetName: string, lastColumnLetter: string, lastColumnIndex: int, totalRows: int, totalColumns: int, sheetState: string}>
*/
protected function listWorksheetInfo2(string $filename, Xls $xls): array
{
File::assertFile($filename);
$worksheetInfo = [];
// Read the OLE file
$xls->loadOLE($filename);
// total byte size of Excel data (workbook global substream + sheet substreams)
$xls->dataSize = strlen($xls->data);
// initialize
$xls->pos = 0;
$xls->sheets = [];
// Parse Workbook Global Substream
while ($xls->pos < $xls->dataSize) {
$code = self::getUInt2d($xls->data, $xls->pos);
match ($code) {
self::XLS_TYPE_BOF => $xls->readBof(),
self::XLS_TYPE_SHEET => $xls->readSheet(),
self::XLS_TYPE_EOF => $xls->readDefault(),
self::XLS_TYPE_CODEPAGE => $xls->readCodepage(),
default => $xls->readDefault(),
};
if ($code === self::XLS_TYPE_EOF) {
break;
}
}
// Parse the individual sheets
foreach ($xls->sheets as $sheet) {
if ($sheet['sheetType'] !== 0x00) {
// 0x00: Worksheet
// 0x02: Chart
// 0x06: Visual Basic module
continue;
}
$tmpInfo = [];
$tmpInfo['worksheetName'] = StringHelper::convertToString($sheet['name']);
$tmpInfo['lastColumnLetter'] = 'A';
$tmpInfo['lastColumnIndex'] = 0;
$tmpInfo['totalRows'] = 0;
$tmpInfo['totalColumns'] = 0;
$tmpInfo['sheetState'] = StringHelper::convertToString($sheet['sheetState']);
$xls->pos = $sheet['offset'];
while ($xls->pos <= $xls->dataSize - 4) {
$code = self::getUInt2d($xls->data, $xls->pos);
switch ($code) {
case self::XLS_TYPE_RK:
case self::XLS_TYPE_LABELSST:
case self::XLS_TYPE_NUMBER:
case self::XLS_TYPE_FORMULA:
case self::XLS_TYPE_BOOLERR:
case self::XLS_TYPE_LABEL:
case self::XLS_TYPE_MULRK:
$length = self::getUInt2d($xls->data, $xls->pos + 2);
$recordData = $xls->readRecordData($xls->data, $xls->pos + 4, $length);
// move stream pointer to next record
$xls->pos += 4 + $length;
$rowIndex = self::getUInt2d($recordData, 0) + 1;
if ($code === self::XLS_TYPE_MULRK) {
$columnIndex = self::getUInt2d($recordData, $length - 2);
} else {
$columnIndex = self::getUInt2d($recordData, 2);
}
$tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex);
$tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex);
break;
case self::XLS_TYPE_BOF:
$xls->readBof();
break;
case self::XLS_TYPE_EOF:
$xls->readDefault();
break 2;
default:
$xls->readDefault();
break;
}
}
$tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
$tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1;
$worksheetInfo[] = $tmpInfo;
}
return $worksheetInfo;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
* @return array<int, array{worksheetName: string, dimensionsMinR: int, dimensionsMinC: int, dimensionsMaxR: int, dimensionsMaxC: int, lastColumnLetter: string}>
*/
protected function listWorksheetDimensions2(string $filename, Xls $xls): array
{
File::assertFile($filename);
$worksheetInfo = [];
// Read the OLE file
$xls->loadOLE($filename);
// total byte size of Excel data (workbook global substream + sheet substreams)
$xls->dataSize = strlen($xls->data);
// initialize
$xls->pos = 0;
$xls->sheets = [];
// Parse Workbook Global Substream
while ($xls->pos < $xls->dataSize) {
$code = self::getUInt2d($xls->data, $xls->pos);
match ($code) {
self::XLS_TYPE_BOF => $xls->readBof(),
self::XLS_TYPE_SHEET => $xls->readSheet(),
self::XLS_TYPE_EOF => $xls->readDefault(),
self::XLS_TYPE_CODEPAGE => $xls->readCodepage(),
default => $xls->readDefault(),
};
if ($code === self::XLS_TYPE_EOF) {
break;
}
}
// Parse the individual sheets
foreach ($xls->sheets as $sheet) {
if ($sheet['sheetType'] !== 0x00) {
// 0x00: Worksheet
// 0x02: Chart
// 0x06: Visual Basic module
continue;
}
$tmpInfo = [];
$tmpInfo['worksheetName'] = StringHelper::convertToString($sheet['name']);
$tmpInfo['dimensionsMinR'] = -1;
$tmpInfo['dimensionsMaxR'] = -1;
$tmpInfo['dimensionsMinC'] = -1;
$tmpInfo['dimensionsMaxC'] = -1;
$tmpInfo['lastColumnLetter'] = '';
$xls->pos = $sheet['offset'];
while ($xls->pos <= $xls->dataSize - 4) {
$code = self::getUInt2d($xls->data, $xls->pos);
switch ($code) {
case self::XLS_TYPE_BOF:
$xls->readBof();
break;
case self::XLS_TYPE_EOF:
$xls->readDefault();
break 2;
case self::XLS_TYPE_DIMENSION:
$length = self::getUInt2d($xls->data, $xls->pos + 2);
if ($length === 14) {
$dimensionsData = substr($xls->data, $xls->pos + 4, $length);
$data = unpack('VrwMic/VrwMac/vcolMic/vcolMac/vreserved', $dimensionsData);
if (is_array($data)) {
/** @var int[] $data */
$tmpInfo['dimensionsMinR'] = $data['rwMic'];
$tmpInfo['dimensionsMaxR'] = $data['rwMac'];
$tmpInfo['dimensionsMinC'] = $data['colMic'];
$tmpInfo['dimensionsMaxC'] = $data['colMac'];
$tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['dimensionsMaxC']);
}
}
$xls->readDefault();
break;
default:
$xls->readDefault();
break;
}
}
$worksheetInfo[] = $tmpInfo;
}
return $worksheetInfo;
}
}
@@ -0,0 +1,692 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\CodePage;
use PhpOffice\PhpSpreadsheet\Shared\Escher as SharedEscher;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
use PhpOffice\PhpSpreadsheet\Shared\Xls as SharedXls;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class LoadSpreadsheet extends Xls
{
/**
* Loads PhpSpreadsheet from file.
*/
protected function loadSpreadsheetFromFile2(string $filename, Xls $xls): Spreadsheet
{
// Read the OLE file
$xls->loadOLE($filename);
// Initialisations
$xls->spreadsheet = $this->newSpreadsheet();
$xls->spreadsheet->setValueBinder($xls->valueBinder);
$xls->spreadsheet->removeSheetByIndex(0); // remove 1st sheet
if (!$xls->readDataOnly) {
$xls->spreadsheet->removeCellStyleXfByIndex(0); // remove the default style
$xls->spreadsheet->removeCellXfByIndex(0); // remove the default style
}
// Read the summary information stream (containing meta data)
$xls->readSummaryInformation();
// Read the Additional document summary information stream (containing application-specific meta data)
$xls->readDocumentSummaryInformation();
// total byte size of Excel data (workbook global substream + sheet substreams)
$xls->dataSize = strlen($xls->data);
// initialize
$xls->pos = 0;
$xls->codepage = $xls->codepage ?: CodePage::DEFAULT_CODE_PAGE;
$xls->formats = [];
$xls->objFonts = [];
$xls->palette = [];
$xls->sheets = [];
$xls->externalBooks = [];
$xls->ref = [];
$xls->definedname = []; //* @phpstan-ignore-line
$xls->sst = [];
$xls->drawingGroupData = '';
$xls->xfIndex = 0;
$xls->mapCellXfIndex = [];
$xls->mapCellStyleXfIndex = [];
// Parse Workbook Global Substream
while ($xls->pos < $xls->dataSize) {
$code = self::getUInt2d($xls->data, $xls->pos);
match ($code) {
self::XLS_TYPE_BOF => $xls->readBof(),
self::XLS_TYPE_FILEPASS => $xls->readFilepass(),
self::XLS_TYPE_CODEPAGE => $xls->readCodepage(),
self::XLS_TYPE_DATEMODE => $xls->readDateMode(),
self::XLS_TYPE_FONT => $xls->readFont(),
self::XLS_TYPE_FORMAT => $xls->readFormat(),
self::XLS_TYPE_XF => $xls->readXf(),
self::XLS_TYPE_XFEXT => $xls->readXfExt(),
self::XLS_TYPE_STYLE => $xls->readStyle(),
self::XLS_TYPE_PALETTE => $xls->readPalette(),
self::XLS_TYPE_SHEET => $xls->readSheet(),
self::XLS_TYPE_EXTERNALBOOK => $xls->readExternalBook(),
self::XLS_TYPE_EXTERNNAME => $xls->readExternName(),
self::XLS_TYPE_EXTERNSHEET => $xls->readExternSheet(),
self::XLS_TYPE_DEFINEDNAME => $xls->readDefinedName(),
self::XLS_TYPE_MSODRAWINGGROUP => $xls->readMsoDrawingGroup(),
self::XLS_TYPE_SST => $xls->readSst(),
self::XLS_TYPE_EOF => $xls->readDefault(),
default => $xls->readDefault(),
};
if ($code === self::XLS_TYPE_EOF) {
break;
}
}
// Resolve indexed colors for font, fill, and border colors
// Cannot be resolved already in XF record, because PALETTE record comes afterwards
if (!$xls->readDataOnly) {
foreach ($xls->objFonts as $objFont) {
if (isset($objFont->colorIndex)) {
$color = Color::map($objFont->colorIndex, $xls->palette, $xls->version);
$objFont->getColor()->setRGB($color['rgb']);
}
}
foreach ($xls->spreadsheet->getCellXfCollection() as $objStyle) {
// fill start and end color
$fill = $objStyle->getFill();
if (isset($fill->startcolorIndex)) {
$startColor = Color::map($fill->startcolorIndex, $xls->palette, $xls->version);
$fill->getStartColor()->setRGB($startColor['rgb']);
}
if (isset($fill->endcolorIndex)) {
$endColor = Color::map($fill->endcolorIndex, $xls->palette, $xls->version);
$fill->getEndColor()->setRGB($endColor['rgb']);
}
// border colors
$top = $objStyle->getBorders()->getTop();
$right = $objStyle->getBorders()->getRight();
$bottom = $objStyle->getBorders()->getBottom();
$left = $objStyle->getBorders()->getLeft();
$diagonal = $objStyle->getBorders()->getDiagonal();
if (isset($top->colorIndex)) {
$borderTopColor = Color::map($top->colorIndex, $xls->palette, $xls->version);
$top->getColor()->setRGB($borderTopColor['rgb']);
}
if (isset($right->colorIndex)) {
$borderRightColor = Color::map($right->colorIndex, $xls->palette, $xls->version);
$right->getColor()->setRGB($borderRightColor['rgb']);
}
if (isset($bottom->colorIndex)) {
$borderBottomColor = Color::map($bottom->colorIndex, $xls->palette, $xls->version);
$bottom->getColor()->setRGB($borderBottomColor['rgb']);
}
if (isset($left->colorIndex)) {
$borderLeftColor = Color::map($left->colorIndex, $xls->palette, $xls->version);
$left->getColor()->setRGB($borderLeftColor['rgb']);
}
if (isset($diagonal->colorIndex)) {
$borderDiagonalColor = Color::map($diagonal->colorIndex, $xls->palette, $xls->version);
$diagonal->getColor()->setRGB($borderDiagonalColor['rgb']);
}
}
}
// treat MSODRAWINGGROUP records, workbook-level Escher
$escherWorkbook = null;
if (!$xls->readDataOnly && $xls->drawingGroupData) {
$escher = new SharedEscher();
$reader = new Escher($escher);
$escherWorkbook = $reader->load($xls->drawingGroupData);
}
// Parse the individual sheets
$xls->activeSheetSet = false;
$sheetCreated = false;
foreach ($xls->sheets as $sheet) {
$selectedCells = '';
if ($sheet['sheetType'] != 0x00) {
// 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
continue;
}
// check if sheet should be skipped
if (isset($xls->loadSheetsOnly) && !in_array($sheet['name'], $xls->loadSheetsOnly)) {
continue;
}
// add sheet to PhpSpreadsheet object
$xls->phpSheet = $xls->spreadsheet->createSheet();
$sheetCreated = true;
// Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula
// cells... during the load, all formulae should be correct, and we're simply bringing the worksheet
// name in line with the formula, not the reverse
$xls->phpSheet->setTitle($sheet['name'], false, false);
$xls->phpSheet->setSheetState($sheet['sheetState']);
$xls->pos = $sheet['offset'];
// Initialize isFitToPages. May change after reading SHEETPR record.
$xls->isFitToPages = false;
// Initialize drawingData
$xls->drawingData = '';
// Initialize objs
$xls->objs = [];
// Initialize shared formula parts
$xls->sharedFormulaParts = [];
// Initialize shared formulas
$xls->sharedFormulas = [];
// Initialize text objs
$xls->textObjects = [];
// Initialize cell annotations
$xls->cellNotes = [];
$xls->textObjRef = -1;
while ($xls->pos <= $xls->dataSize - 4) {
$code = self::getUInt2d($xls->data, $xls->pos);
switch ($code) {
case self::XLS_TYPE_BOF:
$xls->readBof();
break;
case self::XLS_TYPE_PRINTGRIDLINES:
$xls->readPrintGridlines();
break;
case self::XLS_TYPE_DEFAULTROWHEIGHT:
$xls->readDefaultRowHeight();
break;
case self::XLS_TYPE_SHEETPR:
$xls->readSheetPr();
break;
case self::XLS_TYPE_HORIZONTALPAGEBREAKS:
$xls->readHorizontalPageBreaks();
break;
case self::XLS_TYPE_VERTICALPAGEBREAKS:
$xls->readVerticalPageBreaks();
break;
case self::XLS_TYPE_HEADER:
$xls->readHeader();
break;
case self::XLS_TYPE_FOOTER:
$xls->readFooter();
break;
case self::XLS_TYPE_HCENTER:
$xls->readHcenter();
break;
case self::XLS_TYPE_VCENTER:
$xls->readVcenter();
break;
case self::XLS_TYPE_LEFTMARGIN:
$xls->readLeftMargin();
break;
case self::XLS_TYPE_RIGHTMARGIN:
$xls->readRightMargin();
break;
case self::XLS_TYPE_TOPMARGIN:
$xls->readTopMargin();
break;
case self::XLS_TYPE_BOTTOMMARGIN:
$xls->readBottomMargin();
break;
case self::XLS_TYPE_PAGESETUP:
$xls->readPageSetup();
break;
case self::XLS_TYPE_PROTECT:
$xls->readProtect();
break;
case self::XLS_TYPE_SCENPROTECT:
$xls->readScenProtect();
break;
case self::XLS_TYPE_OBJECTPROTECT:
$xls->readObjectProtect();
break;
case self::XLS_TYPE_PASSWORD:
$xls->readPassword();
break;
case self::XLS_TYPE_DEFCOLWIDTH:
$xls->readDefColWidth();
break;
case self::XLS_TYPE_COLINFO:
$xls->readColInfo();
break;
case self::XLS_TYPE_DIMENSION:
$xls->readDefault();
break;
case self::XLS_TYPE_ROW:
$xls->readRow();
break;
case self::XLS_TYPE_DBCELL:
$xls->readDefault();
break;
case self::XLS_TYPE_RK:
$xls->readRk();
break;
case self::XLS_TYPE_LABELSST:
$xls->readLabelSst();
break;
case self::XLS_TYPE_MULRK:
$xls->readMulRk();
break;
case self::XLS_TYPE_NUMBER:
$xls->readNumber();
break;
case self::XLS_TYPE_FORMULA:
$xls->readFormula();
break;
case self::XLS_TYPE_SHAREDFMLA:
$xls->readSharedFmla();
break;
case self::XLS_TYPE_BOOLERR:
$xls->readBoolErr();
break;
case self::XLS_TYPE_MULBLANK:
$xls->readMulBlank();
break;
case self::XLS_TYPE_LABEL:
$xls->readLabel();
break;
case self::XLS_TYPE_BLANK:
$xls->readBlank();
break;
case self::XLS_TYPE_MSODRAWING:
$xls->readMsoDrawing();
break;
case self::XLS_TYPE_OBJ:
$xls->readObj();
break;
case self::XLS_TYPE_WINDOW2:
$xls->readWindow2();
break;
case self::XLS_TYPE_PAGELAYOUTVIEW:
$xls->readPageLayoutView();
break;
case self::XLS_TYPE_SCL:
$xls->readScl();
break;
case self::XLS_TYPE_PANE:
$xls->readPane();
break;
case self::XLS_TYPE_SELECTION:
$selectedCells = $xls->readSelection();
break;
case self::XLS_TYPE_MERGEDCELLS:
$xls->readMergedCells();
break;
case self::XLS_TYPE_HYPERLINK:
$xls->readHyperLink();
break;
case self::XLS_TYPE_DATAVALIDATIONS:
$xls->readDataValidations();
break;
case self::XLS_TYPE_DATAVALIDATION:
$xls->readDataValidation();
break;
case self::XLS_TYPE_CFHEADER:
/** @var string[] */
$cellRangeAddresses = $xls->readCFHeader();
break;
case self::XLS_TYPE_CFRULE:
$xls->readCFRule($cellRangeAddresses ?? []);
break;
case self::XLS_TYPE_SHEETLAYOUT:
$xls->readSheetLayout();
break;
case self::XLS_TYPE_SHEETPROTECTION:
$xls->readSheetProtection();
break;
case self::XLS_TYPE_RANGEPROTECTION:
$xls->readRangeProtection();
break;
case self::XLS_TYPE_NOTE:
$xls->readNote();
break;
case self::XLS_TYPE_TXO:
$xls->readTextObject();
break;
case self::XLS_TYPE_CONTINUE:
$xls->readContinue();
break;
case self::XLS_TYPE_EOF:
$xls->readDefault();
break 2;
default:
$xls->readDefault();
break;
}
}
// treat MSODRAWING records, sheet-level Escher
if (!$xls->readDataOnly && $xls->drawingData) {
$escherWorksheet = new SharedEscher();
$reader = new Escher($escherWorksheet);
$escherWorksheet = $reader->load($xls->drawingData);
// get all spContainers in one long array, so they can be mapped to OBJ records
/** @var SpContainer[] $allSpContainers */
$allSpContainers = $escherWorksheet->getDgContainerOrThrow()->getSpgrContainerOrThrow()->getAllSpContainers();
}
// treat OBJ records
foreach ($xls->objs as $n => $obj) {
// the first shape container never has a corresponding OBJ record, hence $n + 1
if (isset($allSpContainers[$n + 1])) {
$spContainer = $allSpContainers[$n + 1];
// we skip all spContainers that are a part of a group shape since we cannot yet handle those
if ($spContainer->getNestingLevel() > 1) {
continue;
}
// calculate the width and height of the shape
/** @var int $startRow */
[$startColumn, $startRow] = Coordinate::coordinateFromString($spContainer->getStartCoordinates());
/** @var int $endRow */
[$endColumn, $endRow] = Coordinate::coordinateFromString($spContainer->getEndCoordinates());
$startOffsetX = $spContainer->getStartOffsetX();
$startOffsetY = $spContainer->getStartOffsetY();
$endOffsetX = $spContainer->getEndOffsetX();
$endOffsetY = $spContainer->getEndOffsetY();
$width = SharedXls::getDistanceX($xls->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX);
$height = SharedXls::getDistanceY($xls->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY);
// calculate offsetX and offsetY of the shape
$offsetX = (int) ($startOffsetX * SharedXls::sizeCol($xls->phpSheet, $startColumn) / 1024);
$offsetY = (int) ($startOffsetY * SharedXls::sizeRow($xls->phpSheet, $startRow) / 256);
/** @var int[] $obj */
switch ($obj['otObjType']) {
case 0x19:
// Note
if (isset($xls->cellNotes[$obj['idObjID']])) {
//$cellNote = $xls->cellNotes[$obj['idObjID']];
if (isset($xls->textObjects[$obj['idObjID']])) {
$textObject = $xls->textObjects[$obj['idObjID']];
$xls->cellNotes[$obj['idObjID']]['objTextData'] = $textObject; //* @phpstan-ignore-line
}
}
break;
case 0x08:
// picture
// get index to BSE entry (1-based)
/** @var int */
$BSEindex = $spContainer->getOPT(0x0104);
// If there is no BSE Index, we will fail here and other fields are not read.
// Fix by checking here.
// TODO: Why is there no BSE Index? Is this a new Office Version? Password protected field?
// More likely : a uncompatible picture
if (!$BSEindex) {
continue 2;
}
if ($escherWorkbook) {
/** @var BSE[] */
$BSECollection = $escherWorkbook->getDggContainerOrThrow()->getBstoreContainerOrThrow()->getBSECollection();
$BSE = $BSECollection[$BSEindex - 1];
$blipType = $BSE->getBlipType();
// need check because some blip types are not supported by Escher reader such as EMF
if ($blip = $BSE->getBlip()) {
$ih = imagecreatefromstring($blip->getData());
if ($ih !== false) {
$drawing = new MemoryDrawing();
$drawing->setImageResource($ih);
// width, height, offsetX, offsetY
$drawing->setResizeProportional(false);
$drawing->setWidth($width);
$drawing->setHeight($height);
$drawing->setOffsetX($offsetX);
$drawing->setOffsetY($offsetY);
switch ($blipType) {
case BSE::BLIPTYPE_JPEG:
$drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG);
$drawing->setMimeType(MemoryDrawing::MIMETYPE_JPEG);
break;
case BSE::BLIPTYPE_PNG:
imagealphablending($ih, false);
imagesavealpha($ih, true);
$drawing->setRenderingFunction(MemoryDrawing::RENDERING_PNG);
$drawing->setMimeType(MemoryDrawing::MIMETYPE_PNG);
break;
}
$drawing->setWorksheet($xls->phpSheet);
$drawing->setCoordinates($spContainer->getStartCoordinates());
}
}
}
break;
default:
// other object type
break;
}
}
}
// treat SHAREDFMLA records
if ($xls->version == self::XLS_BIFF8) {
foreach ($xls->sharedFormulaParts as $cell => $baseCell) {
/** @var int $row */
[$column, $row] = Coordinate::coordinateFromString($cell);
/** @var string $baseCell */
if ($xls->getReadFilter()->readCell($column, $row, $xls->phpSheet->getTitle())) {
/** @var string */
$temp = $xls->sharedFormulas[$baseCell];
$formula = $xls->getFormulaFromStructure($temp, $cell);
$xls->phpSheet->getCell($cell)->setValueExplicit('=' . $formula, DataType::TYPE_FORMULA);
}
}
}
if (!empty($xls->cellNotes)) {
foreach ($xls->cellNotes as $note => $noteDetails) {
/** @var array{author: string, cellRef: string, objTextData?: mixed[]} $noteDetails */
if (!isset($noteDetails['objTextData'])) {
if (isset($xls->textObjects[$note])) {
$textObject = $xls->textObjects[$note];
$noteDetails['objTextData'] = $textObject;
} else {
$noteDetails['objTextData']['text'] = '';
}
}
$cellAddress = str_replace('$', '', $noteDetails['cellRef']);
/** @var string */
$tempDetails = $noteDetails['objTextData']['text'];
$xls->phpSheet
->getComment($cellAddress)
->setAuthor($noteDetails['author'])
->setText(
$xls->parseRichText($tempDetails)
);
}
}
if ($selectedCells !== '') {
$xls->phpSheet->setSelectedCells($selectedCells);
}
}
if ($xls->createBlankSheetIfNoneRead && !$sheetCreated) {
$xls->spreadsheet->createSheet();
}
if ($xls->activeSheetSet === false) {
$xls->spreadsheet->setActiveSheetIndex(0);
}
// add the named ranges (defined names)
foreach ($xls->definedname as $definedName) {
/** @var array{isBuiltInName: int, name: string, formula: string, scope: int} $definedName */
if ($definedName['isBuiltInName']) {
switch ($definedName['name']) {
case pack('C', 0x06):
// print area
// in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2
$ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma?
$extractedRanges = [];
$sheetName = '';
/** @var non-empty-string $range */
foreach ($ranges as $range) {
// $range should look like one of these
// Foo!$C$7:$J$66
// Bar!$A$1:$IV$2
$explodes = Worksheet::extractSheetTitle($range, true, true);
$sheetName = (string) $explodes[0];
if (!str_contains($explodes[1], ':')) {
$explodes[1] = $explodes[1] . ':' . $explodes[1];
}
$extractedRanges[] = str_replace('$', '', $explodes[1]); // C7:J66
}
if ($docSheet = $xls->spreadsheet->getSheetByName($sheetName)) {
$docSheet->getPageSetup()->setPrintArea(implode(',', $extractedRanges)); // C7:J66,A1:IV2
}
break;
case pack('C', 0x07):
// print titles (repeating rows)
// Assuming BIFF8, there are 3 cases
// 1. repeating rows
// formula looks like this: Sheet!$A$1:$IV$2
// rows 1-2 repeat
// 2. repeating columns
// formula looks like this: Sheet!$A$1:$B$65536
// columns A-B repeat
// 3. both repeating rows and repeating columns
// formula looks like this: Sheet!$A$1:$B$65536,Sheet!$A$1:$IV$2
$ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma?
foreach ($ranges as $range) {
// $range should look like this one of these
// Sheet!$A$1:$B$65536
// Sheet!$A$1:$IV$2
if (str_contains($range, '!')) {
$explodes = Worksheet::extractSheetTitle($range, true, true);
$docSheet = $xls->spreadsheet->getSheetByName($explodes[0]);
if ($docSheet) {
$extractedRange = $explodes[1];
$extractedRange = str_replace('$', '', $extractedRange);
$coordinateStrings = explode(':', $extractedRange);
if (count($coordinateStrings) == 2) {
[$firstColumn, $firstRow] = Coordinate::coordinateFromString($coordinateStrings[0]);
[$lastColumn, $lastRow] = Coordinate::coordinateFromString($coordinateStrings[1]);
$firstRow = (int) $firstRow;
$lastRow = (int) $lastRow;
if ($firstColumn == 'A' && $lastColumn == 'IV') {
// then we have repeating rows
$docSheet->getPageSetup()->setRowsToRepeatAtTop([$firstRow, $lastRow]);
} elseif ($firstRow == 1 && $lastRow == 65536) {
// then we have repeating columns
$docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$firstColumn, $lastColumn]);
}
}
}
}
}
break;
}
} else {
// Extract range
$formula = $definedName['formula'];
if (str_contains($formula, '!')) {
$explodes = Worksheet::extractSheetTitle($formula, true, true);
$docSheet = $xls->spreadsheet->getSheetByName($explodes[0]);
if ($docSheet) {
$extractedRange = $explodes[1];
$localOnly = ($definedName['scope'] === 0) ? false : true;
$scope = ($definedName['scope'] === 0) ? null : $xls->spreadsheet->getSheetByName($xls->sheets[$definedName['scope'] - 1]['name']);
$xls->spreadsheet->addNamedRange(new NamedRange((string) $definedName['name'], $docSheet, $extractedRange, $localOnly, $scope));
}
}
// Named Value
// TODO Provide support for named values
}
}
$xls->data = '';
return $xls->spreadsheet;
}
}
@@ -0,0 +1,198 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
class MD5
{
private int $a;
private int $b;
private int $c;
private int $d;
private static int $allOneBits;
/**
* MD5 stream constructor.
*/
public function __construct()
{
self::$allOneBits = self::signedInt(0xFFFFFFFF);
$this->reset();
}
/**
* Reset the MD5 stream context.
*/
public function reset(): void
{
$this->a = 0x67452301;
$this->b = self::signedInt(0xEFCDAB89);
$this->c = self::signedInt(0x98BADCFE);
$this->d = 0x10325476;
}
/**
* Get MD5 stream context.
*/
public function getContext(): string
{
$s = '';
foreach (['a', 'b', 'c', 'd'] as $i) {
$v = $this->{$i};
$s .= chr($v & 0xFF);
$s .= chr(($v >> 8) & 0xFF);
$s .= chr(($v >> 16) & 0xFF);
$s .= chr(($v >> 24) & 0xFF);
}
return $s;
}
/**
* Add data to context.
*
* @param string $data Data to add
*/
public function add(string $data): void
{
$unpacked = unpack('V16', $data) ?: throw new ReaderException('unable to unpack data');
/** @var int[] */
$words = array_values($unpacked);
$A = $this->a;
$B = $this->b;
$C = $this->c;
$D = $this->d;
$F = [self::class, 'f'];
$G = [self::class, 'g'];
$H = [self::class, 'h'];
$I = [self::class, 'i'];
// ROUND 1
self::step($F, $A, $B, $C, $D, $words[0], 7, 0xD76AA478);
self::step($F, $D, $A, $B, $C, $words[1], 12, 0xE8C7B756);
self::step($F, $C, $D, $A, $B, $words[2], 17, 0x242070DB);
self::step($F, $B, $C, $D, $A, $words[3], 22, 0xC1BDCEEE);
self::step($F, $A, $B, $C, $D, $words[4], 7, 0xF57C0FAF);
self::step($F, $D, $A, $B, $C, $words[5], 12, 0x4787C62A);
self::step($F, $C, $D, $A, $B, $words[6], 17, 0xA8304613);
self::step($F, $B, $C, $D, $A, $words[7], 22, 0xFD469501);
self::step($F, $A, $B, $C, $D, $words[8], 7, 0x698098D8);
self::step($F, $D, $A, $B, $C, $words[9], 12, 0x8B44F7AF);
self::step($F, $C, $D, $A, $B, $words[10], 17, 0xFFFF5BB1);
self::step($F, $B, $C, $D, $A, $words[11], 22, 0x895CD7BE);
self::step($F, $A, $B, $C, $D, $words[12], 7, 0x6B901122);
self::step($F, $D, $A, $B, $C, $words[13], 12, 0xFD987193);
self::step($F, $C, $D, $A, $B, $words[14], 17, 0xA679438E);
self::step($F, $B, $C, $D, $A, $words[15], 22, 0x49B40821);
// ROUND 2
self::step($G, $A, $B, $C, $D, $words[1], 5, 0xF61E2562);
self::step($G, $D, $A, $B, $C, $words[6], 9, 0xC040B340);
self::step($G, $C, $D, $A, $B, $words[11], 14, 0x265E5A51);
self::step($G, $B, $C, $D, $A, $words[0], 20, 0xE9B6C7AA);
self::step($G, $A, $B, $C, $D, $words[5], 5, 0xD62F105D);
self::step($G, $D, $A, $B, $C, $words[10], 9, 0x02441453);
self::step($G, $C, $D, $A, $B, $words[15], 14, 0xD8A1E681);
self::step($G, $B, $C, $D, $A, $words[4], 20, 0xE7D3FBC8);
self::step($G, $A, $B, $C, $D, $words[9], 5, 0x21E1CDE6);
self::step($G, $D, $A, $B, $C, $words[14], 9, 0xC33707D6);
self::step($G, $C, $D, $A, $B, $words[3], 14, 0xF4D50D87);
self::step($G, $B, $C, $D, $A, $words[8], 20, 0x455A14ED);
self::step($G, $A, $B, $C, $D, $words[13], 5, 0xA9E3E905);
self::step($G, $D, $A, $B, $C, $words[2], 9, 0xFCEFA3F8);
self::step($G, $C, $D, $A, $B, $words[7], 14, 0x676F02D9);
self::step($G, $B, $C, $D, $A, $words[12], 20, 0x8D2A4C8A);
// ROUND 3
self::step($H, $A, $B, $C, $D, $words[5], 4, 0xFFFA3942);
self::step($H, $D, $A, $B, $C, $words[8], 11, 0x8771F681);
self::step($H, $C, $D, $A, $B, $words[11], 16, 0x6D9D6122);
self::step($H, $B, $C, $D, $A, $words[14], 23, 0xFDE5380C);
self::step($H, $A, $B, $C, $D, $words[1], 4, 0xA4BEEA44);
self::step($H, $D, $A, $B, $C, $words[4], 11, 0x4BDECFA9);
self::step($H, $C, $D, $A, $B, $words[7], 16, 0xF6BB4B60);
self::step($H, $B, $C, $D, $A, $words[10], 23, 0xBEBFBC70);
self::step($H, $A, $B, $C, $D, $words[13], 4, 0x289B7EC6);
self::step($H, $D, $A, $B, $C, $words[0], 11, 0xEAA127FA);
self::step($H, $C, $D, $A, $B, $words[3], 16, 0xD4EF3085);
self::step($H, $B, $C, $D, $A, $words[6], 23, 0x04881D05);
self::step($H, $A, $B, $C, $D, $words[9], 4, 0xD9D4D039);
self::step($H, $D, $A, $B, $C, $words[12], 11, 0xE6DB99E5);
self::step($H, $C, $D, $A, $B, $words[15], 16, 0x1FA27CF8);
self::step($H, $B, $C, $D, $A, $words[2], 23, 0xC4AC5665);
// ROUND 4
self::step($I, $A, $B, $C, $D, $words[0], 6, 0xF4292244);
self::step($I, $D, $A, $B, $C, $words[7], 10, 0x432AFF97);
self::step($I, $C, $D, $A, $B, $words[14], 15, 0xAB9423A7);
self::step($I, $B, $C, $D, $A, $words[5], 21, 0xFC93A039);
self::step($I, $A, $B, $C, $D, $words[12], 6, 0x655B59C3);
self::step($I, $D, $A, $B, $C, $words[3], 10, 0x8F0CCC92);
self::step($I, $C, $D, $A, $B, $words[10], 15, 0xFFEFF47D);
self::step($I, $B, $C, $D, $A, $words[1], 21, 0x85845DD1);
self::step($I, $A, $B, $C, $D, $words[8], 6, 0x6FA87E4F);
self::step($I, $D, $A, $B, $C, $words[15], 10, 0xFE2CE6E0);
self::step($I, $C, $D, $A, $B, $words[6], 15, 0xA3014314);
self::step($I, $B, $C, $D, $A, $words[13], 21, 0x4E0811A1);
self::step($I, $A, $B, $C, $D, $words[4], 6, 0xF7537E82);
self::step($I, $D, $A, $B, $C, $words[11], 10, 0xBD3AF235);
self::step($I, $C, $D, $A, $B, $words[2], 15, 0x2AD7D2BB);
self::step($I, $B, $C, $D, $A, $words[9], 21, 0xEB86D391);
$this->a = ($this->a + $A) & self::$allOneBits;
$this->b = ($this->b + $B) & self::$allOneBits;
$this->c = ($this->c + $C) & self::$allOneBits;
$this->d = ($this->d + $D) & self::$allOneBits;
}
private static function f(int $X, int $Y, int $Z): int
{
return ($X & $Y) | ((~$X) & $Z); // X AND Y OR NOT X AND Z
}
private static function g(int $X, int $Y, int $Z): int
{
return ($X & $Z) | ($Y & (~$Z)); // X AND Z OR Y AND NOT Z
}
private static function h(int $X, int $Y, int $Z): int
{
return $X ^ $Y ^ $Z; // X XOR Y XOR Z
}
private static function i(int $X, int $Y, int $Z): int
{
return $Y ^ ($X | (~$Z)); // Y XOR (X OR NOT Z)
}
/** @param float|int $t may be float on 32-bit system */
private static function step(callable $func, int &$A, int $B, int $C, int $D, int $M, int $s, $t): void
{
$t = self::signedInt($t);
/** @var int */
$temp = call_user_func($func, $B, $C, $D);
$A = (int) ($A + $temp + $M + $t) & self::$allOneBits;
$A = self::rotate($A, $s);
$A = (int) ($B + $A) & self::$allOneBits;
}
/** @param float|int $result may be float on 32-bit system */
private static function signedInt($result): int
{
return is_int($result) ? $result : (int) (PHP_INT_MIN + $result - 1 - PHP_INT_MAX);
}
private static function rotate(int $decimal, int $bits): int
{
$binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT);
return self::signedInt(bindec(substr($binary, $bits) . substr($binary, 0, $bits)));
}
}
@@ -0,0 +1,271 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
class Mappings
{
/**
* Map tFunc values (functions with fixed number of arguments).
* Key is tFunc value.
* First element of array is Excel function name.
* Second element of array is number of arguments.
*/
const TFUNC_MAPPINGS = [
2 => ['ISNA', 1],
3 => ['ISERROR', 1],
10 => ['NA', 0],
15 => ['SIN', 1],
16 => ['COS', 1],
17 => ['TAN', 1],
18 => ['ATAN', 1],
19 => ['PI', 0],
20 => ['SQRT', 1],
21 => ['EXP', 1],
22 => ['LN', 1],
23 => ['LOG10', 1],
24 => ['ABS', 1],
25 => ['INT', 1],
26 => ['SIGN', 1],
27 => ['ROUND', 2],
30 => ['REPT', 2],
31 => ['MID', 3],
32 => ['LEN', 1],
33 => ['VALUE', 1],
34 => ['TRUE', 0],
35 => ['FALSE', 0],
38 => ['NOT', 1],
39 => ['MOD', 2],
40 => ['DCOUNT', 3],
41 => ['DSUM', 3],
42 => ['DAVERAGE', 3],
43 => ['DMIN', 3],
44 => ['DMAX', 3],
45 => ['DSTDEV', 3],
48 => ['TEXT', 2],
61 => ['MIRR', 3],
63 => ['RAND', 0],
65 => ['DATE', 3],
66 => ['TIME', 3],
67 => ['DAY', 1],
68 => ['MONTH', 1],
69 => ['YEAR', 1],
71 => ['HOUR', 1],
72 => ['MINUTE', 1],
73 => ['SECOND', 1],
74 => ['NOW', 0],
75 => ['AREAS', 1],
76 => ['ROWS', 1],
77 => ['COLUMNS', 1],
83 => ['TRANSPOSE', 1],
86 => ['TYPE', 1],
97 => ['ATAN2', 2],
98 => ['ASIN', 1],
99 => ['ACOS', 1],
105 => ['ISREF', 1],
111 => ['CHAR', 1],
112 => ['LOWER', 1],
113 => ['UPPER', 1],
114 => ['PROPER', 1],
117 => ['EXACT', 2],
118 => ['TRIM', 1],
119 => ['REPLACE', 4],
121 => ['CODE', 1],
126 => ['ISERR', 1],
127 => ['ISTEXT', 1],
128 => ['ISNUMBER', 1],
129 => ['ISBLANK', 1],
130 => ['T', 1],
131 => ['N', 1],
140 => ['DATEVALUE', 1],
141 => ['TIMEVALUE', 1],
142 => ['SLN', 3],
143 => ['SYD', 4],
162 => ['CLEAN', 1],
163 => ['MDETERM', 1],
164 => ['MINVERSE', 1],
165 => ['MMULT', 2],
184 => ['FACT', 1],
189 => ['DPRODUCT', 3],
190 => ['ISNONTEXT', 1],
195 => ['DSTDEVP', 3],
196 => ['DVARP', 3],
198 => ['ISLOGICAL', 1],
199 => ['DCOUNTA', 3],
207 => ['REPLACEB', 4],
210 => ['MIDB', 3],
211 => ['LENB', 1],
212 => ['ROUNDUP', 2],
213 => ['ROUNDDOWN', 2],
214 => ['ASC', 1],
215 => ['DBCS', 1],
221 => ['TODAY', 0],
229 => ['SINH', 1],
230 => ['COSH', 1],
231 => ['TANH', 1],
232 => ['ASINH', 1],
233 => ['ACOSH', 1],
234 => ['ATANH', 1],
235 => ['DGET', 3],
244 => ['INFO', 1],
252 => ['FREQUENCY', 2],
261 => ['ERROR.TYPE', 1],
271 => ['GAMMALN', 1],
273 => ['BINOMDIST', 4],
274 => ['CHIDIST', 2],
275 => ['CHIINV', 2],
276 => ['COMBIN', 2],
277 => ['CONFIDENCE', 3],
278 => ['CRITBINOM', 3],
279 => ['EVEN', 1],
280 => ['EXPONDIST', 3],
281 => ['FDIST', 3],
282 => ['FINV', 3],
283 => ['FISHER', 1],
284 => ['FISHERINV', 1],
285 => ['FLOOR', 2],
286 => ['GAMMADIST', 4],
287 => ['GAMMAINV', 3],
288 => ['CEILING', 2],
289 => ['HYPGEOMDIST', 4],
290 => ['LOGNORMDIST', 3],
291 => ['LOGINV', 3],
292 => ['NEGBINOMDIST', 3],
293 => ['NORMDIST', 4],
294 => ['NORMSDIST', 1],
295 => ['NORMINV', 3],
296 => ['NORMSINV', 1],
297 => ['STANDARDIZE', 3],
298 => ['ODD', 1],
299 => ['PERMUT', 2],
300 => ['POISSON', 3],
301 => ['TDIST', 3],
302 => ['WEIBULL', 4],
303 => ['SUMXMY2', 2],
304 => ['SUMX2MY2', 2],
305 => ['SUMX2PY2', 2],
306 => ['CHITEST', 2],
307 => ['CORREL', 2],
308 => ['COVAR', 2],
309 => ['FORECAST', 3],
310 => ['FTEST', 2],
311 => ['INTERCEPT', 2],
312 => ['PEARSON', 2],
313 => ['RSQ', 2],
314 => ['STEYX', 2],
315 => ['SLOPE', 2],
316 => ['TTEST', 4],
325 => ['LARGE', 2],
326 => ['SMALL', 2],
327 => ['QUARTILE', 2],
328 => ['PERCENTILE', 2],
331 => ['TRIMMEAN', 2],
332 => ['TINV', 2],
337 => ['POWER', 2],
342 => ['RADIANS', 1],
343 => ['DEGREES', 1],
346 => ['COUNTIF', 2],
347 => ['COUNTBLANK', 1],
350 => ['ISPMT', 4],
351 => ['DATEDIF', 3],
352 => ['DATESTRING', 1],
353 => ['NUMBERSTRING', 2],
360 => ['PHONETIC', 1],
368 => ['BAHTTEXT', 1],
];
/**
* Map tFuncV values (functions with variable number of arguments).
* Key is tFuncV value.
* Value is Excel function name.
*/
const TFUNCV_MAPPINGS = [
0 => 'COUNT',
1 => 'IF',
4 => 'SUM',
5 => 'AVERAGE',
6 => 'MIN',
7 => 'MAX',
8 => 'ROW',
9 => 'COLUMN',
11 => 'NPV',
12 => 'STDEV',
13 => 'DOLLAR',
14 => 'FIXED',
28 => 'LOOKUP',
29 => 'INDEX',
36 => 'AND',
37 => 'OR',
46 => 'VAR',
49 => 'LINEST',
50 => 'TREND',
51 => 'LOGEST',
52 => 'GROWTH',
56 => 'PV',
57 => 'FV',
58 => 'NPER',
59 => 'PMT',
60 => 'RATE',
62 => 'IRR',
64 => 'MATCH',
70 => 'WEEKDAY',
78 => 'OFFSET',
82 => 'SEARCH',
100 => 'CHOOSE',
101 => 'HLOOKUP',
102 => 'VLOOKUP',
109 => 'LOG',
115 => 'LEFT',
116 => 'RIGHT',
120 => 'SUBSTITUTE',
124 => 'FIND',
125 => 'CELL',
144 => 'DDB',
148 => 'INDIRECT',
167 => 'IPMT',
168 => 'PPMT',
169 => 'COUNTA',
183 => 'PRODUCT',
193 => 'STDEVP',
194 => 'VARP',
197 => 'TRUNC',
204 => 'USDOLLAR',
205 => 'FINDB',
206 => 'SEARCHB',
208 => 'LEFTB',
209 => 'RIGHTB',
216 => 'RANK',
219 => 'ADDRESS',
220 => 'DAYS360',
222 => 'VDB',
227 => 'MEDIAN',
228 => 'SUMPRODUCT',
247 => 'DB',
255 => '',
269 => 'AVEDEV',
270 => 'BETADIST',
272 => 'BETAINV',
317 => 'PROB',
318 => 'DEVSQ',
319 => 'GEOMEAN',
320 => 'HARMEAN',
321 => 'SUMSQ',
322 => 'KURT',
323 => 'SKEW',
324 => 'ZTEST',
329 => 'PERCENTRANK',
330 => 'MODE',
336 => 'CONCATENATE',
344 => 'SUBTOTAL',
345 => 'SUMIF',
354 => 'ROMAN',
358 => 'GETPIVOTDATA',
359 => 'HYPERLINK',
361 => 'AVERAGEA',
362 => 'MAXA',
363 => 'MINA',
364 => 'STDEVPA',
365 => 'VARPA',
366 => 'STDEVA',
367 => 'VARA',
];
}
@@ -0,0 +1,59 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
class RC4
{
/** @var int[] */
protected array $s = []; // Context
protected int $i = 0;
protected int $j = 0;
/**
* RC4 stream decryption/encryption constrcutor.
*
* @param string $key Encryption key/passphrase
*/
public function __construct(string $key)
{
$len = strlen($key);
for ($this->i = 0; $this->i < 256; ++$this->i) {
$this->s[$this->i] = $this->i;
}
$this->j = 0;
for ($this->i = 0; $this->i < 256; ++$this->i) {
$this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256;
$t = $this->s[$this->i];
$this->s[$this->i] = $this->s[$this->j];
$this->s[$this->j] = $t;
}
$this->i = $this->j = 0;
}
/**
* Symmetric decryption/encryption function.
*
* @param string $data Data to encrypt/decrypt
*/
public function RC4(string $data): string
{
$len = strlen($data);
for ($c = 0; $c < $len; ++$c) {
$this->i = ($this->i + 1) % 256;
$this->j = ($this->j + $this->s[$this->i]) % 256;
$t = $this->s[$this->i];
$this->s[$this->i] = $this->s[$this->j];
$this->s[$this->j] = $t;
$t = ($this->s[$this->i] + $this->s[$this->j]) % 256;
$data[$c] = chr(ord($data[$c]) ^ $this->s[$t]);
}
return $data;
}
}
@@ -0,0 +1,33 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Border as StyleBorder;
class Border
{
/**
* @var array<int, string>
*/
protected static array $borderStyleMap = [
0x00 => StyleBorder::BORDER_NONE,
0x01 => StyleBorder::BORDER_THIN,
0x02 => StyleBorder::BORDER_MEDIUM,
0x03 => StyleBorder::BORDER_DASHED,
0x04 => StyleBorder::BORDER_DOTTED,
0x05 => StyleBorder::BORDER_THICK,
0x06 => StyleBorder::BORDER_DOUBLE,
0x07 => StyleBorder::BORDER_HAIR,
0x08 => StyleBorder::BORDER_MEDIUMDASHED,
0x09 => StyleBorder::BORDER_DASHDOT,
0x0A => StyleBorder::BORDER_MEDIUMDASHDOT,
0x0B => StyleBorder::BORDER_DASHDOTDOT,
0x0C => StyleBorder::BORDER_MEDIUMDASHDOTDOT,
0x0D => StyleBorder::BORDER_SLANTDASHDOT,
];
public static function lookup(int $index): string
{
return self::$borderStyleMap[$index] ?? StyleBorder::BORDER_NONE;
}
}
@@ -0,0 +1,50 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
class CellAlignment
{
/**
* @var array<int, string>
*/
protected static array $horizontalAlignmentMap = [
0 => Alignment::HORIZONTAL_GENERAL,
1 => Alignment::HORIZONTAL_LEFT,
2 => Alignment::HORIZONTAL_CENTER,
3 => Alignment::HORIZONTAL_RIGHT,
4 => Alignment::HORIZONTAL_FILL,
5 => Alignment::HORIZONTAL_JUSTIFY,
6 => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
];
/**
* @var array<int, string>
*/
protected static array $verticalAlignmentMap = [
0 => Alignment::VERTICAL_TOP,
1 => Alignment::VERTICAL_CENTER,
2 => Alignment::VERTICAL_BOTTOM,
3 => Alignment::VERTICAL_JUSTIFY,
];
public static function horizontal(Alignment $alignment, int $horizontal): void
{
if (array_key_exists($horizontal, self::$horizontalAlignmentMap)) {
$alignment->setHorizontal(self::$horizontalAlignmentMap[$horizontal]);
}
}
public static function vertical(Alignment $alignment, int $vertical): void
{
if (array_key_exists($vertical, self::$verticalAlignmentMap)) {
$alignment->setVertical(self::$verticalAlignmentMap[$vertical]);
}
}
public static function wrap(Alignment $alignment, int $wrap): void
{
$alignment->setWrapText((bool) $wrap);
}
}
@@ -0,0 +1,39 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Font;
class CellFont
{
public static function escapement(Font $font, int $escapement): void
{
switch ($escapement) {
case 0x0001:
$font->setSuperscript(true);
break;
case 0x0002:
$font->setSubscript(true);
break;
}
}
/**
* @var array<int, string>
*/
protected static array $underlineMap = [
0x01 => Font::UNDERLINE_SINGLE,
0x02 => Font::UNDERLINE_DOUBLE,
0x21 => Font::UNDERLINE_SINGLEACCOUNTING,
0x22 => Font::UNDERLINE_DOUBLEACCOUNTING,
];
public static function underline(Font $font, int $underline): void
{
if (array_key_exists($underline, self::$underlineMap)) {
$font->setUnderline(self::$underlineMap[$underline]);
}
}
}
@@ -0,0 +1,42 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Fill;
class FillPattern
{
/**
* @var array<int, string>
*/
protected static array $fillPatternMap = [
0x00 => Fill::FILL_NONE,
0x01 => Fill::FILL_SOLID,
0x02 => Fill::FILL_PATTERN_MEDIUMGRAY,
0x03 => Fill::FILL_PATTERN_DARKGRAY,
0x04 => Fill::FILL_PATTERN_LIGHTGRAY,
0x05 => Fill::FILL_PATTERN_DARKHORIZONTAL,
0x06 => Fill::FILL_PATTERN_DARKVERTICAL,
0x07 => Fill::FILL_PATTERN_DARKDOWN,
0x08 => Fill::FILL_PATTERN_DARKUP,
0x09 => Fill::FILL_PATTERN_DARKGRID,
0x0A => Fill::FILL_PATTERN_DARKTRELLIS,
0x0B => Fill::FILL_PATTERN_LIGHTHORIZONTAL,
0x0C => Fill::FILL_PATTERN_LIGHTVERTICAL,
0x0D => Fill::FILL_PATTERN_LIGHTDOWN,
0x0E => Fill::FILL_PATTERN_LIGHTUP,
0x0F => Fill::FILL_PATTERN_LIGHTGRID,
0x10 => Fill::FILL_PATTERN_LIGHTTRELLIS,
0x11 => Fill::FILL_PATTERN_GRAY125,
0x12 => Fill::FILL_PATTERN_GRAY0625,
];
/**
* Get fill pattern from index
* OpenOffice documentation: 2.5.12.
*/
public static function lookup(int $index): string
{
return self::$fillPatternMap[$index] ?? Fill::FILL_NONE;
}
}